ash.c 300 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833
  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. * This code is derived from software contributed to Berkeley by
  12. * Kenneth Almquist.
  13. *
  14. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  15. *
  16. * Original BSD copyright notice is retained at the end of this file.
  17. */
  18. /*
  19. * rewrite arith.y to micro stack based cryptic algorithm by
  20. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  21. *
  22. * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
  23. * dynamic variables.
  24. *
  25. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
  26. * used in busybox and size optimizations,
  27. * rewrote arith (see notes to this), added locale support,
  28. * rewrote dynamic variables.
  29. */
  30. /*
  31. * The following should be set to reflect the type of system you have:
  32. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  33. * define SYSV if you are running under System V.
  34. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  35. * define DEBUG=2 to compile in and turn on debugging.
  36. *
  37. * When debugging is on, debugging info will be written to ./trace and
  38. * a quit signal will generate a core dump.
  39. */
  40. #define DEBUG 0
  41. /* Tweak debug output verbosity here */
  42. #define DEBUG_TIME 0
  43. #define DEBUG_PID 1
  44. #define DEBUG_SIG 1
  45. #define PROFILE 0
  46. #define IFS_BROKEN
  47. #define JOBS ENABLE_ASH_JOB_CONTROL
  48. #if DEBUG
  49. # ifndef _GNU_SOURCE
  50. # define _GNU_SOURCE
  51. # endif
  52. #endif
  53. #include "busybox.h" /* for applet_names */
  54. #include <paths.h>
  55. #include <setjmp.h>
  56. #include <fnmatch.h>
  57. #if JOBS || ENABLE_ASH_READ_NCHARS
  58. # include <termios.h>
  59. #endif
  60. #ifndef PIPE_BUF
  61. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  62. #endif
  63. #if defined(__uClinux__)
  64. # error "Do not even bother, ash will not run on uClinux"
  65. #endif
  66. /* ============ Hash table sizes. Configurable. */
  67. #define VTABSIZE 39
  68. #define ATABSIZE 39
  69. #define CMDTABLESIZE 31 /* should be prime */
  70. /* ============ Shell options */
  71. static const char *const optletters_optnames[] = {
  72. "e" "errexit",
  73. "f" "noglob",
  74. "I" "ignoreeof",
  75. "i" "interactive",
  76. "m" "monitor",
  77. "n" "noexec",
  78. "s" "stdin",
  79. "x" "xtrace",
  80. "v" "verbose",
  81. "C" "noclobber",
  82. "a" "allexport",
  83. "b" "notify",
  84. "u" "nounset",
  85. "\0" "vi"
  86. #if DEBUG
  87. ,"\0" "nolog"
  88. ,"\0" "debug"
  89. #endif
  90. };
  91. #define optletters(n) optletters_optnames[(n)][0]
  92. #define optnames(n) (&optletters_optnames[(n)][1])
  93. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  94. /* ============ Misc data */
  95. static const char homestr[] ALIGN1 = "HOME";
  96. static const char snlfmt[] ALIGN1 = "%s\n";
  97. static const char illnum[] ALIGN1 = "Illegal number: %s";
  98. /*
  99. * We enclose jmp_buf in a structure so that we can declare pointers to
  100. * jump locations. The global variable handler contains the location to
  101. * jump to when an exception occurs, and the global variable exception
  102. * contains a code identifying the exception. To implement nested
  103. * exception handlers, the user should save the value of handler on entry
  104. * to an inner scope, set handler to point to a jmploc structure for the
  105. * inner scope, and restore handler on exit from the scope.
  106. */
  107. struct jmploc {
  108. jmp_buf loc;
  109. };
  110. struct globals_misc {
  111. /* pid of main shell */
  112. int rootpid;
  113. /* shell level: 0 for the main shell, 1 for its children, and so on */
  114. int shlvl;
  115. #define rootshell (!shlvl)
  116. char *minusc; /* argument to -c option */
  117. char *curdir; // = nullstr; /* current working directory */
  118. char *physdir; // = nullstr; /* physical working directory */
  119. char *arg0; /* value of $0 */
  120. struct jmploc *exception_handler;
  121. // disabled by vda: cannot understand how it was supposed to work -
  122. // cannot fix bugs. That's why you have to explain your non-trivial designs!
  123. // /* do we generate EXSIG events */
  124. // int exsig; /* counter */
  125. volatile int suppressint; /* counter */
  126. volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
  127. /* last pending signal */
  128. volatile /*sig_atomic_t*/ smallint pendingsig;
  129. smallint exception; /* kind of exception (0..5) */
  130. /* exceptions */
  131. #define EXINT 0 /* SIGINT received */
  132. #define EXERROR 1 /* a generic error */
  133. #define EXSHELLPROC 2 /* execute a shell procedure */
  134. #define EXEXEC 3 /* command execution failed */
  135. #define EXEXIT 4 /* exit the shell */
  136. #define EXSIG 5 /* trapped signal in wait(1) */
  137. smallint isloginsh;
  138. char nullstr[1]; /* zero length string */
  139. char optlist[NOPTS];
  140. #define eflag optlist[0]
  141. #define fflag optlist[1]
  142. #define Iflag optlist[2]
  143. #define iflag optlist[3]
  144. #define mflag optlist[4]
  145. #define nflag optlist[5]
  146. #define sflag optlist[6]
  147. #define xflag optlist[7]
  148. #define vflag optlist[8]
  149. #define Cflag optlist[9]
  150. #define aflag optlist[10]
  151. #define bflag optlist[11]
  152. #define uflag optlist[12]
  153. #define viflag optlist[13]
  154. #if DEBUG
  155. #define nolog optlist[14]
  156. #define debug optlist[15]
  157. #endif
  158. /* trap handler commands */
  159. /*
  160. * Sigmode records the current value of the signal handlers for the various
  161. * modes. A value of zero means that the current handler is not known.
  162. * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  163. */
  164. char sigmode[NSIG - 1];
  165. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  166. #define S_CATCH 2 /* signal is caught */
  167. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  168. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  169. #define S_RESET 5 /* temporary - to reset a hard ignored sig */
  170. /* indicates specified signal received */
  171. char gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  172. char *trap[NSIG];
  173. /* Rarely referenced stuff */
  174. #if ENABLE_ASH_RANDOM_SUPPORT
  175. /* Random number generators */
  176. int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
  177. uint32_t random_LCG; /* LCG (fast but weak) */
  178. #endif
  179. pid_t backgndpid; /* pid of last background process */
  180. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  181. };
  182. extern struct globals_misc *const ash_ptr_to_globals_misc;
  183. #define G_misc (*ash_ptr_to_globals_misc)
  184. #define rootpid (G_misc.rootpid )
  185. #define shlvl (G_misc.shlvl )
  186. #define minusc (G_misc.minusc )
  187. #define curdir (G_misc.curdir )
  188. #define physdir (G_misc.physdir )
  189. #define arg0 (G_misc.arg0 )
  190. #define exception_handler (G_misc.exception_handler)
  191. #define exception (G_misc.exception )
  192. #define suppressint (G_misc.suppressint )
  193. #define intpending (G_misc.intpending )
  194. //#define exsig (G_misc.exsig )
  195. #define pendingsig (G_misc.pendingsig )
  196. #define isloginsh (G_misc.isloginsh )
  197. #define nullstr (G_misc.nullstr )
  198. #define optlist (G_misc.optlist )
  199. #define sigmode (G_misc.sigmode )
  200. #define gotsig (G_misc.gotsig )
  201. #define trap (G_misc.trap )
  202. #define random_galois_LFSR (G_misc.random_galois_LFSR)
  203. #define random_LCG (G_misc.random_LCG )
  204. #define backgndpid (G_misc.backgndpid )
  205. #define job_warning (G_misc.job_warning)
  206. #define INIT_G_misc() do { \
  207. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  208. barrier(); \
  209. curdir = nullstr; \
  210. physdir = nullstr; \
  211. } while (0)
  212. /* ============ DEBUG */
  213. #if DEBUG
  214. static void trace_printf(const char *fmt, ...);
  215. static void trace_vprintf(const char *fmt, va_list va);
  216. # define TRACE(param) trace_printf param
  217. # define TRACEV(param) trace_vprintf param
  218. # define close(f) do { \
  219. int dfd = (f); \
  220. if (close(dfd) < 0) \
  221. bb_error_msg("bug on %d: closing %d(%x)", \
  222. __LINE__, dfd, dfd); \
  223. } while (0)
  224. #else
  225. # define TRACE(param)
  226. # define TRACEV(param)
  227. #endif
  228. /* ============ Utility functions */
  229. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  230. /* C99 say: "char" declaration may be signed or unsigned by default */
  231. #define signed_char2int(sc) ((int)(signed char)(sc))
  232. static int isdigit_str9(const char *str)
  233. {
  234. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  235. while (--maxlen && isdigit(*str))
  236. str++;
  237. return (*str == '\0');
  238. }
  239. /* ============ Interrupts / exceptions */
  240. /*
  241. * These macros allow the user to suspend the handling of interrupt signals
  242. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  243. * much more efficient and portable. (But hacking the kernel is so much
  244. * more fun than worrying about efficiency and portability. :-))
  245. */
  246. #define INT_OFF do { \
  247. suppressint++; \
  248. xbarrier(); \
  249. } while (0)
  250. /*
  251. * Called to raise an exception. Since C doesn't include exceptions, we
  252. * just do a longjmp to the exception handler. The type of exception is
  253. * stored in the global variable "exception".
  254. */
  255. static void raise_exception(int) NORETURN;
  256. static void
  257. raise_exception(int e)
  258. {
  259. #if DEBUG
  260. if (exception_handler == NULL)
  261. abort();
  262. #endif
  263. INT_OFF;
  264. exception = e;
  265. longjmp(exception_handler->loc, 1);
  266. }
  267. #if DEBUG
  268. #define raise_exception(e) do { \
  269. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  270. raise_exception(e); \
  271. } while (0)
  272. #endif
  273. /*
  274. * Called from trap.c when a SIGINT is received. (If the user specifies
  275. * that SIGINT is to be trapped or ignored using the trap builtin, then
  276. * this routine is not called.) Suppressint is nonzero when interrupts
  277. * are held using the INT_OFF macro. (The test for iflag is just
  278. * defensive programming.)
  279. */
  280. static void raise_interrupt(void) NORETURN;
  281. static void
  282. raise_interrupt(void)
  283. {
  284. int i;
  285. intpending = 0;
  286. /* Signal is not automatically unmasked after it is raised,
  287. * do it ourself - unmask all signals */
  288. sigprocmask_allsigs(SIG_UNBLOCK);
  289. /* pendingsig = 0; - now done in onsig() */
  290. i = EXSIG;
  291. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  292. if (!(rootshell && iflag)) {
  293. /* Kill ourself with SIGINT */
  294. signal(SIGINT, SIG_DFL);
  295. raise(SIGINT);
  296. }
  297. i = EXINT;
  298. }
  299. raise_exception(i);
  300. /* NOTREACHED */
  301. }
  302. #if DEBUG
  303. #define raise_interrupt() do { \
  304. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  305. raise_interrupt(); \
  306. } while (0)
  307. #endif
  308. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  309. static void
  310. int_on(void)
  311. {
  312. if (--suppressint == 0 && intpending) {
  313. raise_interrupt();
  314. }
  315. }
  316. #define INT_ON int_on()
  317. static void
  318. force_int_on(void)
  319. {
  320. suppressint = 0;
  321. if (intpending)
  322. raise_interrupt();
  323. }
  324. #define FORCE_INT_ON force_int_on()
  325. #else /* !ASH_OPTIMIZE_FOR_SIZE */
  326. #define INT_ON do { \
  327. xbarrier(); \
  328. if (--suppressint == 0 && intpending) \
  329. raise_interrupt(); \
  330. } while (0)
  331. #define FORCE_INT_ON do { \
  332. xbarrier(); \
  333. suppressint = 0; \
  334. if (intpending) \
  335. raise_interrupt(); \
  336. } while (0)
  337. #endif /* !ASH_OPTIMIZE_FOR_SIZE */
  338. #define SAVE_INT(v) ((v) = suppressint)
  339. #define RESTORE_INT(v) do { \
  340. xbarrier(); \
  341. suppressint = (v); \
  342. if (suppressint == 0 && intpending) \
  343. raise_interrupt(); \
  344. } while (0)
  345. /*
  346. * Ignore a signal. Only one usage site - in forkchild()
  347. */
  348. static void
  349. ignoresig(int signo)
  350. {
  351. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  352. signal(signo, SIG_IGN);
  353. }
  354. sigmode[signo - 1] = S_HARD_IGN;
  355. }
  356. /*
  357. * Signal handler. Only one usage site - in setsignal()
  358. */
  359. static void
  360. onsig(int signo)
  361. {
  362. gotsig[signo - 1] = 1;
  363. if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
  364. if (!suppressint) {
  365. pendingsig = 0;
  366. raise_interrupt(); /* does not return */
  367. }
  368. intpending = 1;
  369. } else {
  370. pendingsig = signo;
  371. }
  372. }
  373. /* ============ Stdout/stderr output */
  374. static void
  375. outstr(const char *p, FILE *file)
  376. {
  377. INT_OFF;
  378. fputs(p, file);
  379. INT_ON;
  380. }
  381. static void
  382. flush_stdout_stderr(void)
  383. {
  384. INT_OFF;
  385. fflush(stdout);
  386. fflush(stderr);
  387. INT_ON;
  388. }
  389. static void
  390. flush_stderr(void)
  391. {
  392. INT_OFF;
  393. fflush(stderr);
  394. INT_ON;
  395. }
  396. static void
  397. outcslow(int c, FILE *dest)
  398. {
  399. INT_OFF;
  400. putc(c, dest);
  401. fflush(dest);
  402. INT_ON;
  403. }
  404. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  405. static int
  406. out1fmt(const char *fmt, ...)
  407. {
  408. va_list ap;
  409. int r;
  410. INT_OFF;
  411. va_start(ap, fmt);
  412. r = vprintf(fmt, ap);
  413. va_end(ap);
  414. INT_ON;
  415. return r;
  416. }
  417. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  418. static int
  419. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  420. {
  421. va_list ap;
  422. int ret;
  423. va_start(ap, fmt);
  424. INT_OFF;
  425. ret = vsnprintf(outbuf, length, fmt, ap);
  426. va_end(ap);
  427. INT_ON;
  428. return ret;
  429. }
  430. static void
  431. out1str(const char *p)
  432. {
  433. outstr(p, stdout);
  434. }
  435. static void
  436. out2str(const char *p)
  437. {
  438. outstr(p, stderr);
  439. flush_stderr();
  440. }
  441. /* ============ Parser structures */
  442. /* control characters in argument strings */
  443. #define CTLESC '\201' /* escape next character */
  444. #define CTLVAR '\202' /* variable defn */
  445. #define CTLENDVAR '\203'
  446. #define CTLBACKQ '\204'
  447. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  448. /* CTLBACKQ | CTLQUOTE == '\205' */
  449. #define CTLARI '\206' /* arithmetic expression */
  450. #define CTLENDARI '\207'
  451. #define CTLQUOTEMARK '\210'
  452. /* variable substitution byte (follows CTLVAR) */
  453. #define VSTYPE 0x0f /* type of variable substitution */
  454. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  455. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  456. /* values of VSTYPE field */
  457. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  458. #define VSMINUS 0x2 /* ${var-text} */
  459. #define VSPLUS 0x3 /* ${var+text} */
  460. #define VSQUESTION 0x4 /* ${var?message} */
  461. #define VSASSIGN 0x5 /* ${var=text} */
  462. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  463. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  464. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  465. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  466. #define VSLENGTH 0xa /* ${#var} */
  467. #if ENABLE_ASH_BASH_COMPAT
  468. #define VSSUBSTR 0xc /* ${var:position:length} */
  469. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  470. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  471. #endif
  472. static const char dolatstr[] ALIGN1 = {
  473. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  474. };
  475. #define NCMD 0
  476. #define NPIPE 1
  477. #define NREDIR 2
  478. #define NBACKGND 3
  479. #define NSUBSHELL 4
  480. #define NAND 5
  481. #define NOR 6
  482. #define NSEMI 7
  483. #define NIF 8
  484. #define NWHILE 9
  485. #define NUNTIL 10
  486. #define NFOR 11
  487. #define NCASE 12
  488. #define NCLIST 13
  489. #define NDEFUN 14
  490. #define NARG 15
  491. #define NTO 16
  492. #if ENABLE_ASH_BASH_COMPAT
  493. #define NTO2 17
  494. #endif
  495. #define NCLOBBER 18
  496. #define NFROM 19
  497. #define NFROMTO 20
  498. #define NAPPEND 21
  499. #define NTOFD 22
  500. #define NFROMFD 23
  501. #define NHERE 24
  502. #define NXHERE 25
  503. #define NNOT 26
  504. #define N_NUMBER 27
  505. union node;
  506. struct ncmd {
  507. smallint type; /* Nxxxx */
  508. union node *assign;
  509. union node *args;
  510. union node *redirect;
  511. };
  512. struct npipe {
  513. smallint type;
  514. smallint pipe_backgnd;
  515. struct nodelist *cmdlist;
  516. };
  517. struct nredir {
  518. smallint type;
  519. union node *n;
  520. union node *redirect;
  521. };
  522. struct nbinary {
  523. smallint type;
  524. union node *ch1;
  525. union node *ch2;
  526. };
  527. struct nif {
  528. smallint type;
  529. union node *test;
  530. union node *ifpart;
  531. union node *elsepart;
  532. };
  533. struct nfor {
  534. smallint type;
  535. union node *args;
  536. union node *body;
  537. char *var;
  538. };
  539. struct ncase {
  540. smallint type;
  541. union node *expr;
  542. union node *cases;
  543. };
  544. struct nclist {
  545. smallint type;
  546. union node *next;
  547. union node *pattern;
  548. union node *body;
  549. };
  550. struct narg {
  551. smallint type;
  552. union node *next;
  553. char *text;
  554. struct nodelist *backquote;
  555. };
  556. /* nfile and ndup layout must match!
  557. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  558. * that it is actually NTO2 (>&file), and change its type.
  559. */
  560. struct nfile {
  561. smallint type;
  562. union node *next;
  563. int fd;
  564. int _unused_dupfd;
  565. union node *fname;
  566. char *expfname;
  567. };
  568. struct ndup {
  569. smallint type;
  570. union node *next;
  571. int fd;
  572. int dupfd;
  573. union node *vname;
  574. char *_unused_expfname;
  575. };
  576. struct nhere {
  577. smallint type;
  578. union node *next;
  579. int fd;
  580. union node *doc;
  581. };
  582. struct nnot {
  583. smallint type;
  584. union node *com;
  585. };
  586. union node {
  587. smallint type;
  588. struct ncmd ncmd;
  589. struct npipe npipe;
  590. struct nredir nredir;
  591. struct nbinary nbinary;
  592. struct nif nif;
  593. struct nfor nfor;
  594. struct ncase ncase;
  595. struct nclist nclist;
  596. struct narg narg;
  597. struct nfile nfile;
  598. struct ndup ndup;
  599. struct nhere nhere;
  600. struct nnot nnot;
  601. };
  602. struct nodelist {
  603. struct nodelist *next;
  604. union node *n;
  605. };
  606. struct funcnode {
  607. int count;
  608. union node n;
  609. };
  610. /*
  611. * Free a parse tree.
  612. */
  613. static void
  614. freefunc(struct funcnode *f)
  615. {
  616. if (f && --f->count < 0)
  617. free(f);
  618. }
  619. /* ============ Debugging output */
  620. #if DEBUG
  621. static FILE *tracefile;
  622. static void
  623. trace_printf(const char *fmt, ...)
  624. {
  625. va_list va;
  626. if (debug != 1)
  627. return;
  628. if (DEBUG_TIME)
  629. fprintf(tracefile, "%u ", (int) time(NULL));
  630. if (DEBUG_PID)
  631. fprintf(tracefile, "[%u] ", (int) getpid());
  632. if (DEBUG_SIG)
  633. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
  634. va_start(va, fmt);
  635. vfprintf(tracefile, fmt, va);
  636. va_end(va);
  637. }
  638. static void
  639. trace_vprintf(const char *fmt, va_list va)
  640. {
  641. if (debug != 1)
  642. return;
  643. if (DEBUG_TIME)
  644. fprintf(tracefile, "%u ", (int) time(NULL));
  645. if (DEBUG_PID)
  646. fprintf(tracefile, "[%u] ", (int) getpid());
  647. if (DEBUG_SIG)
  648. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
  649. vfprintf(tracefile, fmt, va);
  650. }
  651. static void
  652. trace_puts(const char *s)
  653. {
  654. if (debug != 1)
  655. return;
  656. fputs(s, tracefile);
  657. }
  658. static void
  659. trace_puts_quoted(char *s)
  660. {
  661. char *p;
  662. char c;
  663. if (debug != 1)
  664. return;
  665. putc('"', tracefile);
  666. for (p = s; *p; p++) {
  667. switch (*p) {
  668. case '\n': c = 'n'; goto backslash;
  669. case '\t': c = 't'; goto backslash;
  670. case '\r': c = 'r'; goto backslash;
  671. case '"': c = '"'; goto backslash;
  672. case '\\': c = '\\'; goto backslash;
  673. case CTLESC: c = 'e'; goto backslash;
  674. case CTLVAR: c = 'v'; goto backslash;
  675. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  676. case CTLBACKQ: c = 'q'; goto backslash;
  677. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  678. backslash:
  679. putc('\\', tracefile);
  680. putc(c, tracefile);
  681. break;
  682. default:
  683. if (*p >= ' ' && *p <= '~')
  684. putc(*p, tracefile);
  685. else {
  686. putc('\\', tracefile);
  687. putc(*p >> 6 & 03, tracefile);
  688. putc(*p >> 3 & 07, tracefile);
  689. putc(*p & 07, tracefile);
  690. }
  691. break;
  692. }
  693. }
  694. putc('"', tracefile);
  695. }
  696. static void
  697. trace_puts_args(char **ap)
  698. {
  699. if (debug != 1)
  700. return;
  701. if (!*ap)
  702. return;
  703. while (1) {
  704. trace_puts_quoted(*ap);
  705. if (!*++ap) {
  706. putc('\n', tracefile);
  707. break;
  708. }
  709. putc(' ', tracefile);
  710. }
  711. }
  712. static void
  713. opentrace(void)
  714. {
  715. char s[100];
  716. #ifdef O_APPEND
  717. int flags;
  718. #endif
  719. if (debug != 1) {
  720. if (tracefile)
  721. fflush(tracefile);
  722. /* leave open because libedit might be using it */
  723. return;
  724. }
  725. strcpy(s, "./trace");
  726. if (tracefile) {
  727. if (!freopen(s, "a", tracefile)) {
  728. fprintf(stderr, "Can't re-open %s\n", s);
  729. debug = 0;
  730. return;
  731. }
  732. } else {
  733. tracefile = fopen(s, "a");
  734. if (tracefile == NULL) {
  735. fprintf(stderr, "Can't open %s\n", s);
  736. debug = 0;
  737. return;
  738. }
  739. }
  740. #ifdef O_APPEND
  741. flags = fcntl(fileno(tracefile), F_GETFL);
  742. if (flags >= 0)
  743. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  744. #endif
  745. setlinebuf(tracefile);
  746. fputs("\nTracing started.\n", tracefile);
  747. }
  748. static void
  749. indent(int amount, char *pfx, FILE *fp)
  750. {
  751. int i;
  752. for (i = 0; i < amount; i++) {
  753. if (pfx && i == amount - 1)
  754. fputs(pfx, fp);
  755. putc('\t', fp);
  756. }
  757. }
  758. /* little circular references here... */
  759. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  760. static void
  761. sharg(union node *arg, FILE *fp)
  762. {
  763. char *p;
  764. struct nodelist *bqlist;
  765. int subtype;
  766. if (arg->type != NARG) {
  767. out1fmt("<node type %d>\n", arg->type);
  768. abort();
  769. }
  770. bqlist = arg->narg.backquote;
  771. for (p = arg->narg.text; *p; p++) {
  772. switch (*p) {
  773. case CTLESC:
  774. putc(*++p, fp);
  775. break;
  776. case CTLVAR:
  777. putc('$', fp);
  778. putc('{', fp);
  779. subtype = *++p;
  780. if (subtype == VSLENGTH)
  781. putc('#', fp);
  782. while (*p != '=')
  783. putc(*p++, fp);
  784. if (subtype & VSNUL)
  785. putc(':', fp);
  786. switch (subtype & VSTYPE) {
  787. case VSNORMAL:
  788. putc('}', fp);
  789. break;
  790. case VSMINUS:
  791. putc('-', fp);
  792. break;
  793. case VSPLUS:
  794. putc('+', fp);
  795. break;
  796. case VSQUESTION:
  797. putc('?', fp);
  798. break;
  799. case VSASSIGN:
  800. putc('=', fp);
  801. break;
  802. case VSTRIMLEFT:
  803. putc('#', fp);
  804. break;
  805. case VSTRIMLEFTMAX:
  806. putc('#', fp);
  807. putc('#', fp);
  808. break;
  809. case VSTRIMRIGHT:
  810. putc('%', fp);
  811. break;
  812. case VSTRIMRIGHTMAX:
  813. putc('%', fp);
  814. putc('%', fp);
  815. break;
  816. case VSLENGTH:
  817. break;
  818. default:
  819. out1fmt("<subtype %d>", subtype);
  820. }
  821. break;
  822. case CTLENDVAR:
  823. putc('}', fp);
  824. break;
  825. case CTLBACKQ:
  826. case CTLBACKQ|CTLQUOTE:
  827. putc('$', fp);
  828. putc('(', fp);
  829. shtree(bqlist->n, -1, NULL, fp);
  830. putc(')', fp);
  831. break;
  832. default:
  833. putc(*p, fp);
  834. break;
  835. }
  836. }
  837. }
  838. static void
  839. shcmd(union node *cmd, FILE *fp)
  840. {
  841. union node *np;
  842. int first;
  843. const char *s;
  844. int dftfd;
  845. first = 1;
  846. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  847. if (!first)
  848. putc(' ', fp);
  849. sharg(np, fp);
  850. first = 0;
  851. }
  852. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  853. if (!first)
  854. putc(' ', fp);
  855. dftfd = 0;
  856. switch (np->nfile.type) {
  857. case NTO: s = ">>"+1; dftfd = 1; break;
  858. case NCLOBBER: s = ">|"; dftfd = 1; break;
  859. case NAPPEND: s = ">>"; dftfd = 1; break;
  860. #if ENABLE_ASH_BASH_COMPAT
  861. case NTO2:
  862. #endif
  863. case NTOFD: s = ">&"; dftfd = 1; break;
  864. case NFROM: s = "<"; break;
  865. case NFROMFD: s = "<&"; break;
  866. case NFROMTO: s = "<>"; break;
  867. default: s = "*error*"; break;
  868. }
  869. if (np->nfile.fd != dftfd)
  870. fprintf(fp, "%d", np->nfile.fd);
  871. fputs(s, fp);
  872. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  873. fprintf(fp, "%d", np->ndup.dupfd);
  874. } else {
  875. sharg(np->nfile.fname, fp);
  876. }
  877. first = 0;
  878. }
  879. }
  880. static void
  881. shtree(union node *n, int ind, char *pfx, FILE *fp)
  882. {
  883. struct nodelist *lp;
  884. const char *s;
  885. if (n == NULL)
  886. return;
  887. indent(ind, pfx, fp);
  888. switch (n->type) {
  889. case NSEMI:
  890. s = "; ";
  891. goto binop;
  892. case NAND:
  893. s = " && ";
  894. goto binop;
  895. case NOR:
  896. s = " || ";
  897. binop:
  898. shtree(n->nbinary.ch1, ind, NULL, fp);
  899. /* if (ind < 0) */
  900. fputs(s, fp);
  901. shtree(n->nbinary.ch2, ind, NULL, fp);
  902. break;
  903. case NCMD:
  904. shcmd(n, fp);
  905. if (ind >= 0)
  906. putc('\n', fp);
  907. break;
  908. case NPIPE:
  909. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  910. shcmd(lp->n, fp);
  911. if (lp->next)
  912. fputs(" | ", fp);
  913. }
  914. if (n->npipe.pipe_backgnd)
  915. fputs(" &", fp);
  916. if (ind >= 0)
  917. putc('\n', fp);
  918. break;
  919. default:
  920. fprintf(fp, "<node type %d>", n->type);
  921. if (ind >= 0)
  922. putc('\n', fp);
  923. break;
  924. }
  925. }
  926. static void
  927. showtree(union node *n)
  928. {
  929. trace_puts("showtree called\n");
  930. shtree(n, 1, NULL, stdout);
  931. }
  932. #endif /* DEBUG */
  933. /* ============ Parser data */
  934. /*
  935. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  936. */
  937. struct strlist {
  938. struct strlist *next;
  939. char *text;
  940. };
  941. struct alias;
  942. struct strpush {
  943. struct strpush *prev; /* preceding string on stack */
  944. char *prevstring;
  945. int prevnleft;
  946. #if ENABLE_ASH_ALIAS
  947. struct alias *ap; /* if push was associated with an alias */
  948. #endif
  949. char *string; /* remember the string since it may change */
  950. };
  951. struct parsefile {
  952. struct parsefile *prev; /* preceding file on stack */
  953. int linno; /* current line */
  954. int fd; /* file descriptor (or -1 if string) */
  955. int nleft; /* number of chars left in this line */
  956. int lleft; /* number of chars left in this buffer */
  957. char *nextc; /* next char in buffer */
  958. char *buf; /* input buffer */
  959. struct strpush *strpush; /* for pushing strings at this level */
  960. struct strpush basestrpush; /* so pushing one is fast */
  961. };
  962. static struct parsefile basepf; /* top level input file */
  963. static struct parsefile *g_parsefile = &basepf; /* current input file */
  964. static int startlinno; /* line # where last token started */
  965. static char *commandname; /* currently executing command */
  966. static struct strlist *cmdenviron; /* environment for builtin command */
  967. static uint8_t exitstatus; /* exit status of last command */
  968. /* ============ Message printing */
  969. static void
  970. ash_vmsg(const char *msg, va_list ap)
  971. {
  972. fprintf(stderr, "%s: ", arg0);
  973. if (commandname) {
  974. if (strcmp(arg0, commandname))
  975. fprintf(stderr, "%s: ", commandname);
  976. if (!iflag || g_parsefile->fd)
  977. fprintf(stderr, "line %d: ", startlinno);
  978. }
  979. vfprintf(stderr, msg, ap);
  980. outcslow('\n', stderr);
  981. }
  982. /*
  983. * Exverror is called to raise the error exception. If the second argument
  984. * is not NULL then error prints an error message using printf style
  985. * formatting. It then raises the error exception.
  986. */
  987. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  988. static void
  989. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  990. {
  991. #if DEBUG
  992. if (msg) {
  993. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  994. TRACEV((msg, ap));
  995. TRACE(("\") pid=%d\n", getpid()));
  996. } else
  997. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  998. if (msg)
  999. #endif
  1000. ash_vmsg(msg, ap);
  1001. flush_stdout_stderr();
  1002. raise_exception(cond);
  1003. /* NOTREACHED */
  1004. }
  1005. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1006. static void
  1007. ash_msg_and_raise_error(const char *msg, ...)
  1008. {
  1009. va_list ap;
  1010. va_start(ap, msg);
  1011. ash_vmsg_and_raise(EXERROR, msg, ap);
  1012. /* NOTREACHED */
  1013. va_end(ap);
  1014. }
  1015. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1016. static void
  1017. ash_msg_and_raise(int cond, const char *msg, ...)
  1018. {
  1019. va_list ap;
  1020. va_start(ap, msg);
  1021. ash_vmsg_and_raise(cond, msg, ap);
  1022. /* NOTREACHED */
  1023. va_end(ap);
  1024. }
  1025. /*
  1026. * error/warning routines for external builtins
  1027. */
  1028. static void
  1029. ash_msg(const char *fmt, ...)
  1030. {
  1031. va_list ap;
  1032. va_start(ap, fmt);
  1033. ash_vmsg(fmt, ap);
  1034. va_end(ap);
  1035. }
  1036. /*
  1037. * Return a string describing an error. The returned string may be a
  1038. * pointer to a static buffer that will be overwritten on the next call.
  1039. * Action describes the operation that got the error.
  1040. */
  1041. static const char *
  1042. errmsg(int e, const char *em)
  1043. {
  1044. if (e == ENOENT || e == ENOTDIR) {
  1045. return em;
  1046. }
  1047. return strerror(e);
  1048. }
  1049. /* ============ Memory allocation */
  1050. /*
  1051. * It appears that grabstackstr() will barf with such alignments
  1052. * because stalloc() will return a string allocated in a new stackblock.
  1053. */
  1054. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1055. enum {
  1056. /* Most machines require the value returned from malloc to be aligned
  1057. * in some way. The following macro will get this right
  1058. * on many machines. */
  1059. SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
  1060. /* Minimum size of a block */
  1061. MINSIZE = SHELL_ALIGN(504),
  1062. };
  1063. struct stack_block {
  1064. struct stack_block *prev;
  1065. char space[MINSIZE];
  1066. };
  1067. struct stackmark {
  1068. struct stack_block *stackp;
  1069. char *stacknxt;
  1070. size_t stacknleft;
  1071. struct stackmark *marknext;
  1072. };
  1073. struct globals_memstack {
  1074. struct stack_block *g_stackp; // = &stackbase;
  1075. struct stackmark *markp;
  1076. char *g_stacknxt; // = stackbase.space;
  1077. char *sstrend; // = stackbase.space + MINSIZE;
  1078. size_t g_stacknleft; // = MINSIZE;
  1079. int herefd; // = -1;
  1080. struct stack_block stackbase;
  1081. };
  1082. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1083. #define G_memstack (*ash_ptr_to_globals_memstack)
  1084. #define g_stackp (G_memstack.g_stackp )
  1085. #define markp (G_memstack.markp )
  1086. #define g_stacknxt (G_memstack.g_stacknxt )
  1087. #define sstrend (G_memstack.sstrend )
  1088. #define g_stacknleft (G_memstack.g_stacknleft)
  1089. #define herefd (G_memstack.herefd )
  1090. #define stackbase (G_memstack.stackbase )
  1091. #define INIT_G_memstack() do { \
  1092. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1093. barrier(); \
  1094. g_stackp = &stackbase; \
  1095. g_stacknxt = stackbase.space; \
  1096. g_stacknleft = MINSIZE; \
  1097. sstrend = stackbase.space + MINSIZE; \
  1098. herefd = -1; \
  1099. } while (0)
  1100. #define stackblock() ((void *)g_stacknxt)
  1101. #define stackblocksize() g_stacknleft
  1102. static void *
  1103. ckrealloc(void * p, size_t nbytes)
  1104. {
  1105. p = realloc(p, nbytes);
  1106. if (!p)
  1107. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1108. return p;
  1109. }
  1110. static void *
  1111. ckmalloc(size_t nbytes)
  1112. {
  1113. return ckrealloc(NULL, nbytes);
  1114. }
  1115. static void *
  1116. ckzalloc(size_t nbytes)
  1117. {
  1118. return memset(ckmalloc(nbytes), 0, nbytes);
  1119. }
  1120. /*
  1121. * Make a copy of a string in safe storage.
  1122. */
  1123. static char *
  1124. ckstrdup(const char *s)
  1125. {
  1126. char *p = strdup(s);
  1127. if (!p)
  1128. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1129. return p;
  1130. }
  1131. /*
  1132. * Parse trees for commands are allocated in lifo order, so we use a stack
  1133. * to make this more efficient, and also to avoid all sorts of exception
  1134. * handling code to handle interrupts in the middle of a parse.
  1135. *
  1136. * The size 504 was chosen because the Ultrix malloc handles that size
  1137. * well.
  1138. */
  1139. static void *
  1140. stalloc(size_t nbytes)
  1141. {
  1142. char *p;
  1143. size_t aligned;
  1144. aligned = SHELL_ALIGN(nbytes);
  1145. if (aligned > g_stacknleft) {
  1146. size_t len;
  1147. size_t blocksize;
  1148. struct stack_block *sp;
  1149. blocksize = aligned;
  1150. if (blocksize < MINSIZE)
  1151. blocksize = MINSIZE;
  1152. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1153. if (len < blocksize)
  1154. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1155. INT_OFF;
  1156. sp = ckmalloc(len);
  1157. sp->prev = g_stackp;
  1158. g_stacknxt = sp->space;
  1159. g_stacknleft = blocksize;
  1160. sstrend = g_stacknxt + blocksize;
  1161. g_stackp = sp;
  1162. INT_ON;
  1163. }
  1164. p = g_stacknxt;
  1165. g_stacknxt += aligned;
  1166. g_stacknleft -= aligned;
  1167. return p;
  1168. }
  1169. static void *
  1170. stzalloc(size_t nbytes)
  1171. {
  1172. return memset(stalloc(nbytes), 0, nbytes);
  1173. }
  1174. static void
  1175. stunalloc(void *p)
  1176. {
  1177. #if DEBUG
  1178. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1179. write(STDERR_FILENO, "stunalloc\n", 10);
  1180. abort();
  1181. }
  1182. #endif
  1183. g_stacknleft += g_stacknxt - (char *)p;
  1184. g_stacknxt = p;
  1185. }
  1186. /*
  1187. * Like strdup but works with the ash stack.
  1188. */
  1189. static char *
  1190. ststrdup(const char *p)
  1191. {
  1192. size_t len = strlen(p) + 1;
  1193. return memcpy(stalloc(len), p, len);
  1194. }
  1195. static void
  1196. setstackmark(struct stackmark *mark)
  1197. {
  1198. mark->stackp = g_stackp;
  1199. mark->stacknxt = g_stacknxt;
  1200. mark->stacknleft = g_stacknleft;
  1201. mark->marknext = markp;
  1202. markp = mark;
  1203. }
  1204. static void
  1205. popstackmark(struct stackmark *mark)
  1206. {
  1207. struct stack_block *sp;
  1208. if (!mark->stackp)
  1209. return;
  1210. INT_OFF;
  1211. markp = mark->marknext;
  1212. while (g_stackp != mark->stackp) {
  1213. sp = g_stackp;
  1214. g_stackp = sp->prev;
  1215. free(sp);
  1216. }
  1217. g_stacknxt = mark->stacknxt;
  1218. g_stacknleft = mark->stacknleft;
  1219. sstrend = mark->stacknxt + mark->stacknleft;
  1220. INT_ON;
  1221. }
  1222. /*
  1223. * When the parser reads in a string, it wants to stick the string on the
  1224. * stack and only adjust the stack pointer when it knows how big the
  1225. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1226. * of space on top of the stack and stackblocklen returns the length of
  1227. * this block. Growstackblock will grow this space by at least one byte,
  1228. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1229. * part of the block that has been used.
  1230. */
  1231. static void
  1232. growstackblock(void)
  1233. {
  1234. size_t newlen;
  1235. newlen = g_stacknleft * 2;
  1236. if (newlen < g_stacknleft)
  1237. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1238. if (newlen < 128)
  1239. newlen += 128;
  1240. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1241. struct stack_block *oldstackp;
  1242. struct stackmark *xmark;
  1243. struct stack_block *sp;
  1244. struct stack_block *prevstackp;
  1245. size_t grosslen;
  1246. INT_OFF;
  1247. oldstackp = g_stackp;
  1248. sp = g_stackp;
  1249. prevstackp = sp->prev;
  1250. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1251. sp = ckrealloc(sp, grosslen);
  1252. sp->prev = prevstackp;
  1253. g_stackp = sp;
  1254. g_stacknxt = sp->space;
  1255. g_stacknleft = newlen;
  1256. sstrend = sp->space + newlen;
  1257. /*
  1258. * Stack marks pointing to the start of the old block
  1259. * must be relocated to point to the new block
  1260. */
  1261. xmark = markp;
  1262. while (xmark != NULL && xmark->stackp == oldstackp) {
  1263. xmark->stackp = g_stackp;
  1264. xmark->stacknxt = g_stacknxt;
  1265. xmark->stacknleft = g_stacknleft;
  1266. xmark = xmark->marknext;
  1267. }
  1268. INT_ON;
  1269. } else {
  1270. char *oldspace = g_stacknxt;
  1271. size_t oldlen = g_stacknleft;
  1272. char *p = stalloc(newlen);
  1273. /* free the space we just allocated */
  1274. g_stacknxt = memcpy(p, oldspace, oldlen);
  1275. g_stacknleft += newlen;
  1276. }
  1277. }
  1278. static void
  1279. grabstackblock(size_t len)
  1280. {
  1281. len = SHELL_ALIGN(len);
  1282. g_stacknxt += len;
  1283. g_stacknleft -= len;
  1284. }
  1285. /*
  1286. * The following routines are somewhat easier to use than the above.
  1287. * The user declares a variable of type STACKSTR, which may be declared
  1288. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1289. * the user uses the macro STPUTC to add characters to the string. In
  1290. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1291. * grown as necessary. When the user is done, she can just leave the
  1292. * string there and refer to it using stackblock(). Or she can allocate
  1293. * the space for it using grabstackstr(). If it is necessary to allow
  1294. * someone else to use the stack temporarily and then continue to grow
  1295. * the string, the user should use grabstack to allocate the space, and
  1296. * then call ungrabstr(p) to return to the previous mode of operation.
  1297. *
  1298. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1299. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1300. * is space for at least one character.
  1301. */
  1302. static void *
  1303. growstackstr(void)
  1304. {
  1305. size_t len = stackblocksize();
  1306. if (herefd >= 0 && len >= 1024) {
  1307. full_write(herefd, stackblock(), len);
  1308. return stackblock();
  1309. }
  1310. growstackblock();
  1311. return (char *)stackblock() + len;
  1312. }
  1313. /*
  1314. * Called from CHECKSTRSPACE.
  1315. */
  1316. static char *
  1317. makestrspace(size_t newlen, char *p)
  1318. {
  1319. size_t len = p - g_stacknxt;
  1320. size_t size = stackblocksize();
  1321. for (;;) {
  1322. size_t nleft;
  1323. size = stackblocksize();
  1324. nleft = size - len;
  1325. if (nleft >= newlen)
  1326. break;
  1327. growstackblock();
  1328. }
  1329. return (char *)stackblock() + len;
  1330. }
  1331. static char *
  1332. stack_nputstr(const char *s, size_t n, char *p)
  1333. {
  1334. p = makestrspace(n, p);
  1335. p = (char *)memcpy(p, s, n) + n;
  1336. return p;
  1337. }
  1338. static char *
  1339. stack_putstr(const char *s, char *p)
  1340. {
  1341. return stack_nputstr(s, strlen(s), p);
  1342. }
  1343. static char *
  1344. _STPUTC(int c, char *p)
  1345. {
  1346. if (p == sstrend)
  1347. p = growstackstr();
  1348. *p++ = c;
  1349. return p;
  1350. }
  1351. #define STARTSTACKSTR(p) ((p) = stackblock())
  1352. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1353. #define CHECKSTRSPACE(n, p) do { \
  1354. char *q = (p); \
  1355. size_t l = (n); \
  1356. size_t m = sstrend - q; \
  1357. if (l > m) \
  1358. (p) = makestrspace(l, q); \
  1359. } while (0)
  1360. #define USTPUTC(c, p) (*(p)++ = (c))
  1361. #define STACKSTRNUL(p) do { \
  1362. if ((p) == sstrend) \
  1363. (p) = growstackstr(); \
  1364. *(p) = '\0'; \
  1365. } while (0)
  1366. #define STUNPUTC(p) (--(p))
  1367. #define STTOPC(p) ((p)[-1])
  1368. #define STADJUST(amount, p) ((p) += (amount))
  1369. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1370. #define ungrabstackstr(s, p) stunalloc(s)
  1371. #define stackstrend() ((void *)sstrend)
  1372. /* ============ String helpers */
  1373. /*
  1374. * prefix -- see if pfx is a prefix of string.
  1375. */
  1376. static char *
  1377. prefix(const char *string, const char *pfx)
  1378. {
  1379. while (*pfx) {
  1380. if (*pfx++ != *string++)
  1381. return NULL;
  1382. }
  1383. return (char *) string;
  1384. }
  1385. /*
  1386. * Check for a valid number. This should be elsewhere.
  1387. */
  1388. static int
  1389. is_number(const char *p)
  1390. {
  1391. do {
  1392. if (!isdigit(*p))
  1393. return 0;
  1394. } while (*++p != '\0');
  1395. return 1;
  1396. }
  1397. /*
  1398. * Convert a string of digits to an integer, printing an error message on
  1399. * failure.
  1400. */
  1401. static int
  1402. number(const char *s)
  1403. {
  1404. if (!is_number(s))
  1405. ash_msg_and_raise_error(illnum, s);
  1406. return atoi(s);
  1407. }
  1408. /*
  1409. * Produce a possibly single quoted string suitable as input to the shell.
  1410. * The return string is allocated on the stack.
  1411. */
  1412. static char *
  1413. single_quote(const char *s)
  1414. {
  1415. char *p;
  1416. STARTSTACKSTR(p);
  1417. do {
  1418. char *q;
  1419. size_t len;
  1420. len = strchrnul(s, '\'') - s;
  1421. q = p = makestrspace(len + 3, p);
  1422. *q++ = '\'';
  1423. q = (char *)memcpy(q, s, len) + len;
  1424. *q++ = '\'';
  1425. s += len;
  1426. STADJUST(q - p, p);
  1427. len = strspn(s, "'");
  1428. if (!len)
  1429. break;
  1430. q = p = makestrspace(len + 3, p);
  1431. *q++ = '"';
  1432. q = (char *)memcpy(q, s, len) + len;
  1433. *q++ = '"';
  1434. s += len;
  1435. STADJUST(q - p, p);
  1436. } while (*s);
  1437. USTPUTC(0, p);
  1438. return stackblock();
  1439. }
  1440. /* ============ nextopt */
  1441. static char **argptr; /* argument list for builtin commands */
  1442. static char *optionarg; /* set by nextopt (like getopt) */
  1443. static char *optptr; /* used by nextopt */
  1444. /*
  1445. * XXX - should get rid of. Have all builtins use getopt(3).
  1446. * The library getopt must have the BSD extension static variable
  1447. * "optreset", otherwise it can't be used within the shell safely.
  1448. *
  1449. * Standard option processing (a la getopt) for builtin routines.
  1450. * The only argument that is passed to nextopt is the option string;
  1451. * the other arguments are unnecessary. It returns the character,
  1452. * or '\0' on end of input.
  1453. */
  1454. static int
  1455. nextopt(const char *optstring)
  1456. {
  1457. char *p;
  1458. const char *q;
  1459. char c;
  1460. p = optptr;
  1461. if (p == NULL || *p == '\0') {
  1462. /* We ate entire "-param", take next one */
  1463. p = *argptr;
  1464. if (p == NULL)
  1465. return '\0';
  1466. if (*p != '-')
  1467. return '\0';
  1468. if (*++p == '\0') /* just "-" ? */
  1469. return '\0';
  1470. argptr++;
  1471. if (LONE_DASH(p)) /* "--" ? */
  1472. return '\0';
  1473. /* p => next "-param" */
  1474. }
  1475. /* p => some option char in the middle of a "-param" */
  1476. c = *p++;
  1477. for (q = optstring; *q != c;) {
  1478. if (*q == '\0')
  1479. ash_msg_and_raise_error("illegal option -%c", c);
  1480. if (*++q == ':')
  1481. q++;
  1482. }
  1483. if (*++q == ':') {
  1484. if (*p == '\0') {
  1485. p = *argptr++;
  1486. if (p == NULL)
  1487. ash_msg_and_raise_error("no arg for -%c option", c);
  1488. }
  1489. optionarg = p;
  1490. p = NULL;
  1491. }
  1492. optptr = p;
  1493. return c;
  1494. }
  1495. /* ============ Shell variables */
  1496. /*
  1497. * The parsefile structure pointed to by the global variable parsefile
  1498. * contains information about the current file being read.
  1499. */
  1500. struct shparam {
  1501. int nparam; /* # of positional parameters (without $0) */
  1502. #if ENABLE_ASH_GETOPTS
  1503. int optind; /* next parameter to be processed by getopts */
  1504. int optoff; /* used by getopts */
  1505. #endif
  1506. unsigned char malloced; /* if parameter list dynamically allocated */
  1507. char **p; /* parameter list */
  1508. };
  1509. /*
  1510. * Free the list of positional parameters.
  1511. */
  1512. static void
  1513. freeparam(volatile struct shparam *param)
  1514. {
  1515. if (param->malloced) {
  1516. char **ap, **ap1;
  1517. ap = ap1 = param->p;
  1518. while (*ap)
  1519. free(*ap++);
  1520. free(ap1);
  1521. }
  1522. }
  1523. #if ENABLE_ASH_GETOPTS
  1524. static void getoptsreset(const char *value);
  1525. #endif
  1526. struct var {
  1527. struct var *next; /* next entry in hash list */
  1528. int flags; /* flags are defined above */
  1529. const char *text; /* name=value */
  1530. void (*func)(const char *); /* function to be called when */
  1531. /* the variable gets set/unset */
  1532. };
  1533. struct localvar {
  1534. struct localvar *next; /* next local variable in list */
  1535. struct var *vp; /* the variable that was made local */
  1536. int flags; /* saved flags */
  1537. const char *text; /* saved text */
  1538. };
  1539. /* flags */
  1540. #define VEXPORT 0x01 /* variable is exported */
  1541. #define VREADONLY 0x02 /* variable cannot be modified */
  1542. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1543. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1544. #define VSTACK 0x10 /* text is allocated on the stack */
  1545. #define VUNSET 0x20 /* the variable is not set */
  1546. #define VNOFUNC 0x40 /* don't call the callback function */
  1547. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1548. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1549. #if ENABLE_ASH_RANDOM_SUPPORT
  1550. # define VDYNAMIC 0x200 /* dynamic variable */
  1551. #else
  1552. # define VDYNAMIC 0
  1553. #endif
  1554. #ifdef IFS_BROKEN
  1555. static const char defifsvar[] ALIGN1 = "IFS= \t\n";
  1556. #define defifs (defifsvar + 4)
  1557. #else
  1558. static const char defifs[] ALIGN1 = " \t\n";
  1559. #endif
  1560. /* Need to be before varinit_data[] */
  1561. #if ENABLE_LOCALE_SUPPORT
  1562. static void
  1563. change_lc_all(const char *value)
  1564. {
  1565. if (value && *value != '\0')
  1566. setlocale(LC_ALL, value);
  1567. }
  1568. static void
  1569. change_lc_ctype(const char *value)
  1570. {
  1571. if (value && *value != '\0')
  1572. setlocale(LC_CTYPE, value);
  1573. }
  1574. #endif
  1575. #if ENABLE_ASH_MAIL
  1576. static void chkmail(void);
  1577. static void changemail(const char *);
  1578. #endif
  1579. static void changepath(const char *);
  1580. #if ENABLE_ASH_RANDOM_SUPPORT
  1581. static void change_random(const char *);
  1582. #endif
  1583. static const struct {
  1584. int flags;
  1585. const char *text;
  1586. void (*func)(const char *);
  1587. } varinit_data[] = {
  1588. #ifdef IFS_BROKEN
  1589. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1590. #else
  1591. { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
  1592. #endif
  1593. #if ENABLE_ASH_MAIL
  1594. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
  1595. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1596. #endif
  1597. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1598. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1599. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1600. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1601. #if ENABLE_ASH_GETOPTS
  1602. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1603. #endif
  1604. #if ENABLE_ASH_RANDOM_SUPPORT
  1605. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1606. #endif
  1607. #if ENABLE_LOCALE_SUPPORT
  1608. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
  1609. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1610. #endif
  1611. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1612. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
  1613. #endif
  1614. };
  1615. struct redirtab;
  1616. struct globals_var {
  1617. struct shparam shellparam; /* $@ current positional parameters */
  1618. struct redirtab *redirlist;
  1619. int g_nullredirs;
  1620. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1621. struct var *vartab[VTABSIZE];
  1622. struct var varinit[ARRAY_SIZE(varinit_data)];
  1623. };
  1624. extern struct globals_var *const ash_ptr_to_globals_var;
  1625. #define G_var (*ash_ptr_to_globals_var)
  1626. #define shellparam (G_var.shellparam )
  1627. //#define redirlist (G_var.redirlist )
  1628. #define g_nullredirs (G_var.g_nullredirs )
  1629. #define preverrout_fd (G_var.preverrout_fd)
  1630. #define vartab (G_var.vartab )
  1631. #define varinit (G_var.varinit )
  1632. #define INIT_G_var() do { \
  1633. unsigned i; \
  1634. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1635. barrier(); \
  1636. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1637. varinit[i].flags = varinit_data[i].flags; \
  1638. varinit[i].text = varinit_data[i].text; \
  1639. varinit[i].func = varinit_data[i].func; \
  1640. } \
  1641. } while (0)
  1642. #define vifs varinit[0]
  1643. #if ENABLE_ASH_MAIL
  1644. # define vmail (&vifs)[1]
  1645. # define vmpath (&vmail)[1]
  1646. # define vpath (&vmpath)[1]
  1647. #else
  1648. # define vpath (&vifs)[1]
  1649. #endif
  1650. #define vps1 (&vpath)[1]
  1651. #define vps2 (&vps1)[1]
  1652. #define vps4 (&vps2)[1]
  1653. #if ENABLE_ASH_GETOPTS
  1654. # define voptind (&vps4)[1]
  1655. # if ENABLE_ASH_RANDOM_SUPPORT
  1656. # define vrandom (&voptind)[1]
  1657. # endif
  1658. #else
  1659. # if ENABLE_ASH_RANDOM_SUPPORT
  1660. # define vrandom (&vps4)[1]
  1661. # endif
  1662. #endif
  1663. /*
  1664. * The following macros access the values of the above variables.
  1665. * They have to skip over the name. They return the null string
  1666. * for unset variables.
  1667. */
  1668. #define ifsval() (vifs.text + 4)
  1669. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1670. #if ENABLE_ASH_MAIL
  1671. # define mailval() (vmail.text + 5)
  1672. # define mpathval() (vmpath.text + 9)
  1673. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1674. #endif
  1675. #define pathval() (vpath.text + 5)
  1676. #define ps1val() (vps1.text + 4)
  1677. #define ps2val() (vps2.text + 4)
  1678. #define ps4val() (vps4.text + 4)
  1679. #if ENABLE_ASH_GETOPTS
  1680. # define optindval() (voptind.text + 7)
  1681. #endif
  1682. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1683. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1684. #if ENABLE_ASH_GETOPTS
  1685. static void
  1686. getoptsreset(const char *value)
  1687. {
  1688. shellparam.optind = number(value);
  1689. shellparam.optoff = -1;
  1690. }
  1691. #endif
  1692. /*
  1693. * Return of a legal variable name (a letter or underscore followed by zero or
  1694. * more letters, underscores, and digits).
  1695. */
  1696. static char *
  1697. endofname(const char *name)
  1698. {
  1699. char *p;
  1700. p = (char *) name;
  1701. if (!is_name(*p))
  1702. return p;
  1703. while (*++p) {
  1704. if (!is_in_name(*p))
  1705. break;
  1706. }
  1707. return p;
  1708. }
  1709. /*
  1710. * Compares two strings up to the first = or '\0'. The first
  1711. * string must be terminated by '='; the second may be terminated by
  1712. * either '=' or '\0'.
  1713. */
  1714. static int
  1715. varcmp(const char *p, const char *q)
  1716. {
  1717. int c, d;
  1718. while ((c = *p) == (d = *q)) {
  1719. if (!c || c == '=')
  1720. goto out;
  1721. p++;
  1722. q++;
  1723. }
  1724. if (c == '=')
  1725. c = '\0';
  1726. if (d == '=')
  1727. d = '\0';
  1728. out:
  1729. return c - d;
  1730. }
  1731. static int
  1732. varequal(const char *a, const char *b)
  1733. {
  1734. return !varcmp(a, b);
  1735. }
  1736. /*
  1737. * Find the appropriate entry in the hash table from the name.
  1738. */
  1739. static struct var **
  1740. hashvar(const char *p)
  1741. {
  1742. unsigned hashval;
  1743. hashval = ((unsigned char) *p) << 4;
  1744. while (*p && *p != '=')
  1745. hashval += (unsigned char) *p++;
  1746. return &vartab[hashval % VTABSIZE];
  1747. }
  1748. static int
  1749. vpcmp(const void *a, const void *b)
  1750. {
  1751. return varcmp(*(const char **)a, *(const char **)b);
  1752. }
  1753. /*
  1754. * This routine initializes the builtin variables.
  1755. */
  1756. static void
  1757. initvar(void)
  1758. {
  1759. struct var *vp;
  1760. struct var *end;
  1761. struct var **vpp;
  1762. /*
  1763. * PS1 depends on uid
  1764. */
  1765. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1766. vps1.text = "PS1=\\w \\$ ";
  1767. #else
  1768. if (!geteuid())
  1769. vps1.text = "PS1=# ";
  1770. #endif
  1771. vp = varinit;
  1772. end = vp + ARRAY_SIZE(varinit);
  1773. do {
  1774. vpp = hashvar(vp->text);
  1775. vp->next = *vpp;
  1776. *vpp = vp;
  1777. } while (++vp < end);
  1778. }
  1779. static struct var **
  1780. findvar(struct var **vpp, const char *name)
  1781. {
  1782. for (; *vpp; vpp = &(*vpp)->next) {
  1783. if (varequal((*vpp)->text, name)) {
  1784. break;
  1785. }
  1786. }
  1787. return vpp;
  1788. }
  1789. /*
  1790. * Find the value of a variable. Returns NULL if not set.
  1791. */
  1792. static char *
  1793. lookupvar(const char *name)
  1794. {
  1795. struct var *v;
  1796. v = *findvar(hashvar(name), name);
  1797. if (v) {
  1798. #if ENABLE_ASH_RANDOM_SUPPORT
  1799. /*
  1800. * Dynamic variables are implemented roughly the same way they are
  1801. * in bash. Namely, they're "special" so long as they aren't unset.
  1802. * As soon as they're unset, they're no longer dynamic, and dynamic
  1803. * lookup will no longer happen at that point. -- PFM.
  1804. */
  1805. if ((v->flags & VDYNAMIC))
  1806. (*v->func)(NULL);
  1807. #endif
  1808. if (!(v->flags & VUNSET))
  1809. return strchrnul(v->text, '=') + 1;
  1810. }
  1811. return NULL;
  1812. }
  1813. /*
  1814. * Search the environment of a builtin command.
  1815. */
  1816. static char *
  1817. bltinlookup(const char *name)
  1818. {
  1819. struct strlist *sp;
  1820. for (sp = cmdenviron; sp; sp = sp->next) {
  1821. if (varequal(sp->text, name))
  1822. return strchrnul(sp->text, '=') + 1;
  1823. }
  1824. return lookupvar(name);
  1825. }
  1826. /*
  1827. * Same as setvar except that the variable and value are passed in
  1828. * the first argument as name=value. Since the first argument will
  1829. * be actually stored in the table, it should not be a string that
  1830. * will go away.
  1831. * Called with interrupts off.
  1832. */
  1833. static void
  1834. setvareq(char *s, int flags)
  1835. {
  1836. struct var *vp, **vpp;
  1837. vpp = hashvar(s);
  1838. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1839. vp = *findvar(vpp, s);
  1840. if (vp) {
  1841. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1842. const char *n;
  1843. if (flags & VNOSAVE)
  1844. free(s);
  1845. n = vp->text;
  1846. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1847. }
  1848. if (flags & VNOSET)
  1849. return;
  1850. if (vp->func && (flags & VNOFUNC) == 0)
  1851. (*vp->func)(strchrnul(s, '=') + 1);
  1852. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1853. free((char*)vp->text);
  1854. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1855. } else {
  1856. if (flags & VNOSET)
  1857. return;
  1858. /* not found */
  1859. vp = ckzalloc(sizeof(*vp));
  1860. vp->next = *vpp;
  1861. /*vp->func = NULL; - ckzalloc did it */
  1862. *vpp = vp;
  1863. }
  1864. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1865. s = ckstrdup(s);
  1866. vp->text = s;
  1867. vp->flags = flags;
  1868. }
  1869. /*
  1870. * Set the value of a variable. The flags argument is ored with the
  1871. * flags of the variable. If val is NULL, the variable is unset.
  1872. */
  1873. static void
  1874. setvar(const char *name, const char *val, int flags)
  1875. {
  1876. char *p, *q;
  1877. size_t namelen;
  1878. char *nameeq;
  1879. size_t vallen;
  1880. q = endofname(name);
  1881. p = strchrnul(q, '=');
  1882. namelen = p - name;
  1883. if (!namelen || p != q)
  1884. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1885. vallen = 0;
  1886. if (val == NULL) {
  1887. flags |= VUNSET;
  1888. } else {
  1889. vallen = strlen(val);
  1890. }
  1891. INT_OFF;
  1892. nameeq = ckmalloc(namelen + vallen + 2);
  1893. p = (char *)memcpy(nameeq, name, namelen) + namelen;
  1894. if (val) {
  1895. *p++ = '=';
  1896. p = (char *)memcpy(p, val, vallen) + vallen;
  1897. }
  1898. *p = '\0';
  1899. setvareq(nameeq, flags | VNOSAVE);
  1900. INT_ON;
  1901. }
  1902. #if ENABLE_ASH_GETOPTS
  1903. /*
  1904. * Safe version of setvar, returns 1 on success 0 on failure.
  1905. */
  1906. static int
  1907. setvarsafe(const char *name, const char *val, int flags)
  1908. {
  1909. int err;
  1910. volatile int saveint;
  1911. struct jmploc *volatile savehandler = exception_handler;
  1912. struct jmploc jmploc;
  1913. SAVE_INT(saveint);
  1914. if (setjmp(jmploc.loc))
  1915. err = 1;
  1916. else {
  1917. exception_handler = &jmploc;
  1918. setvar(name, val, flags);
  1919. err = 0;
  1920. }
  1921. exception_handler = savehandler;
  1922. RESTORE_INT(saveint);
  1923. return err;
  1924. }
  1925. #endif
  1926. /*
  1927. * Unset the specified variable.
  1928. */
  1929. static int
  1930. unsetvar(const char *s)
  1931. {
  1932. struct var **vpp;
  1933. struct var *vp;
  1934. int retval;
  1935. vpp = findvar(hashvar(s), s);
  1936. vp = *vpp;
  1937. retval = 2;
  1938. if (vp) {
  1939. int flags = vp->flags;
  1940. retval = 1;
  1941. if (flags & VREADONLY)
  1942. goto out;
  1943. #if ENABLE_ASH_RANDOM_SUPPORT
  1944. vp->flags &= ~VDYNAMIC;
  1945. #endif
  1946. if (flags & VUNSET)
  1947. goto ok;
  1948. if ((flags & VSTRFIXED) == 0) {
  1949. INT_OFF;
  1950. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1951. free((char*)vp->text);
  1952. *vpp = vp->next;
  1953. free(vp);
  1954. INT_ON;
  1955. } else {
  1956. setvar(s, 0, 0);
  1957. vp->flags &= ~VEXPORT;
  1958. }
  1959. ok:
  1960. retval = 0;
  1961. }
  1962. out:
  1963. return retval;
  1964. }
  1965. /*
  1966. * Process a linked list of variable assignments.
  1967. */
  1968. static void
  1969. listsetvar(struct strlist *list_set_var, int flags)
  1970. {
  1971. struct strlist *lp = list_set_var;
  1972. if (!lp)
  1973. return;
  1974. INT_OFF;
  1975. do {
  1976. setvareq(lp->text, flags);
  1977. lp = lp->next;
  1978. } while (lp);
  1979. INT_ON;
  1980. }
  1981. /*
  1982. * Generate a list of variables satisfying the given conditions.
  1983. */
  1984. static char **
  1985. listvars(int on, int off, char ***end)
  1986. {
  1987. struct var **vpp;
  1988. struct var *vp;
  1989. char **ep;
  1990. int mask;
  1991. STARTSTACKSTR(ep);
  1992. vpp = vartab;
  1993. mask = on | off;
  1994. do {
  1995. for (vp = *vpp; vp; vp = vp->next) {
  1996. if ((vp->flags & mask) == on) {
  1997. if (ep == stackstrend())
  1998. ep = growstackstr();
  1999. *ep++ = (char *) vp->text;
  2000. }
  2001. }
  2002. } while (++vpp < vartab + VTABSIZE);
  2003. if (ep == stackstrend())
  2004. ep = growstackstr();
  2005. if (end)
  2006. *end = ep;
  2007. *ep++ = NULL;
  2008. return grabstackstr(ep);
  2009. }
  2010. /* ============ Path search helper
  2011. *
  2012. * The variable path (passed by reference) should be set to the start
  2013. * of the path before the first call; padvance will update
  2014. * this value as it proceeds. Successive calls to padvance will return
  2015. * the possible path expansions in sequence. If an option (indicated by
  2016. * a percent sign) appears in the path entry then the global variable
  2017. * pathopt will be set to point to it; otherwise pathopt will be set to
  2018. * NULL.
  2019. */
  2020. static const char *pathopt; /* set by padvance */
  2021. static char *
  2022. padvance(const char **path, const char *name)
  2023. {
  2024. const char *p;
  2025. char *q;
  2026. const char *start;
  2027. size_t len;
  2028. if (*path == NULL)
  2029. return NULL;
  2030. start = *path;
  2031. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2032. continue;
  2033. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2034. while (stackblocksize() < len)
  2035. growstackblock();
  2036. q = stackblock();
  2037. if (p != start) {
  2038. memcpy(q, start, p - start);
  2039. q += p - start;
  2040. *q++ = '/';
  2041. }
  2042. strcpy(q, name);
  2043. pathopt = NULL;
  2044. if (*p == '%') {
  2045. pathopt = ++p;
  2046. while (*p && *p != ':')
  2047. p++;
  2048. }
  2049. if (*p == ':')
  2050. *path = p + 1;
  2051. else
  2052. *path = NULL;
  2053. return stalloc(len);
  2054. }
  2055. /* ============ Prompt */
  2056. static smallint doprompt; /* if set, prompt the user */
  2057. static smallint needprompt; /* true if interactive and at start of line */
  2058. #if ENABLE_FEATURE_EDITING
  2059. static line_input_t *line_input_state;
  2060. static const char *cmdedit_prompt;
  2061. static void
  2062. putprompt(const char *s)
  2063. {
  2064. if (ENABLE_ASH_EXPAND_PRMT) {
  2065. free((char*)cmdedit_prompt);
  2066. cmdedit_prompt = ckstrdup(s);
  2067. return;
  2068. }
  2069. cmdedit_prompt = s;
  2070. }
  2071. #else
  2072. static void
  2073. putprompt(const char *s)
  2074. {
  2075. out2str(s);
  2076. }
  2077. #endif
  2078. #if ENABLE_ASH_EXPAND_PRMT
  2079. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2080. static const char *expandstr(const char *ps);
  2081. #else
  2082. #define expandstr(s) s
  2083. #endif
  2084. static void
  2085. setprompt(int whichprompt)
  2086. {
  2087. const char *prompt;
  2088. #if ENABLE_ASH_EXPAND_PRMT
  2089. struct stackmark smark;
  2090. #endif
  2091. needprompt = 0;
  2092. switch (whichprompt) {
  2093. case 1:
  2094. prompt = ps1val();
  2095. break;
  2096. case 2:
  2097. prompt = ps2val();
  2098. break;
  2099. default: /* 0 */
  2100. prompt = nullstr;
  2101. }
  2102. #if ENABLE_ASH_EXPAND_PRMT
  2103. setstackmark(&smark);
  2104. stalloc(stackblocksize());
  2105. #endif
  2106. putprompt(expandstr(prompt));
  2107. #if ENABLE_ASH_EXPAND_PRMT
  2108. popstackmark(&smark);
  2109. #endif
  2110. }
  2111. /* ============ The cd and pwd commands */
  2112. #define CD_PHYSICAL 1
  2113. #define CD_PRINT 2
  2114. static int docd(const char *, int);
  2115. static int
  2116. cdopt(void)
  2117. {
  2118. int flags = 0;
  2119. int i, j;
  2120. j = 'L';
  2121. while ((i = nextopt("LP"))) {
  2122. if (i != j) {
  2123. flags ^= CD_PHYSICAL;
  2124. j = i;
  2125. }
  2126. }
  2127. return flags;
  2128. }
  2129. /*
  2130. * Update curdir (the name of the current directory) in response to a
  2131. * cd command.
  2132. */
  2133. static const char *
  2134. updatepwd(const char *dir)
  2135. {
  2136. char *new;
  2137. char *p;
  2138. char *cdcomppath;
  2139. const char *lim;
  2140. cdcomppath = ststrdup(dir);
  2141. STARTSTACKSTR(new);
  2142. if (*dir != '/') {
  2143. if (curdir == nullstr)
  2144. return 0;
  2145. new = stack_putstr(curdir, new);
  2146. }
  2147. new = makestrspace(strlen(dir) + 2, new);
  2148. lim = (char *)stackblock() + 1;
  2149. if (*dir != '/') {
  2150. if (new[-1] != '/')
  2151. USTPUTC('/', new);
  2152. if (new > lim && *lim == '/')
  2153. lim++;
  2154. } else {
  2155. USTPUTC('/', new);
  2156. cdcomppath++;
  2157. if (dir[1] == '/' && dir[2] != '/') {
  2158. USTPUTC('/', new);
  2159. cdcomppath++;
  2160. lim++;
  2161. }
  2162. }
  2163. p = strtok(cdcomppath, "/");
  2164. while (p) {
  2165. switch (*p) {
  2166. case '.':
  2167. if (p[1] == '.' && p[2] == '\0') {
  2168. while (new > lim) {
  2169. STUNPUTC(new);
  2170. if (new[-1] == '/')
  2171. break;
  2172. }
  2173. break;
  2174. }
  2175. if (p[1] == '\0')
  2176. break;
  2177. /* fall through */
  2178. default:
  2179. new = stack_putstr(p, new);
  2180. USTPUTC('/', new);
  2181. }
  2182. p = strtok(0, "/");
  2183. }
  2184. if (new > lim)
  2185. STUNPUTC(new);
  2186. *new = 0;
  2187. return stackblock();
  2188. }
  2189. /*
  2190. * Find out what the current directory is. If we already know the current
  2191. * directory, this routine returns immediately.
  2192. */
  2193. static char *
  2194. getpwd(void)
  2195. {
  2196. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2197. return dir ? dir : nullstr;
  2198. }
  2199. static void
  2200. setpwd(const char *val, int setold)
  2201. {
  2202. char *oldcur, *dir;
  2203. oldcur = dir = curdir;
  2204. if (setold) {
  2205. setvar("OLDPWD", oldcur, VEXPORT);
  2206. }
  2207. INT_OFF;
  2208. if (physdir != nullstr) {
  2209. if (physdir != oldcur)
  2210. free(physdir);
  2211. physdir = nullstr;
  2212. }
  2213. if (oldcur == val || !val) {
  2214. char *s = getpwd();
  2215. physdir = s;
  2216. if (!val)
  2217. dir = s;
  2218. } else
  2219. dir = ckstrdup(val);
  2220. if (oldcur != dir && oldcur != nullstr) {
  2221. free(oldcur);
  2222. }
  2223. curdir = dir;
  2224. INT_ON;
  2225. setvar("PWD", dir, VEXPORT);
  2226. }
  2227. static void hashcd(void);
  2228. /*
  2229. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2230. * know that the current directory has changed.
  2231. */
  2232. static int
  2233. docd(const char *dest, int flags)
  2234. {
  2235. const char *dir = 0;
  2236. int err;
  2237. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2238. INT_OFF;
  2239. if (!(flags & CD_PHYSICAL)) {
  2240. dir = updatepwd(dest);
  2241. if (dir)
  2242. dest = dir;
  2243. }
  2244. err = chdir(dest);
  2245. if (err)
  2246. goto out;
  2247. setpwd(dir, 1);
  2248. hashcd();
  2249. out:
  2250. INT_ON;
  2251. return err;
  2252. }
  2253. static int
  2254. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2255. {
  2256. const char *dest;
  2257. const char *path;
  2258. const char *p;
  2259. char c;
  2260. struct stat statb;
  2261. int flags;
  2262. flags = cdopt();
  2263. dest = *argptr;
  2264. if (!dest)
  2265. dest = bltinlookup(homestr);
  2266. else if (LONE_DASH(dest)) {
  2267. dest = bltinlookup("OLDPWD");
  2268. flags |= CD_PRINT;
  2269. }
  2270. if (!dest)
  2271. dest = nullstr;
  2272. if (*dest == '/')
  2273. goto step7;
  2274. if (*dest == '.') {
  2275. c = dest[1];
  2276. dotdot:
  2277. switch (c) {
  2278. case '\0':
  2279. case '/':
  2280. goto step6;
  2281. case '.':
  2282. c = dest[2];
  2283. if (c != '.')
  2284. goto dotdot;
  2285. }
  2286. }
  2287. if (!*dest)
  2288. dest = ".";
  2289. path = bltinlookup("CDPATH");
  2290. if (!path) {
  2291. step6:
  2292. step7:
  2293. p = dest;
  2294. goto docd;
  2295. }
  2296. do {
  2297. c = *path;
  2298. p = padvance(&path, dest);
  2299. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2300. if (c && c != ':')
  2301. flags |= CD_PRINT;
  2302. docd:
  2303. if (!docd(p, flags))
  2304. goto out;
  2305. break;
  2306. }
  2307. } while (path);
  2308. ash_msg_and_raise_error("can't cd to %s", dest);
  2309. /* NOTREACHED */
  2310. out:
  2311. if (flags & CD_PRINT)
  2312. out1fmt(snlfmt, curdir);
  2313. return 0;
  2314. }
  2315. static int
  2316. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2317. {
  2318. int flags;
  2319. const char *dir = curdir;
  2320. flags = cdopt();
  2321. if (flags) {
  2322. if (physdir == nullstr)
  2323. setpwd(dir, 0);
  2324. dir = physdir;
  2325. }
  2326. out1fmt(snlfmt, dir);
  2327. return 0;
  2328. }
  2329. /* ============ ... */
  2330. #define IBUFSIZ COMMON_BUFSIZE
  2331. /* buffer for top level input file */
  2332. #define basebuf bb_common_bufsiz1
  2333. /* Syntax classes */
  2334. #define CWORD 0 /* character is nothing special */
  2335. #define CNL 1 /* newline character */
  2336. #define CBACK 2 /* a backslash character */
  2337. #define CSQUOTE 3 /* single quote */
  2338. #define CDQUOTE 4 /* double quote */
  2339. #define CENDQUOTE 5 /* a terminating quote */
  2340. #define CBQUOTE 6 /* backwards single quote */
  2341. #define CVAR 7 /* a dollar sign */
  2342. #define CENDVAR 8 /* a '}' character */
  2343. #define CLP 9 /* a left paren in arithmetic */
  2344. #define CRP 10 /* a right paren in arithmetic */
  2345. #define CENDFILE 11 /* end of file */
  2346. #define CCTL 12 /* like CWORD, except it must be escaped */
  2347. #define CSPCL 13 /* these terminate a word */
  2348. #define CIGN 14 /* character should be ignored */
  2349. #if ENABLE_ASH_ALIAS
  2350. #define SYNBASE 130
  2351. #define PEOF -130
  2352. #define PEOA -129
  2353. #define PEOA_OR_PEOF PEOA
  2354. #else
  2355. #define SYNBASE 129
  2356. #define PEOF -129
  2357. #define PEOA_OR_PEOF PEOF
  2358. #endif
  2359. /* number syntax index */
  2360. #define BASESYNTAX 0 /* not in quotes */
  2361. #define DQSYNTAX 1 /* in double quotes */
  2362. #define SQSYNTAX 2 /* in single quotes */
  2363. #define ARISYNTAX 3 /* in arithmetic */
  2364. #define PSSYNTAX 4 /* prompt */
  2365. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2366. #define USE_SIT_FUNCTION
  2367. #endif
  2368. #if ENABLE_ASH_MATH_SUPPORT
  2369. static const char S_I_T[][4] = {
  2370. #if ENABLE_ASH_ALIAS
  2371. { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
  2372. #endif
  2373. { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
  2374. { CNL, CNL, CNL, CNL }, /* 2, \n */
  2375. { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
  2376. { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
  2377. { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
  2378. { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
  2379. { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
  2380. { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
  2381. { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
  2382. { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
  2383. { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
  2384. #ifndef USE_SIT_FUNCTION
  2385. { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2386. { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2387. { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2388. #endif
  2389. };
  2390. #else
  2391. static const char S_I_T[][3] = {
  2392. #if ENABLE_ASH_ALIAS
  2393. { CSPCL, CIGN, CIGN }, /* 0, PEOA */
  2394. #endif
  2395. { CSPCL, CWORD, CWORD }, /* 1, ' ' */
  2396. { CNL, CNL, CNL }, /* 2, \n */
  2397. { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
  2398. { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
  2399. { CVAR, CVAR, CWORD }, /* 5, $ */
  2400. { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
  2401. { CSPCL, CWORD, CWORD }, /* 7, ( */
  2402. { CSPCL, CWORD, CWORD }, /* 8, ) */
  2403. { CBACK, CBACK, CCTL }, /* 9, \ */
  2404. { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
  2405. { CENDVAR, CENDVAR, CWORD }, /* 11, } */
  2406. #ifndef USE_SIT_FUNCTION
  2407. { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2408. { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2409. { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2410. #endif
  2411. };
  2412. #endif /* ASH_MATH_SUPPORT */
  2413. #ifdef USE_SIT_FUNCTION
  2414. static int
  2415. SIT(int c, int syntax)
  2416. {
  2417. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2418. #if ENABLE_ASH_ALIAS
  2419. static const char syntax_index_table[] ALIGN1 = {
  2420. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2421. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2422. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2423. 11, 3 /* "}~" */
  2424. };
  2425. #else
  2426. static const char syntax_index_table[] ALIGN1 = {
  2427. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2428. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2429. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2430. 10, 2 /* "}~" */
  2431. };
  2432. #endif
  2433. const char *s;
  2434. int indx;
  2435. if (c == PEOF) /* 2^8+2 */
  2436. return CENDFILE;
  2437. #if ENABLE_ASH_ALIAS
  2438. if (c == PEOA) /* 2^8+1 */
  2439. indx = 0;
  2440. else
  2441. #endif
  2442. if ((unsigned char)c >= (unsigned char)(CTLESC)
  2443. && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
  2444. ) {
  2445. return CCTL;
  2446. } else {
  2447. s = strchrnul(spec_symbls, c);
  2448. if (*s == '\0')
  2449. return CWORD;
  2450. indx = syntax_index_table[s - spec_symbls];
  2451. }
  2452. return S_I_T[indx][syntax];
  2453. }
  2454. #else /* !USE_SIT_FUNCTION */
  2455. #if ENABLE_ASH_ALIAS
  2456. #define CSPCL_CIGN_CIGN_CIGN 0
  2457. #define CSPCL_CWORD_CWORD_CWORD 1
  2458. #define CNL_CNL_CNL_CNL 2
  2459. #define CWORD_CCTL_CCTL_CWORD 3
  2460. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  2461. #define CVAR_CVAR_CWORD_CVAR 5
  2462. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  2463. #define CSPCL_CWORD_CWORD_CLP 7
  2464. #define CSPCL_CWORD_CWORD_CRP 8
  2465. #define CBACK_CBACK_CCTL_CBACK 9
  2466. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  2467. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  2468. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  2469. #define CWORD_CWORD_CWORD_CWORD 13
  2470. #define CCTL_CCTL_CCTL_CCTL 14
  2471. #else
  2472. #define CSPCL_CWORD_CWORD_CWORD 0
  2473. #define CNL_CNL_CNL_CNL 1
  2474. #define CWORD_CCTL_CCTL_CWORD 2
  2475. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  2476. #define CVAR_CVAR_CWORD_CVAR 4
  2477. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  2478. #define CSPCL_CWORD_CWORD_CLP 6
  2479. #define CSPCL_CWORD_CWORD_CRP 7
  2480. #define CBACK_CBACK_CCTL_CBACK 8
  2481. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  2482. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  2483. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  2484. #define CWORD_CWORD_CWORD_CWORD 12
  2485. #define CCTL_CCTL_CCTL_CCTL 13
  2486. #endif
  2487. static const char syntax_index_table[258] = {
  2488. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2489. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2490. #if ENABLE_ASH_ALIAS
  2491. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2492. #endif
  2493. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2495. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2496. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2497. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2498. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2499. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2500. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2501. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2502. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  2507. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  2508. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  2509. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  2511. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  2513. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  2514. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  2515. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  2516. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  2517. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  2520. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  2522. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  2528. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  2529. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  2530. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  2531. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  2533. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  2534. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  2535. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  2536. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  2537. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  2538. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  2571. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  2601. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  2602. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  2603. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  2623. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  2624. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  2625. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2631. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  2632. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2654. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2655. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2656. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2658. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2660. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2661. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2662. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2663. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2664. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2667. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2669. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2680. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2681. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2682. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2683. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2684. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2685. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2693. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2694. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2695. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2696. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2697. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2698. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2713. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2714. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2715. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2718. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2746. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2747. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2748. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  2749. };
  2750. #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
  2751. #endif /* USE_SIT_FUNCTION */
  2752. /* ============ Alias handling */
  2753. #if ENABLE_ASH_ALIAS
  2754. #define ALIASINUSE 1
  2755. #define ALIASDEAD 2
  2756. struct alias {
  2757. struct alias *next;
  2758. char *name;
  2759. char *val;
  2760. int flag;
  2761. };
  2762. static struct alias **atab; // [ATABSIZE];
  2763. #define INIT_G_alias() do { \
  2764. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2765. } while (0)
  2766. static struct alias **
  2767. __lookupalias(const char *name) {
  2768. unsigned int hashval;
  2769. struct alias **app;
  2770. const char *p;
  2771. unsigned int ch;
  2772. p = name;
  2773. ch = (unsigned char)*p;
  2774. hashval = ch << 4;
  2775. while (ch) {
  2776. hashval += ch;
  2777. ch = (unsigned char)*++p;
  2778. }
  2779. app = &atab[hashval % ATABSIZE];
  2780. for (; *app; app = &(*app)->next) {
  2781. if (strcmp(name, (*app)->name) == 0) {
  2782. break;
  2783. }
  2784. }
  2785. return app;
  2786. }
  2787. static struct alias *
  2788. lookupalias(const char *name, int check)
  2789. {
  2790. struct alias *ap = *__lookupalias(name);
  2791. if (check && ap && (ap->flag & ALIASINUSE))
  2792. return NULL;
  2793. return ap;
  2794. }
  2795. static struct alias *
  2796. freealias(struct alias *ap)
  2797. {
  2798. struct alias *next;
  2799. if (ap->flag & ALIASINUSE) {
  2800. ap->flag |= ALIASDEAD;
  2801. return ap;
  2802. }
  2803. next = ap->next;
  2804. free(ap->name);
  2805. free(ap->val);
  2806. free(ap);
  2807. return next;
  2808. }
  2809. static void
  2810. setalias(const char *name, const char *val)
  2811. {
  2812. struct alias *ap, **app;
  2813. app = __lookupalias(name);
  2814. ap = *app;
  2815. INT_OFF;
  2816. if (ap) {
  2817. if (!(ap->flag & ALIASINUSE)) {
  2818. free(ap->val);
  2819. }
  2820. ap->val = ckstrdup(val);
  2821. ap->flag &= ~ALIASDEAD;
  2822. } else {
  2823. /* not found */
  2824. ap = ckzalloc(sizeof(struct alias));
  2825. ap->name = ckstrdup(name);
  2826. ap->val = ckstrdup(val);
  2827. /*ap->flag = 0; - ckzalloc did it */
  2828. /*ap->next = NULL;*/
  2829. *app = ap;
  2830. }
  2831. INT_ON;
  2832. }
  2833. static int
  2834. unalias(const char *name)
  2835. {
  2836. struct alias **app;
  2837. app = __lookupalias(name);
  2838. if (*app) {
  2839. INT_OFF;
  2840. *app = freealias(*app);
  2841. INT_ON;
  2842. return 0;
  2843. }
  2844. return 1;
  2845. }
  2846. static void
  2847. rmaliases(void)
  2848. {
  2849. struct alias *ap, **app;
  2850. int i;
  2851. INT_OFF;
  2852. for (i = 0; i < ATABSIZE; i++) {
  2853. app = &atab[i];
  2854. for (ap = *app; ap; ap = *app) {
  2855. *app = freealias(*app);
  2856. if (ap == *app) {
  2857. app = &ap->next;
  2858. }
  2859. }
  2860. }
  2861. INT_ON;
  2862. }
  2863. static void
  2864. printalias(const struct alias *ap)
  2865. {
  2866. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2867. }
  2868. /*
  2869. * TODO - sort output
  2870. */
  2871. static int
  2872. aliascmd(int argc UNUSED_PARAM, char **argv)
  2873. {
  2874. char *n, *v;
  2875. int ret = 0;
  2876. struct alias *ap;
  2877. if (!argv[1]) {
  2878. int i;
  2879. for (i = 0; i < ATABSIZE; i++) {
  2880. for (ap = atab[i]; ap; ap = ap->next) {
  2881. printalias(ap);
  2882. }
  2883. }
  2884. return 0;
  2885. }
  2886. while ((n = *++argv) != NULL) {
  2887. v = strchr(n+1, '=');
  2888. if (v == NULL) { /* n+1: funny ksh stuff */
  2889. ap = *__lookupalias(n);
  2890. if (ap == NULL) {
  2891. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2892. ret = 1;
  2893. } else
  2894. printalias(ap);
  2895. } else {
  2896. *v++ = '\0';
  2897. setalias(n, v);
  2898. }
  2899. }
  2900. return ret;
  2901. }
  2902. static int
  2903. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2904. {
  2905. int i;
  2906. while ((i = nextopt("a")) != '\0') {
  2907. if (i == 'a') {
  2908. rmaliases();
  2909. return 0;
  2910. }
  2911. }
  2912. for (i = 0; *argptr; argptr++) {
  2913. if (unalias(*argptr)) {
  2914. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2915. i = 1;
  2916. }
  2917. }
  2918. return i;
  2919. }
  2920. #endif /* ASH_ALIAS */
  2921. /* ============ jobs.c */
  2922. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2923. #define FORK_FG 0
  2924. #define FORK_BG 1
  2925. #define FORK_NOJOB 2
  2926. /* mode flags for showjob(s) */
  2927. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  2928. #define SHOW_PID 0x04 /* include process pid */
  2929. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  2930. /*
  2931. * A job structure contains information about a job. A job is either a
  2932. * single process or a set of processes contained in a pipeline. In the
  2933. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2934. * array of pids.
  2935. */
  2936. struct procstat {
  2937. pid_t pid; /* process id */
  2938. int status; /* last process status from wait() */
  2939. char *cmd; /* text of command being run */
  2940. };
  2941. struct job {
  2942. struct procstat ps0; /* status of process */
  2943. struct procstat *ps; /* status or processes when more than one */
  2944. #if JOBS
  2945. int stopstatus; /* status of a stopped job */
  2946. #endif
  2947. uint32_t
  2948. nprocs: 16, /* number of processes */
  2949. state: 8,
  2950. #define JOBRUNNING 0 /* at least one proc running */
  2951. #define JOBSTOPPED 1 /* all procs are stopped */
  2952. #define JOBDONE 2 /* all procs are completed */
  2953. #if JOBS
  2954. sigint: 1, /* job was killed by SIGINT */
  2955. jobctl: 1, /* job running under job control */
  2956. #endif
  2957. waited: 1, /* true if this entry has been waited for */
  2958. used: 1, /* true if this entry is in used */
  2959. changed: 1; /* true if status has changed */
  2960. struct job *prev_job; /* previous job */
  2961. };
  2962. static struct job *makejob(/*union node *,*/ int);
  2963. #if !JOBS
  2964. #define forkshell(job, node, mode) forkshell(job, mode)
  2965. #endif
  2966. static int forkshell(struct job *, union node *, int);
  2967. static int waitforjob(struct job *);
  2968. #if !JOBS
  2969. enum { doing_jobctl = 0 };
  2970. #define setjobctl(on) do {} while (0)
  2971. #else
  2972. static smallint doing_jobctl; //references:8
  2973. static void setjobctl(int);
  2974. #endif
  2975. /*
  2976. * Set the signal handler for the specified signal. The routine figures
  2977. * out what it should be set to.
  2978. */
  2979. static void
  2980. setsignal(int signo)
  2981. {
  2982. int action;
  2983. char *t, tsig;
  2984. struct sigaction act;
  2985. t = trap[signo];
  2986. action = S_IGN;
  2987. if (t == NULL)
  2988. action = S_DFL;
  2989. else if (*t != '\0')
  2990. action = S_CATCH;
  2991. if (rootshell && action == S_DFL) {
  2992. switch (signo) {
  2993. case SIGINT:
  2994. if (iflag || minusc || sflag == 0)
  2995. action = S_CATCH;
  2996. break;
  2997. case SIGQUIT:
  2998. #if DEBUG
  2999. if (debug)
  3000. break;
  3001. #endif
  3002. /* FALLTHROUGH */
  3003. case SIGTERM:
  3004. if (iflag)
  3005. action = S_IGN;
  3006. break;
  3007. #if JOBS
  3008. case SIGTSTP:
  3009. case SIGTTOU:
  3010. if (mflag)
  3011. action = S_IGN;
  3012. break;
  3013. #endif
  3014. }
  3015. }
  3016. t = &sigmode[signo - 1];
  3017. tsig = *t;
  3018. if (tsig == 0) {
  3019. /*
  3020. * current setting unknown
  3021. */
  3022. if (sigaction(signo, NULL, &act) == -1) {
  3023. /*
  3024. * Pretend it worked; maybe we should give a warning
  3025. * here, but other shells don't. We don't alter
  3026. * sigmode, so that we retry every time.
  3027. */
  3028. return;
  3029. }
  3030. tsig = S_RESET; /* force to be set */
  3031. if (act.sa_handler == SIG_IGN) {
  3032. tsig = S_HARD_IGN;
  3033. if (mflag
  3034. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3035. ) {
  3036. tsig = S_IGN; /* don't hard ignore these */
  3037. }
  3038. }
  3039. }
  3040. if (tsig == S_HARD_IGN || tsig == action)
  3041. return;
  3042. act.sa_handler = SIG_DFL;
  3043. switch (action) {
  3044. case S_CATCH:
  3045. act.sa_handler = onsig;
  3046. break;
  3047. case S_IGN:
  3048. act.sa_handler = SIG_IGN;
  3049. break;
  3050. }
  3051. *t = action;
  3052. act.sa_flags = 0;
  3053. sigfillset(&act.sa_mask);
  3054. sigaction_set(signo, &act);
  3055. }
  3056. /* mode flags for set_curjob */
  3057. #define CUR_DELETE 2
  3058. #define CUR_RUNNING 1
  3059. #define CUR_STOPPED 0
  3060. /* mode flags for dowait */
  3061. #define DOWAIT_NONBLOCK WNOHANG
  3062. #define DOWAIT_BLOCK 0
  3063. #if JOBS
  3064. /* pgrp of shell on invocation */
  3065. static int initialpgrp; //references:2
  3066. static int ttyfd = -1; //5
  3067. #endif
  3068. /* array of jobs */
  3069. static struct job *jobtab; //5
  3070. /* size of array */
  3071. static unsigned njobs; //4
  3072. /* current job */
  3073. static struct job *curjob; //lots
  3074. /* number of presumed living untracked jobs */
  3075. static int jobless; //4
  3076. static void
  3077. set_curjob(struct job *jp, unsigned mode)
  3078. {
  3079. struct job *jp1;
  3080. struct job **jpp, **curp;
  3081. /* first remove from list */
  3082. jpp = curp = &curjob;
  3083. do {
  3084. jp1 = *jpp;
  3085. if (jp1 == jp)
  3086. break;
  3087. jpp = &jp1->prev_job;
  3088. } while (1);
  3089. *jpp = jp1->prev_job;
  3090. /* Then re-insert in correct position */
  3091. jpp = curp;
  3092. switch (mode) {
  3093. default:
  3094. #if DEBUG
  3095. abort();
  3096. #endif
  3097. case CUR_DELETE:
  3098. /* job being deleted */
  3099. break;
  3100. case CUR_RUNNING:
  3101. /* newly created job or backgrounded job,
  3102. put after all stopped jobs. */
  3103. do {
  3104. jp1 = *jpp;
  3105. #if JOBS
  3106. if (!jp1 || jp1->state != JOBSTOPPED)
  3107. #endif
  3108. break;
  3109. jpp = &jp1->prev_job;
  3110. } while (1);
  3111. /* FALLTHROUGH */
  3112. #if JOBS
  3113. case CUR_STOPPED:
  3114. #endif
  3115. /* newly stopped job - becomes curjob */
  3116. jp->prev_job = *jpp;
  3117. *jpp = jp;
  3118. break;
  3119. }
  3120. }
  3121. #if JOBS || DEBUG
  3122. static int
  3123. jobno(const struct job *jp)
  3124. {
  3125. return jp - jobtab + 1;
  3126. }
  3127. #endif
  3128. /*
  3129. * Convert a job name to a job structure.
  3130. */
  3131. #if !JOBS
  3132. #define getjob(name, getctl) getjob(name)
  3133. #endif
  3134. static struct job *
  3135. getjob(const char *name, int getctl)
  3136. {
  3137. struct job *jp;
  3138. struct job *found;
  3139. const char *err_msg = "No such job: %s";
  3140. unsigned num;
  3141. int c;
  3142. const char *p;
  3143. char *(*match)(const char *, const char *);
  3144. jp = curjob;
  3145. p = name;
  3146. if (!p)
  3147. goto currentjob;
  3148. if (*p != '%')
  3149. goto err;
  3150. c = *++p;
  3151. if (!c)
  3152. goto currentjob;
  3153. if (!p[1]) {
  3154. if (c == '+' || c == '%') {
  3155. currentjob:
  3156. err_msg = "No current job";
  3157. goto check;
  3158. }
  3159. if (c == '-') {
  3160. if (jp)
  3161. jp = jp->prev_job;
  3162. err_msg = "No previous job";
  3163. check:
  3164. if (!jp)
  3165. goto err;
  3166. goto gotit;
  3167. }
  3168. }
  3169. if (is_number(p)) {
  3170. // TODO: number() instead? It does error checking...
  3171. num = atoi(p);
  3172. if (num < njobs) {
  3173. jp = jobtab + num - 1;
  3174. if (jp->used)
  3175. goto gotit;
  3176. goto err;
  3177. }
  3178. }
  3179. match = prefix;
  3180. if (*p == '?') {
  3181. match = strstr;
  3182. p++;
  3183. }
  3184. found = 0;
  3185. while (1) {
  3186. if (!jp)
  3187. goto err;
  3188. if (match(jp->ps[0].cmd, p)) {
  3189. if (found)
  3190. goto err;
  3191. found = jp;
  3192. err_msg = "%s: ambiguous";
  3193. }
  3194. jp = jp->prev_job;
  3195. }
  3196. gotit:
  3197. #if JOBS
  3198. err_msg = "job %s not created under job control";
  3199. if (getctl && jp->jobctl == 0)
  3200. goto err;
  3201. #endif
  3202. return jp;
  3203. err:
  3204. ash_msg_and_raise_error(err_msg, name);
  3205. }
  3206. /*
  3207. * Mark a job structure as unused.
  3208. */
  3209. static void
  3210. freejob(struct job *jp)
  3211. {
  3212. struct procstat *ps;
  3213. int i;
  3214. INT_OFF;
  3215. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3216. if (ps->cmd != nullstr)
  3217. free(ps->cmd);
  3218. }
  3219. if (jp->ps != &jp->ps0)
  3220. free(jp->ps);
  3221. jp->used = 0;
  3222. set_curjob(jp, CUR_DELETE);
  3223. INT_ON;
  3224. }
  3225. #if JOBS
  3226. static void
  3227. xtcsetpgrp(int fd, pid_t pgrp)
  3228. {
  3229. if (tcsetpgrp(fd, pgrp))
  3230. ash_msg_and_raise_error("can't set tty process group (%m)");
  3231. }
  3232. /*
  3233. * Turn job control on and off.
  3234. *
  3235. * Note: This code assumes that the third arg to ioctl is a character
  3236. * pointer, which is true on Berkeley systems but not System V. Since
  3237. * System V doesn't have job control yet, this isn't a problem now.
  3238. *
  3239. * Called with interrupts off.
  3240. */
  3241. static void
  3242. setjobctl(int on)
  3243. {
  3244. int fd;
  3245. int pgrp;
  3246. if (on == doing_jobctl || rootshell == 0)
  3247. return;
  3248. if (on) {
  3249. int ofd;
  3250. ofd = fd = open(_PATH_TTY, O_RDWR);
  3251. if (fd < 0) {
  3252. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3253. * That sometimes helps to acquire controlling tty.
  3254. * Obviously, a workaround for bugs when someone
  3255. * failed to provide a controlling tty to bash! :) */
  3256. fd = 2;
  3257. while (!isatty(fd))
  3258. if (--fd < 0)
  3259. goto out;
  3260. }
  3261. fd = fcntl(fd, F_DUPFD, 10);
  3262. if (ofd >= 0)
  3263. close(ofd);
  3264. if (fd < 0)
  3265. goto out;
  3266. /* fd is a tty at this point */
  3267. close_on_exec_on(fd);
  3268. do { /* while we are in the background */
  3269. pgrp = tcgetpgrp(fd);
  3270. if (pgrp < 0) {
  3271. out:
  3272. ash_msg("can't access tty; job control turned off");
  3273. mflag = on = 0;
  3274. goto close;
  3275. }
  3276. if (pgrp == getpgrp())
  3277. break;
  3278. killpg(0, SIGTTIN);
  3279. } while (1);
  3280. initialpgrp = pgrp;
  3281. setsignal(SIGTSTP);
  3282. setsignal(SIGTTOU);
  3283. setsignal(SIGTTIN);
  3284. pgrp = rootpid;
  3285. setpgid(0, pgrp);
  3286. xtcsetpgrp(fd, pgrp);
  3287. } else {
  3288. /* turning job control off */
  3289. fd = ttyfd;
  3290. pgrp = initialpgrp;
  3291. /* was xtcsetpgrp, but this can make exiting ash
  3292. * loop forever if pty is already deleted */
  3293. tcsetpgrp(fd, pgrp);
  3294. setpgid(0, pgrp);
  3295. setsignal(SIGTSTP);
  3296. setsignal(SIGTTOU);
  3297. setsignal(SIGTTIN);
  3298. close:
  3299. if (fd >= 0)
  3300. close(fd);
  3301. fd = -1;
  3302. }
  3303. ttyfd = fd;
  3304. doing_jobctl = on;
  3305. }
  3306. static int
  3307. killcmd(int argc, char **argv)
  3308. {
  3309. int i = 1;
  3310. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3311. do {
  3312. if (argv[i][0] == '%') {
  3313. struct job *jp = getjob(argv[i], 0);
  3314. unsigned pid = jp->ps[0].pid;
  3315. /* Enough space for ' -NNN<nul>' */
  3316. argv[i] = alloca(sizeof(int)*3 + 3);
  3317. /* kill_main has matching code to expect
  3318. * leading space. Needed to not confuse
  3319. * negative pids with "kill -SIGNAL_NO" syntax */
  3320. sprintf(argv[i], " -%u", pid);
  3321. }
  3322. } while (argv[++i]);
  3323. }
  3324. return kill_main(argc, argv);
  3325. }
  3326. static void
  3327. showpipe(struct job *jp, FILE *out)
  3328. {
  3329. struct procstat *sp;
  3330. struct procstat *spend;
  3331. spend = jp->ps + jp->nprocs;
  3332. for (sp = jp->ps + 1; sp < spend; sp++)
  3333. fprintf(out, " | %s", sp->cmd);
  3334. outcslow('\n', out);
  3335. flush_stdout_stderr();
  3336. }
  3337. static int
  3338. restartjob(struct job *jp, int mode)
  3339. {
  3340. struct procstat *ps;
  3341. int i;
  3342. int status;
  3343. pid_t pgid;
  3344. INT_OFF;
  3345. if (jp->state == JOBDONE)
  3346. goto out;
  3347. jp->state = JOBRUNNING;
  3348. pgid = jp->ps->pid;
  3349. if (mode == FORK_FG)
  3350. xtcsetpgrp(ttyfd, pgid);
  3351. killpg(pgid, SIGCONT);
  3352. ps = jp->ps;
  3353. i = jp->nprocs;
  3354. do {
  3355. if (WIFSTOPPED(ps->status)) {
  3356. ps->status = -1;
  3357. }
  3358. ps++;
  3359. } while (--i);
  3360. out:
  3361. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3362. INT_ON;
  3363. return status;
  3364. }
  3365. static int
  3366. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3367. {
  3368. struct job *jp;
  3369. FILE *out;
  3370. int mode;
  3371. int retval;
  3372. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3373. nextopt(nullstr);
  3374. argv = argptr;
  3375. out = stdout;
  3376. do {
  3377. jp = getjob(*argv, 1);
  3378. if (mode == FORK_BG) {
  3379. set_curjob(jp, CUR_RUNNING);
  3380. fprintf(out, "[%d] ", jobno(jp));
  3381. }
  3382. outstr(jp->ps->cmd, out);
  3383. showpipe(jp, out);
  3384. retval = restartjob(jp, mode);
  3385. } while (*argv && *++argv);
  3386. return retval;
  3387. }
  3388. #endif
  3389. static int
  3390. sprint_status(char *s, int status, int sigonly)
  3391. {
  3392. int col;
  3393. int st;
  3394. col = 0;
  3395. if (!WIFEXITED(status)) {
  3396. #if JOBS
  3397. if (WIFSTOPPED(status))
  3398. st = WSTOPSIG(status);
  3399. else
  3400. #endif
  3401. st = WTERMSIG(status);
  3402. if (sigonly) {
  3403. if (st == SIGINT || st == SIGPIPE)
  3404. goto out;
  3405. #if JOBS
  3406. if (WIFSTOPPED(status))
  3407. goto out;
  3408. #endif
  3409. }
  3410. st &= 0x7f;
  3411. col = fmtstr(s, 32, strsignal(st));
  3412. if (WCOREDUMP(status)) {
  3413. col += fmtstr(s + col, 16, " (core dumped)");
  3414. }
  3415. } else if (!sigonly) {
  3416. st = WEXITSTATUS(status);
  3417. if (st)
  3418. col = fmtstr(s, 16, "Done(%d)", st);
  3419. else
  3420. col = fmtstr(s, 16, "Done");
  3421. }
  3422. out:
  3423. return col;
  3424. }
  3425. static int
  3426. dowait(int wait_flags, struct job *job)
  3427. {
  3428. int pid;
  3429. int status;
  3430. struct job *jp;
  3431. struct job *thisjob;
  3432. int state;
  3433. TRACE(("dowait(0x%x) called\n", wait_flags));
  3434. /* Do a wait system call. If job control is compiled in, we accept
  3435. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3436. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3437. pid = waitpid(-1, &status,
  3438. (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
  3439. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n", pid, status, errno, strerror(errno)));
  3440. if (pid <= 0) {
  3441. /* If we were doing blocking wait and (probably) got EINTR,
  3442. * check for pending sigs received while waiting.
  3443. * (NB: can be moved into callers if needed) */
  3444. if (wait_flags == DOWAIT_BLOCK && pendingsig)
  3445. raise_exception(EXSIG);
  3446. return pid;
  3447. }
  3448. INT_OFF;
  3449. thisjob = NULL;
  3450. for (jp = curjob; jp; jp = jp->prev_job) {
  3451. struct procstat *sp;
  3452. struct procstat *spend;
  3453. if (jp->state == JOBDONE)
  3454. continue;
  3455. state = JOBDONE;
  3456. spend = jp->ps + jp->nprocs;
  3457. sp = jp->ps;
  3458. do {
  3459. if (sp->pid == pid) {
  3460. TRACE(("Job %d: changing status of proc %d "
  3461. "from 0x%x to 0x%x\n",
  3462. jobno(jp), pid, sp->status, status));
  3463. sp->status = status;
  3464. thisjob = jp;
  3465. }
  3466. if (sp->status == -1)
  3467. state = JOBRUNNING;
  3468. #if JOBS
  3469. if (state == JOBRUNNING)
  3470. continue;
  3471. if (WIFSTOPPED(sp->status)) {
  3472. jp->stopstatus = sp->status;
  3473. state = JOBSTOPPED;
  3474. }
  3475. #endif
  3476. } while (++sp < spend);
  3477. if (thisjob)
  3478. goto gotjob;
  3479. }
  3480. #if JOBS
  3481. if (!WIFSTOPPED(status))
  3482. #endif
  3483. jobless--;
  3484. goto out;
  3485. gotjob:
  3486. if (state != JOBRUNNING) {
  3487. thisjob->changed = 1;
  3488. if (thisjob->state != state) {
  3489. TRACE(("Job %d: changing state from %d to %d\n",
  3490. jobno(thisjob), thisjob->state, state));
  3491. thisjob->state = state;
  3492. #if JOBS
  3493. if (state == JOBSTOPPED) {
  3494. set_curjob(thisjob, CUR_STOPPED);
  3495. }
  3496. #endif
  3497. }
  3498. }
  3499. out:
  3500. INT_ON;
  3501. if (thisjob && thisjob == job) {
  3502. char s[48 + 1];
  3503. int len;
  3504. len = sprint_status(s, status, 1);
  3505. if (len) {
  3506. s[len] = '\n';
  3507. s[len + 1] = '\0';
  3508. out2str(s);
  3509. }
  3510. }
  3511. return pid;
  3512. }
  3513. #if JOBS
  3514. static void
  3515. showjob(FILE *out, struct job *jp, int mode)
  3516. {
  3517. struct procstat *ps;
  3518. struct procstat *psend;
  3519. int col;
  3520. int indent_col;
  3521. char s[80];
  3522. ps = jp->ps;
  3523. if (mode & SHOW_PGID) {
  3524. /* just output process (group) id of pipeline */
  3525. fprintf(out, "%d\n", ps->pid);
  3526. return;
  3527. }
  3528. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3529. indent_col = col;
  3530. if (jp == curjob)
  3531. s[col - 2] = '+';
  3532. else if (curjob && jp == curjob->prev_job)
  3533. s[col - 2] = '-';
  3534. if (mode & SHOW_PID)
  3535. col += fmtstr(s + col, 16, "%d ", ps->pid);
  3536. psend = ps + jp->nprocs;
  3537. if (jp->state == JOBRUNNING) {
  3538. strcpy(s + col, "Running");
  3539. col += sizeof("Running") - 1;
  3540. } else {
  3541. int status = psend[-1].status;
  3542. if (jp->state == JOBSTOPPED)
  3543. status = jp->stopstatus;
  3544. col += sprint_status(s + col, status, 0);
  3545. }
  3546. goto start;
  3547. do {
  3548. /* for each process */
  3549. col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
  3550. start:
  3551. fprintf(out, "%s%*c%s",
  3552. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  3553. );
  3554. if (!(mode & SHOW_PID)) {
  3555. showpipe(jp, out);
  3556. break;
  3557. }
  3558. if (++ps == psend) {
  3559. outcslow('\n', out);
  3560. break;
  3561. }
  3562. } while (1);
  3563. jp->changed = 0;
  3564. if (jp->state == JOBDONE) {
  3565. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3566. freejob(jp);
  3567. }
  3568. }
  3569. /*
  3570. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3571. * statuses have changed since the last call to showjobs.
  3572. */
  3573. static void
  3574. showjobs(FILE *out, int mode)
  3575. {
  3576. struct job *jp;
  3577. TRACE(("showjobs(%x) called\n", mode));
  3578. /* If not even one job changed, there is nothing to do */
  3579. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3580. continue;
  3581. for (jp = curjob; jp; jp = jp->prev_job) {
  3582. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3583. showjob(out, jp, mode);
  3584. }
  3585. }
  3586. }
  3587. static int
  3588. jobscmd(int argc UNUSED_PARAM, char **argv)
  3589. {
  3590. int mode, m;
  3591. mode = 0;
  3592. while ((m = nextopt("lp"))) {
  3593. if (m == 'l')
  3594. mode = SHOW_PID;
  3595. else
  3596. mode = SHOW_PGID;
  3597. }
  3598. argv = argptr;
  3599. if (*argv) {
  3600. do
  3601. showjob(stdout, getjob(*argv,0), mode);
  3602. while (*++argv);
  3603. } else
  3604. showjobs(stdout, mode);
  3605. return 0;
  3606. }
  3607. #endif /* JOBS */
  3608. static int
  3609. getstatus(struct job *job)
  3610. {
  3611. int status;
  3612. int retval;
  3613. status = job->ps[job->nprocs - 1].status;
  3614. retval = WEXITSTATUS(status);
  3615. if (!WIFEXITED(status)) {
  3616. #if JOBS
  3617. retval = WSTOPSIG(status);
  3618. if (!WIFSTOPPED(status))
  3619. #endif
  3620. {
  3621. /* XXX: limits number of signals */
  3622. retval = WTERMSIG(status);
  3623. #if JOBS
  3624. if (retval == SIGINT)
  3625. job->sigint = 1;
  3626. #endif
  3627. }
  3628. retval += 128;
  3629. }
  3630. TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
  3631. jobno(job), job->nprocs, status, retval));
  3632. return retval;
  3633. }
  3634. static int
  3635. waitcmd(int argc UNUSED_PARAM, char **argv)
  3636. {
  3637. struct job *job;
  3638. int retval;
  3639. struct job *jp;
  3640. // exsig++;
  3641. // xbarrier();
  3642. if (pendingsig)
  3643. raise_exception(EXSIG);
  3644. nextopt(nullstr);
  3645. retval = 0;
  3646. argv = argptr;
  3647. if (!*argv) {
  3648. /* wait for all jobs */
  3649. for (;;) {
  3650. jp = curjob;
  3651. while (1) {
  3652. if (!jp) /* no running procs */
  3653. goto ret;
  3654. if (jp->state == JOBRUNNING)
  3655. break;
  3656. jp->waited = 1;
  3657. jp = jp->prev_job;
  3658. }
  3659. dowait(DOWAIT_BLOCK, NULL);
  3660. }
  3661. }
  3662. retval = 127;
  3663. do {
  3664. if (**argv != '%') {
  3665. pid_t pid = number(*argv);
  3666. job = curjob;
  3667. while (1) {
  3668. if (!job)
  3669. goto repeat;
  3670. if (job->ps[job->nprocs - 1].pid == pid)
  3671. break;
  3672. job = job->prev_job;
  3673. }
  3674. } else
  3675. job = getjob(*argv, 0);
  3676. /* loop until process terminated or stopped */
  3677. while (job->state == JOBRUNNING)
  3678. dowait(DOWAIT_BLOCK, NULL);
  3679. job->waited = 1;
  3680. retval = getstatus(job);
  3681. repeat:
  3682. ;
  3683. } while (*++argv);
  3684. ret:
  3685. return retval;
  3686. }
  3687. static struct job *
  3688. growjobtab(void)
  3689. {
  3690. size_t len;
  3691. ptrdiff_t offset;
  3692. struct job *jp, *jq;
  3693. len = njobs * sizeof(*jp);
  3694. jq = jobtab;
  3695. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3696. offset = (char *)jp - (char *)jq;
  3697. if (offset) {
  3698. /* Relocate pointers */
  3699. size_t l = len;
  3700. jq = (struct job *)((char *)jq + l);
  3701. while (l) {
  3702. l -= sizeof(*jp);
  3703. jq--;
  3704. #define joff(p) ((struct job *)((char *)(p) + l))
  3705. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3706. if (joff(jp)->ps == &jq->ps0)
  3707. jmove(joff(jp)->ps);
  3708. if (joff(jp)->prev_job)
  3709. jmove(joff(jp)->prev_job);
  3710. }
  3711. if (curjob)
  3712. jmove(curjob);
  3713. #undef joff
  3714. #undef jmove
  3715. }
  3716. njobs += 4;
  3717. jobtab = jp;
  3718. jp = (struct job *)((char *)jp + len);
  3719. jq = jp + 3;
  3720. do {
  3721. jq->used = 0;
  3722. } while (--jq >= jp);
  3723. return jp;
  3724. }
  3725. /*
  3726. * Return a new job structure.
  3727. * Called with interrupts off.
  3728. */
  3729. static struct job *
  3730. makejob(/*union node *node,*/ int nprocs)
  3731. {
  3732. int i;
  3733. struct job *jp;
  3734. for (i = njobs, jp = jobtab; ; jp++) {
  3735. if (--i < 0) {
  3736. jp = growjobtab();
  3737. break;
  3738. }
  3739. if (jp->used == 0)
  3740. break;
  3741. if (jp->state != JOBDONE || !jp->waited)
  3742. continue;
  3743. #if JOBS
  3744. if (doing_jobctl)
  3745. continue;
  3746. #endif
  3747. freejob(jp);
  3748. break;
  3749. }
  3750. memset(jp, 0, sizeof(*jp));
  3751. #if JOBS
  3752. /* jp->jobctl is a bitfield.
  3753. * "jp->jobctl |= jobctl" likely to give awful code */
  3754. if (doing_jobctl)
  3755. jp->jobctl = 1;
  3756. #endif
  3757. jp->prev_job = curjob;
  3758. curjob = jp;
  3759. jp->used = 1;
  3760. jp->ps = &jp->ps0;
  3761. if (nprocs > 1) {
  3762. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3763. }
  3764. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3765. jobno(jp)));
  3766. return jp;
  3767. }
  3768. #if JOBS
  3769. /*
  3770. * Return a string identifying a command (to be printed by the
  3771. * jobs command).
  3772. */
  3773. static char *cmdnextc;
  3774. static void
  3775. cmdputs(const char *s)
  3776. {
  3777. static const char vstype[VSTYPE + 1][3] = {
  3778. "", "}", "-", "+", "?", "=",
  3779. "%", "%%", "#", "##"
  3780. USE_ASH_BASH_COMPAT(, ":", "/", "//")
  3781. };
  3782. const char *p, *str;
  3783. char c, cc[2] = " ";
  3784. char *nextc;
  3785. int subtype = 0;
  3786. int quoted = 0;
  3787. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3788. p = s;
  3789. while ((c = *p++) != 0) {
  3790. str = NULL;
  3791. switch (c) {
  3792. case CTLESC:
  3793. c = *p++;
  3794. break;
  3795. case CTLVAR:
  3796. subtype = *p++;
  3797. if ((subtype & VSTYPE) == VSLENGTH)
  3798. str = "${#";
  3799. else
  3800. str = "${";
  3801. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3802. goto dostr;
  3803. quoted ^= 1;
  3804. c = '"';
  3805. break;
  3806. case CTLENDVAR:
  3807. str = "\"}" + !(quoted & 1);
  3808. quoted >>= 1;
  3809. subtype = 0;
  3810. goto dostr;
  3811. case CTLBACKQ:
  3812. str = "$(...)";
  3813. goto dostr;
  3814. case CTLBACKQ+CTLQUOTE:
  3815. str = "\"$(...)\"";
  3816. goto dostr;
  3817. #if ENABLE_ASH_MATH_SUPPORT
  3818. case CTLARI:
  3819. str = "$((";
  3820. goto dostr;
  3821. case CTLENDARI:
  3822. str = "))";
  3823. goto dostr;
  3824. #endif
  3825. case CTLQUOTEMARK:
  3826. quoted ^= 1;
  3827. c = '"';
  3828. break;
  3829. case '=':
  3830. if (subtype == 0)
  3831. break;
  3832. if ((subtype & VSTYPE) != VSNORMAL)
  3833. quoted <<= 1;
  3834. str = vstype[subtype & VSTYPE];
  3835. if (subtype & VSNUL)
  3836. c = ':';
  3837. else
  3838. goto checkstr;
  3839. break;
  3840. case '\'':
  3841. case '\\':
  3842. case '"':
  3843. case '$':
  3844. /* These can only happen inside quotes */
  3845. cc[0] = c;
  3846. str = cc;
  3847. c = '\\';
  3848. break;
  3849. default:
  3850. break;
  3851. }
  3852. USTPUTC(c, nextc);
  3853. checkstr:
  3854. if (!str)
  3855. continue;
  3856. dostr:
  3857. while ((c = *str++)) {
  3858. USTPUTC(c, nextc);
  3859. }
  3860. }
  3861. if (quoted & 1) {
  3862. USTPUTC('"', nextc);
  3863. }
  3864. *nextc = 0;
  3865. cmdnextc = nextc;
  3866. }
  3867. /* cmdtxt() and cmdlist() call each other */
  3868. static void cmdtxt(union node *n);
  3869. static void
  3870. cmdlist(union node *np, int sep)
  3871. {
  3872. for (; np; np = np->narg.next) {
  3873. if (!sep)
  3874. cmdputs(" ");
  3875. cmdtxt(np);
  3876. if (sep && np->narg.next)
  3877. cmdputs(" ");
  3878. }
  3879. }
  3880. static void
  3881. cmdtxt(union node *n)
  3882. {
  3883. union node *np;
  3884. struct nodelist *lp;
  3885. const char *p;
  3886. if (!n)
  3887. return;
  3888. switch (n->type) {
  3889. default:
  3890. #if DEBUG
  3891. abort();
  3892. #endif
  3893. case NPIPE:
  3894. lp = n->npipe.cmdlist;
  3895. for (;;) {
  3896. cmdtxt(lp->n);
  3897. lp = lp->next;
  3898. if (!lp)
  3899. break;
  3900. cmdputs(" | ");
  3901. }
  3902. break;
  3903. case NSEMI:
  3904. p = "; ";
  3905. goto binop;
  3906. case NAND:
  3907. p = " && ";
  3908. goto binop;
  3909. case NOR:
  3910. p = " || ";
  3911. binop:
  3912. cmdtxt(n->nbinary.ch1);
  3913. cmdputs(p);
  3914. n = n->nbinary.ch2;
  3915. goto donode;
  3916. case NREDIR:
  3917. case NBACKGND:
  3918. n = n->nredir.n;
  3919. goto donode;
  3920. case NNOT:
  3921. cmdputs("!");
  3922. n = n->nnot.com;
  3923. donode:
  3924. cmdtxt(n);
  3925. break;
  3926. case NIF:
  3927. cmdputs("if ");
  3928. cmdtxt(n->nif.test);
  3929. cmdputs("; then ");
  3930. n = n->nif.ifpart;
  3931. if (n->nif.elsepart) {
  3932. cmdtxt(n);
  3933. cmdputs("; else ");
  3934. n = n->nif.elsepart;
  3935. }
  3936. p = "; fi";
  3937. goto dotail;
  3938. case NSUBSHELL:
  3939. cmdputs("(");
  3940. n = n->nredir.n;
  3941. p = ")";
  3942. goto dotail;
  3943. case NWHILE:
  3944. p = "while ";
  3945. goto until;
  3946. case NUNTIL:
  3947. p = "until ";
  3948. until:
  3949. cmdputs(p);
  3950. cmdtxt(n->nbinary.ch1);
  3951. n = n->nbinary.ch2;
  3952. p = "; done";
  3953. dodo:
  3954. cmdputs("; do ");
  3955. dotail:
  3956. cmdtxt(n);
  3957. goto dotail2;
  3958. case NFOR:
  3959. cmdputs("for ");
  3960. cmdputs(n->nfor.var);
  3961. cmdputs(" in ");
  3962. cmdlist(n->nfor.args, 1);
  3963. n = n->nfor.body;
  3964. p = "; done";
  3965. goto dodo;
  3966. case NDEFUN:
  3967. cmdputs(n->narg.text);
  3968. p = "() { ... }";
  3969. goto dotail2;
  3970. case NCMD:
  3971. cmdlist(n->ncmd.args, 1);
  3972. cmdlist(n->ncmd.redirect, 0);
  3973. break;
  3974. case NARG:
  3975. p = n->narg.text;
  3976. dotail2:
  3977. cmdputs(p);
  3978. break;
  3979. case NHERE:
  3980. case NXHERE:
  3981. p = "<<...";
  3982. goto dotail2;
  3983. case NCASE:
  3984. cmdputs("case ");
  3985. cmdputs(n->ncase.expr->narg.text);
  3986. cmdputs(" in ");
  3987. for (np = n->ncase.cases; np; np = np->nclist.next) {
  3988. cmdtxt(np->nclist.pattern);
  3989. cmdputs(") ");
  3990. cmdtxt(np->nclist.body);
  3991. cmdputs(";; ");
  3992. }
  3993. p = "esac";
  3994. goto dotail2;
  3995. case NTO:
  3996. p = ">";
  3997. goto redir;
  3998. case NCLOBBER:
  3999. p = ">|";
  4000. goto redir;
  4001. case NAPPEND:
  4002. p = ">>";
  4003. goto redir;
  4004. #if ENABLE_ASH_BASH_COMPAT
  4005. case NTO2:
  4006. #endif
  4007. case NTOFD:
  4008. p = ">&";
  4009. goto redir;
  4010. case NFROM:
  4011. p = "<";
  4012. goto redir;
  4013. case NFROMFD:
  4014. p = "<&";
  4015. goto redir;
  4016. case NFROMTO:
  4017. p = "<>";
  4018. redir:
  4019. cmdputs(utoa(n->nfile.fd));
  4020. cmdputs(p);
  4021. if (n->type == NTOFD || n->type == NFROMFD) {
  4022. cmdputs(utoa(n->ndup.dupfd));
  4023. break;
  4024. }
  4025. n = n->nfile.fname;
  4026. goto donode;
  4027. }
  4028. }
  4029. static char *
  4030. commandtext(union node *n)
  4031. {
  4032. char *name;
  4033. STARTSTACKSTR(cmdnextc);
  4034. cmdtxt(n);
  4035. name = stackblock();
  4036. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4037. name, cmdnextc, cmdnextc));
  4038. return ckstrdup(name);
  4039. }
  4040. #endif /* JOBS */
  4041. /*
  4042. * Fork off a subshell. If we are doing job control, give the subshell its
  4043. * own process group. Jp is a job structure that the job is to be added to.
  4044. * N is the command that will be evaluated by the child. Both jp and n may
  4045. * be NULL. The mode parameter can be one of the following:
  4046. * FORK_FG - Fork off a foreground process.
  4047. * FORK_BG - Fork off a background process.
  4048. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4049. * process group even if job control is on.
  4050. *
  4051. * When job control is turned off, background processes have their standard
  4052. * input redirected to /dev/null (except for the second and later processes
  4053. * in a pipeline).
  4054. *
  4055. * Called with interrupts off.
  4056. */
  4057. /*
  4058. * Clear traps on a fork.
  4059. */
  4060. static void
  4061. clear_traps(void)
  4062. {
  4063. char **tp;
  4064. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4065. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4066. INT_OFF;
  4067. free(*tp);
  4068. *tp = NULL;
  4069. if (tp != &trap[0])
  4070. setsignal(tp - trap);
  4071. INT_ON;
  4072. }
  4073. }
  4074. }
  4075. /* Lives far away from here, needed for forkchild */
  4076. static void closescript(void);
  4077. /* Called after fork(), in child */
  4078. static void
  4079. forkchild(struct job *jp, /*union node *n,*/ int mode)
  4080. {
  4081. int oldlvl;
  4082. TRACE(("Child shell %d\n", getpid()));
  4083. oldlvl = shlvl;
  4084. shlvl++;
  4085. closescript();
  4086. clear_traps();
  4087. #if JOBS
  4088. /* do job control only in root shell */
  4089. doing_jobctl = 0;
  4090. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  4091. pid_t pgrp;
  4092. if (jp->nprocs == 0)
  4093. pgrp = getpid();
  4094. else
  4095. pgrp = jp->ps[0].pid;
  4096. /* This can fail because we are doing it in the parent also */
  4097. (void)setpgid(0, pgrp);
  4098. if (mode == FORK_FG)
  4099. xtcsetpgrp(ttyfd, pgrp);
  4100. setsignal(SIGTSTP);
  4101. setsignal(SIGTTOU);
  4102. } else
  4103. #endif
  4104. if (mode == FORK_BG) {
  4105. ignoresig(SIGINT);
  4106. ignoresig(SIGQUIT);
  4107. if (jp->nprocs == 0) {
  4108. close(0);
  4109. if (open(bb_dev_null, O_RDONLY) != 0)
  4110. ash_msg_and_raise_error("can't open %s", bb_dev_null);
  4111. }
  4112. }
  4113. if (!oldlvl && iflag) {
  4114. setsignal(SIGINT);
  4115. setsignal(SIGQUIT);
  4116. setsignal(SIGTERM);
  4117. }
  4118. for (jp = curjob; jp; jp = jp->prev_job)
  4119. freejob(jp);
  4120. jobless = 0;
  4121. }
  4122. /* Called after fork(), in parent */
  4123. #if !JOBS
  4124. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4125. #endif
  4126. static void
  4127. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4128. {
  4129. TRACE(("In parent shell: child = %d\n", pid));
  4130. if (!jp) {
  4131. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4132. continue;
  4133. jobless++;
  4134. return;
  4135. }
  4136. #if JOBS
  4137. if (mode != FORK_NOJOB && jp->jobctl) {
  4138. int pgrp;
  4139. if (jp->nprocs == 0)
  4140. pgrp = pid;
  4141. else
  4142. pgrp = jp->ps[0].pid;
  4143. /* This can fail because we are doing it in the child also */
  4144. setpgid(pid, pgrp);
  4145. }
  4146. #endif
  4147. if (mode == FORK_BG) {
  4148. backgndpid = pid; /* set $! */
  4149. set_curjob(jp, CUR_RUNNING);
  4150. }
  4151. if (jp) {
  4152. struct procstat *ps = &jp->ps[jp->nprocs++];
  4153. ps->pid = pid;
  4154. ps->status = -1;
  4155. ps->cmd = nullstr;
  4156. #if JOBS
  4157. if (doing_jobctl && n)
  4158. ps->cmd = commandtext(n);
  4159. #endif
  4160. }
  4161. }
  4162. static int
  4163. forkshell(struct job *jp, union node *n, int mode)
  4164. {
  4165. int pid;
  4166. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4167. pid = fork();
  4168. if (pid < 0) {
  4169. TRACE(("Fork failed, errno=%d", errno));
  4170. if (jp)
  4171. freejob(jp);
  4172. ash_msg_and_raise_error("can't fork");
  4173. }
  4174. if (pid == 0)
  4175. forkchild(jp, /*n,*/ mode);
  4176. else
  4177. forkparent(jp, n, mode, pid);
  4178. return pid;
  4179. }
  4180. /*
  4181. * Wait for job to finish.
  4182. *
  4183. * Under job control we have the problem that while a child process is
  4184. * running interrupts generated by the user are sent to the child but not
  4185. * to the shell. This means that an infinite loop started by an inter-
  4186. * active user may be hard to kill. With job control turned off, an
  4187. * interactive user may place an interactive program inside a loop. If
  4188. * the interactive program catches interrupts, the user doesn't want
  4189. * these interrupts to also abort the loop. The approach we take here
  4190. * is to have the shell ignore interrupt signals while waiting for a
  4191. * foreground process to terminate, and then send itself an interrupt
  4192. * signal if the child process was terminated by an interrupt signal.
  4193. * Unfortunately, some programs want to do a bit of cleanup and then
  4194. * exit on interrupt; unless these processes terminate themselves by
  4195. * sending a signal to themselves (instead of calling exit) they will
  4196. * confuse this approach.
  4197. *
  4198. * Called with interrupts off.
  4199. */
  4200. static int
  4201. waitforjob(struct job *jp)
  4202. {
  4203. int st;
  4204. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4205. while (jp->state == JOBRUNNING) {
  4206. dowait(DOWAIT_BLOCK, jp);
  4207. }
  4208. st = getstatus(jp);
  4209. #if JOBS
  4210. if (jp->jobctl) {
  4211. xtcsetpgrp(ttyfd, rootpid);
  4212. /*
  4213. * This is truly gross.
  4214. * If we're doing job control, then we did a TIOCSPGRP which
  4215. * caused us (the shell) to no longer be in the controlling
  4216. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4217. * intuit from the subprocess exit status whether a SIGINT
  4218. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4219. */
  4220. if (jp->sigint) /* TODO: do the same with all signals */
  4221. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4222. }
  4223. if (jp->state == JOBDONE)
  4224. #endif
  4225. freejob(jp);
  4226. return st;
  4227. }
  4228. /*
  4229. * return 1 if there are stopped jobs, otherwise 0
  4230. */
  4231. static int
  4232. stoppedjobs(void)
  4233. {
  4234. struct job *jp;
  4235. int retval;
  4236. retval = 0;
  4237. if (job_warning)
  4238. goto out;
  4239. jp = curjob;
  4240. if (jp && jp->state == JOBSTOPPED) {
  4241. out2str("You have stopped jobs.\n");
  4242. job_warning = 2;
  4243. retval++;
  4244. }
  4245. out:
  4246. return retval;
  4247. }
  4248. /* ============ redir.c
  4249. *
  4250. * Code for dealing with input/output redirection.
  4251. */
  4252. #define EMPTY -2 /* marks an unused slot in redirtab */
  4253. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4254. /*
  4255. * Open a file in noclobber mode.
  4256. * The code was copied from bash.
  4257. */
  4258. static int
  4259. noclobberopen(const char *fname)
  4260. {
  4261. int r, fd;
  4262. struct stat finfo, finfo2;
  4263. /*
  4264. * If the file exists and is a regular file, return an error
  4265. * immediately.
  4266. */
  4267. r = stat(fname, &finfo);
  4268. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4269. errno = EEXIST;
  4270. return -1;
  4271. }
  4272. /*
  4273. * If the file was not present (r != 0), make sure we open it
  4274. * exclusively so that if it is created before we open it, our open
  4275. * will fail. Make sure that we do not truncate an existing file.
  4276. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4277. * file was not a regular file, we leave O_EXCL off.
  4278. */
  4279. if (r != 0)
  4280. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4281. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4282. /* If the open failed, return the file descriptor right away. */
  4283. if (fd < 0)
  4284. return fd;
  4285. /*
  4286. * OK, the open succeeded, but the file may have been changed from a
  4287. * non-regular file to a regular file between the stat and the open.
  4288. * We are assuming that the O_EXCL open handles the case where FILENAME
  4289. * did not exist and is symlinked to an existing file between the stat
  4290. * and open.
  4291. */
  4292. /*
  4293. * If we can open it and fstat the file descriptor, and neither check
  4294. * revealed that it was a regular file, and the file has not been
  4295. * replaced, return the file descriptor.
  4296. */
  4297. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4298. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4299. return fd;
  4300. /* The file has been replaced. badness. */
  4301. close(fd);
  4302. errno = EEXIST;
  4303. return -1;
  4304. }
  4305. /*
  4306. * Handle here documents. Normally we fork off a process to write the
  4307. * data to a pipe. If the document is short, we can stuff the data in
  4308. * the pipe without forking.
  4309. */
  4310. /* openhere needs this forward reference */
  4311. static void expandhere(union node *arg, int fd);
  4312. static int
  4313. openhere(union node *redir)
  4314. {
  4315. int pip[2];
  4316. size_t len = 0;
  4317. if (pipe(pip) < 0)
  4318. ash_msg_and_raise_error("pipe call failed");
  4319. if (redir->type == NHERE) {
  4320. len = strlen(redir->nhere.doc->narg.text);
  4321. if (len <= PIPE_BUF) {
  4322. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4323. goto out;
  4324. }
  4325. }
  4326. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4327. /* child */
  4328. close(pip[0]);
  4329. signal(SIGINT, SIG_IGN);
  4330. signal(SIGQUIT, SIG_IGN);
  4331. signal(SIGHUP, SIG_IGN);
  4332. #ifdef SIGTSTP
  4333. signal(SIGTSTP, SIG_IGN);
  4334. #endif
  4335. signal(SIGPIPE, SIG_DFL);
  4336. if (redir->type == NHERE)
  4337. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4338. else /* NXHERE */
  4339. expandhere(redir->nhere.doc, pip[1]);
  4340. _exit(EXIT_SUCCESS);
  4341. }
  4342. out:
  4343. close(pip[1]);
  4344. return pip[0];
  4345. }
  4346. static int
  4347. openredirect(union node *redir)
  4348. {
  4349. char *fname;
  4350. int f;
  4351. switch (redir->nfile.type) {
  4352. case NFROM:
  4353. fname = redir->nfile.expfname;
  4354. f = open(fname, O_RDONLY);
  4355. if (f < 0)
  4356. goto eopen;
  4357. break;
  4358. case NFROMTO:
  4359. fname = redir->nfile.expfname;
  4360. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4361. if (f < 0)
  4362. goto ecreate;
  4363. break;
  4364. case NTO:
  4365. #if ENABLE_ASH_BASH_COMPAT
  4366. case NTO2:
  4367. #endif
  4368. /* Take care of noclobber mode. */
  4369. if (Cflag) {
  4370. fname = redir->nfile.expfname;
  4371. f = noclobberopen(fname);
  4372. if (f < 0)
  4373. goto ecreate;
  4374. break;
  4375. }
  4376. /* FALLTHROUGH */
  4377. case NCLOBBER:
  4378. fname = redir->nfile.expfname;
  4379. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4380. if (f < 0)
  4381. goto ecreate;
  4382. break;
  4383. case NAPPEND:
  4384. fname = redir->nfile.expfname;
  4385. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4386. if (f < 0)
  4387. goto ecreate;
  4388. break;
  4389. default:
  4390. #if DEBUG
  4391. abort();
  4392. #endif
  4393. /* Fall through to eliminate warning. */
  4394. /* Our single caller does this itself */
  4395. // case NTOFD:
  4396. // case NFROMFD:
  4397. // f = -1;
  4398. // break;
  4399. case NHERE:
  4400. case NXHERE:
  4401. f = openhere(redir);
  4402. break;
  4403. }
  4404. return f;
  4405. ecreate:
  4406. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4407. eopen:
  4408. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4409. }
  4410. /*
  4411. * Copy a file descriptor to be >= to. Returns -1
  4412. * if the source file descriptor is closed, EMPTY if there are no unused
  4413. * file descriptors left.
  4414. */
  4415. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4416. * old code was doing close(to) prior to copyfd() to achieve the same */
  4417. enum {
  4418. COPYFD_EXACT = (int)~(INT_MAX),
  4419. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4420. };
  4421. static int
  4422. copyfd(int from, int to)
  4423. {
  4424. int newfd;
  4425. if (to & COPYFD_EXACT) {
  4426. to &= ~COPYFD_EXACT;
  4427. /*if (from != to)*/
  4428. newfd = dup2(from, to);
  4429. } else {
  4430. newfd = fcntl(from, F_DUPFD, to);
  4431. }
  4432. if (newfd < 0) {
  4433. if (errno == EMFILE)
  4434. return EMPTY;
  4435. /* Happens when source fd is not open: try "echo >&99" */
  4436. ash_msg_and_raise_error("%d: %m", from);
  4437. }
  4438. return newfd;
  4439. }
  4440. /* Struct def and variable are moved down to the first usage site */
  4441. struct two_fd_t {
  4442. int orig, copy;
  4443. };
  4444. struct redirtab {
  4445. struct redirtab *next;
  4446. int nullredirs;
  4447. int pair_count;
  4448. struct two_fd_t two_fd[0];
  4449. };
  4450. #define redirlist (G_var.redirlist)
  4451. static int need_to_remember(struct redirtab *rp, int fd)
  4452. {
  4453. int i;
  4454. if (!rp) /* remembering was not requested */
  4455. return 0;
  4456. for (i = 0; i < rp->pair_count; i++) {
  4457. if (rp->two_fd[i].orig == fd) {
  4458. /* already remembered */
  4459. return 0;
  4460. }
  4461. }
  4462. return 1;
  4463. }
  4464. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4465. static int is_hidden_fd(struct redirtab *rp, int fd)
  4466. {
  4467. int i;
  4468. struct parsefile *pf;
  4469. if (fd == -1)
  4470. return 0;
  4471. pf = g_parsefile;
  4472. while (pf) {
  4473. if (fd == pf->fd) {
  4474. return 1;
  4475. }
  4476. pf = pf->prev;
  4477. }
  4478. if (!rp)
  4479. return 0;
  4480. fd |= COPYFD_RESTORE;
  4481. for (i = 0; i < rp->pair_count; i++) {
  4482. if (rp->two_fd[i].copy == fd) {
  4483. return 1;
  4484. }
  4485. }
  4486. return 0;
  4487. }
  4488. /*
  4489. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4490. * old file descriptors are stashed away so that the redirection can be
  4491. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4492. * standard output, and the standard error if it becomes a duplicate of
  4493. * stdout, is saved in memory.
  4494. */
  4495. /* flags passed to redirect */
  4496. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4497. #define REDIR_SAVEFD2 03 /* set preverrout */
  4498. static void
  4499. redirect(union node *redir, int flags)
  4500. {
  4501. struct redirtab *sv;
  4502. int sv_pos;
  4503. int i;
  4504. int fd;
  4505. int newfd;
  4506. int copied_fd2 = -1;
  4507. g_nullredirs++;
  4508. if (!redir) {
  4509. return;
  4510. }
  4511. sv = NULL;
  4512. sv_pos = 0;
  4513. INT_OFF;
  4514. if (flags & REDIR_PUSH) {
  4515. union node *tmp = redir;
  4516. do {
  4517. sv_pos++;
  4518. #if ENABLE_ASH_BASH_COMPAT
  4519. if (redir->nfile.type == NTO2)
  4520. sv_pos++;
  4521. #endif
  4522. tmp = tmp->nfile.next;
  4523. } while (tmp);
  4524. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4525. sv->next = redirlist;
  4526. sv->pair_count = sv_pos;
  4527. redirlist = sv;
  4528. sv->nullredirs = g_nullredirs - 1;
  4529. g_nullredirs = 0;
  4530. while (sv_pos > 0) {
  4531. sv_pos--;
  4532. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4533. }
  4534. }
  4535. do {
  4536. fd = redir->nfile.fd;
  4537. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4538. int right_fd = redir->ndup.dupfd;
  4539. /* redirect from/to same file descriptor? */
  4540. if (right_fd == fd)
  4541. continue;
  4542. /* echo >&10 and 10 is a fd opened to the sh script? */
  4543. if (is_hidden_fd(sv, right_fd)) {
  4544. errno = EBADF; /* as if it is closed */
  4545. ash_msg_and_raise_error("%d: %m", right_fd);
  4546. }
  4547. newfd = -1;
  4548. } else {
  4549. newfd = openredirect(redir); /* always >= 0 */
  4550. if (fd == newfd) {
  4551. /* Descriptor wasn't open before redirect.
  4552. * Mark it for close in the future */
  4553. if (need_to_remember(sv, fd)) {
  4554. goto remember_to_close;
  4555. }
  4556. continue;
  4557. }
  4558. }
  4559. #if ENABLE_ASH_BASH_COMPAT
  4560. redirect_more:
  4561. #endif
  4562. if (need_to_remember(sv, fd)) {
  4563. /* Copy old descriptor */
  4564. i = fcntl(fd, F_DUPFD, 10);
  4565. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4566. * are closed in popredir() in the child, preventing them from leaking
  4567. * into child. (popredir() also cleans up the mess in case of failures)
  4568. */
  4569. if (i == -1) {
  4570. i = errno;
  4571. if (i != EBADF) {
  4572. /* Strange error (e.g. "too many files" EMFILE?) */
  4573. if (newfd >= 0)
  4574. close(newfd);
  4575. errno = i;
  4576. ash_msg_and_raise_error("%d: %m", fd);
  4577. /* NOTREACHED */
  4578. }
  4579. /* EBADF: it is not open - good, remember to close it */
  4580. remember_to_close:
  4581. i = CLOSED;
  4582. } else { /* fd is open, save its copy */
  4583. /* "exec fd>&-" should not close fds
  4584. * which point to script file(s).
  4585. * Force them to be restored afterwards */
  4586. if (is_hidden_fd(sv, fd))
  4587. i |= COPYFD_RESTORE;
  4588. }
  4589. if (fd == 2)
  4590. copied_fd2 = i;
  4591. sv->two_fd[sv_pos].orig = fd;
  4592. sv->two_fd[sv_pos].copy = i;
  4593. sv_pos++;
  4594. }
  4595. if (newfd < 0) {
  4596. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4597. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4598. /* Don't want to trigger debugging */
  4599. if (fd != -1)
  4600. close(fd);
  4601. } else {
  4602. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4603. }
  4604. } else if (fd != newfd) { /* move newfd to fd */
  4605. copyfd(newfd, fd | COPYFD_EXACT);
  4606. #if ENABLE_ASH_BASH_COMPAT
  4607. if (!(redir->nfile.type == NTO2 && fd == 2))
  4608. #endif
  4609. close(newfd);
  4610. }
  4611. #if ENABLE_ASH_BASH_COMPAT
  4612. if (redir->nfile.type == NTO2 && fd == 1) {
  4613. /* We already redirected it to fd 1, now copy it to 2 */
  4614. newfd = 1;
  4615. fd = 2;
  4616. goto redirect_more;
  4617. }
  4618. #endif
  4619. } while ((redir = redir->nfile.next) != NULL);
  4620. INT_ON;
  4621. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4622. preverrout_fd = copied_fd2;
  4623. }
  4624. /*
  4625. * Undo the effects of the last redirection.
  4626. */
  4627. static void
  4628. popredir(int drop, int restore)
  4629. {
  4630. struct redirtab *rp;
  4631. int i;
  4632. if (--g_nullredirs >= 0)
  4633. return;
  4634. INT_OFF;
  4635. rp = redirlist;
  4636. for (i = 0; i < rp->pair_count; i++) {
  4637. int fd = rp->two_fd[i].orig;
  4638. int copy = rp->two_fd[i].copy;
  4639. if (copy == CLOSED) {
  4640. if (!drop)
  4641. close(fd);
  4642. continue;
  4643. }
  4644. if (copy != EMPTY) {
  4645. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4646. copy &= ~COPYFD_RESTORE;
  4647. /*close(fd);*/
  4648. copyfd(copy, fd | COPYFD_EXACT);
  4649. }
  4650. close(copy & ~COPYFD_RESTORE);
  4651. }
  4652. }
  4653. redirlist = rp->next;
  4654. g_nullredirs = rp->nullredirs;
  4655. free(rp);
  4656. INT_ON;
  4657. }
  4658. /*
  4659. * Undo all redirections. Called on error or interrupt.
  4660. */
  4661. /*
  4662. * Discard all saved file descriptors.
  4663. */
  4664. static void
  4665. clearredir(int drop)
  4666. {
  4667. for (;;) {
  4668. g_nullredirs = 0;
  4669. if (!redirlist)
  4670. break;
  4671. popredir(drop, /*restore:*/ 0);
  4672. }
  4673. }
  4674. static int
  4675. redirectsafe(union node *redir, int flags)
  4676. {
  4677. int err;
  4678. volatile int saveint;
  4679. struct jmploc *volatile savehandler = exception_handler;
  4680. struct jmploc jmploc;
  4681. SAVE_INT(saveint);
  4682. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4683. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4684. if (!err) {
  4685. exception_handler = &jmploc;
  4686. redirect(redir, flags);
  4687. }
  4688. exception_handler = savehandler;
  4689. if (err && exception != EXERROR)
  4690. longjmp(exception_handler->loc, 1);
  4691. RESTORE_INT(saveint);
  4692. return err;
  4693. }
  4694. /* ============ Routines to expand arguments to commands
  4695. *
  4696. * We have to deal with backquotes, shell variables, and file metacharacters.
  4697. */
  4698. #if ENABLE_ASH_MATH_SUPPORT_64
  4699. typedef int64_t arith_t;
  4700. #define arith_t_type long long
  4701. #else
  4702. typedef long arith_t;
  4703. #define arith_t_type long
  4704. #endif
  4705. #if ENABLE_ASH_MATH_SUPPORT
  4706. static arith_t dash_arith(const char *);
  4707. static arith_t arith(const char *expr, int *perrcode);
  4708. #endif
  4709. /*
  4710. * expandarg flags
  4711. */
  4712. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4713. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4714. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4715. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4716. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4717. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4718. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4719. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4720. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4721. /*
  4722. * _rmescape() flags
  4723. */
  4724. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4725. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4726. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4727. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4728. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4729. /*
  4730. * Structure specifying which parts of the string should be searched
  4731. * for IFS characters.
  4732. */
  4733. struct ifsregion {
  4734. struct ifsregion *next; /* next region in list */
  4735. int begoff; /* offset of start of region */
  4736. int endoff; /* offset of end of region */
  4737. int nulonly; /* search for nul bytes only */
  4738. };
  4739. struct arglist {
  4740. struct strlist *list;
  4741. struct strlist **lastp;
  4742. };
  4743. /* output of current string */
  4744. static char *expdest;
  4745. /* list of back quote expressions */
  4746. static struct nodelist *argbackq;
  4747. /* first struct in list of ifs regions */
  4748. static struct ifsregion ifsfirst;
  4749. /* last struct in list */
  4750. static struct ifsregion *ifslastp;
  4751. /* holds expanded arg list */
  4752. static struct arglist exparg;
  4753. /*
  4754. * Our own itoa().
  4755. */
  4756. static int
  4757. cvtnum(arith_t num)
  4758. {
  4759. int len;
  4760. expdest = makestrspace(32, expdest);
  4761. #if ENABLE_ASH_MATH_SUPPORT_64
  4762. len = fmtstr(expdest, 32, "%lld", (long long) num);
  4763. #else
  4764. len = fmtstr(expdest, 32, "%ld", num);
  4765. #endif
  4766. STADJUST(len, expdest);
  4767. return len;
  4768. }
  4769. static size_t
  4770. esclen(const char *start, const char *p)
  4771. {
  4772. size_t esc = 0;
  4773. while (p > start && *--p == CTLESC) {
  4774. esc++;
  4775. }
  4776. return esc;
  4777. }
  4778. /*
  4779. * Remove any CTLESC characters from a string.
  4780. */
  4781. static char *
  4782. _rmescapes(char *str, int flag)
  4783. {
  4784. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4785. char *p, *q, *r;
  4786. unsigned inquotes;
  4787. int notescaped;
  4788. int globbing;
  4789. p = strpbrk(str, qchars);
  4790. if (!p) {
  4791. return str;
  4792. }
  4793. q = p;
  4794. r = str;
  4795. if (flag & RMESCAPE_ALLOC) {
  4796. size_t len = p - str;
  4797. size_t fulllen = len + strlen(p) + 1;
  4798. if (flag & RMESCAPE_GROW) {
  4799. r = makestrspace(fulllen, expdest);
  4800. } else if (flag & RMESCAPE_HEAP) {
  4801. r = ckmalloc(fulllen);
  4802. } else {
  4803. r = stalloc(fulllen);
  4804. }
  4805. q = r;
  4806. if (len > 0) {
  4807. q = (char *)memcpy(q, str, len) + len;
  4808. }
  4809. }
  4810. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4811. globbing = flag & RMESCAPE_GLOB;
  4812. notescaped = globbing;
  4813. while (*p) {
  4814. if (*p == CTLQUOTEMARK) {
  4815. inquotes = ~inquotes;
  4816. p++;
  4817. notescaped = globbing;
  4818. continue;
  4819. }
  4820. if (*p == '\\') {
  4821. /* naked back slash */
  4822. notescaped = 0;
  4823. goto copy;
  4824. }
  4825. if (*p == CTLESC) {
  4826. p++;
  4827. if (notescaped && inquotes && *p != '/') {
  4828. *q++ = '\\';
  4829. }
  4830. }
  4831. notescaped = globbing;
  4832. copy:
  4833. *q++ = *p++;
  4834. }
  4835. *q = '\0';
  4836. if (flag & RMESCAPE_GROW) {
  4837. expdest = r;
  4838. STADJUST(q - r + 1, expdest);
  4839. }
  4840. return r;
  4841. }
  4842. #define rmescapes(p) _rmescapes((p), 0)
  4843. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4844. /*
  4845. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4846. *
  4847. * Returns an stalloced string.
  4848. */
  4849. static char *
  4850. preglob(const char *pattern, int quoted, int flag)
  4851. {
  4852. flag |= RMESCAPE_GLOB;
  4853. if (quoted) {
  4854. flag |= RMESCAPE_QUOTED;
  4855. }
  4856. return _rmescapes((char *)pattern, flag);
  4857. }
  4858. /*
  4859. * Put a string on the stack.
  4860. */
  4861. static void
  4862. memtodest(const char *p, size_t len, int syntax, int quotes)
  4863. {
  4864. char *q = expdest;
  4865. q = makestrspace(len * 2, q);
  4866. while (len--) {
  4867. int c = signed_char2int(*p++);
  4868. if (!c)
  4869. continue;
  4870. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4871. USTPUTC(CTLESC, q);
  4872. USTPUTC(c, q);
  4873. }
  4874. expdest = q;
  4875. }
  4876. static void
  4877. strtodest(const char *p, int syntax, int quotes)
  4878. {
  4879. memtodest(p, strlen(p), syntax, quotes);
  4880. }
  4881. /*
  4882. * Record the fact that we have to scan this region of the
  4883. * string for IFS characters.
  4884. */
  4885. static void
  4886. recordregion(int start, int end, int nulonly)
  4887. {
  4888. struct ifsregion *ifsp;
  4889. if (ifslastp == NULL) {
  4890. ifsp = &ifsfirst;
  4891. } else {
  4892. INT_OFF;
  4893. ifsp = ckzalloc(sizeof(*ifsp));
  4894. /*ifsp->next = NULL; - ckzalloc did it */
  4895. ifslastp->next = ifsp;
  4896. INT_ON;
  4897. }
  4898. ifslastp = ifsp;
  4899. ifslastp->begoff = start;
  4900. ifslastp->endoff = end;
  4901. ifslastp->nulonly = nulonly;
  4902. }
  4903. static void
  4904. removerecordregions(int endoff)
  4905. {
  4906. if (ifslastp == NULL)
  4907. return;
  4908. if (ifsfirst.endoff > endoff) {
  4909. while (ifsfirst.next != NULL) {
  4910. struct ifsregion *ifsp;
  4911. INT_OFF;
  4912. ifsp = ifsfirst.next->next;
  4913. free(ifsfirst.next);
  4914. ifsfirst.next = ifsp;
  4915. INT_ON;
  4916. }
  4917. if (ifsfirst.begoff > endoff)
  4918. ifslastp = NULL;
  4919. else {
  4920. ifslastp = &ifsfirst;
  4921. ifsfirst.endoff = endoff;
  4922. }
  4923. return;
  4924. }
  4925. ifslastp = &ifsfirst;
  4926. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4927. ifslastp=ifslastp->next;
  4928. while (ifslastp->next != NULL) {
  4929. struct ifsregion *ifsp;
  4930. INT_OFF;
  4931. ifsp = ifslastp->next->next;
  4932. free(ifslastp->next);
  4933. ifslastp->next = ifsp;
  4934. INT_ON;
  4935. }
  4936. if (ifslastp->endoff > endoff)
  4937. ifslastp->endoff = endoff;
  4938. }
  4939. static char *
  4940. exptilde(char *startp, char *p, int flag)
  4941. {
  4942. char c;
  4943. char *name;
  4944. struct passwd *pw;
  4945. const char *home;
  4946. int quotes = flag & (EXP_FULL | EXP_CASE);
  4947. int startloc;
  4948. name = p + 1;
  4949. while ((c = *++p) != '\0') {
  4950. switch (c) {
  4951. case CTLESC:
  4952. return startp;
  4953. case CTLQUOTEMARK:
  4954. return startp;
  4955. case ':':
  4956. if (flag & EXP_VARTILDE)
  4957. goto done;
  4958. break;
  4959. case '/':
  4960. case CTLENDVAR:
  4961. goto done;
  4962. }
  4963. }
  4964. done:
  4965. *p = '\0';
  4966. if (*name == '\0') {
  4967. home = lookupvar(homestr);
  4968. } else {
  4969. pw = getpwnam(name);
  4970. if (pw == NULL)
  4971. goto lose;
  4972. home = pw->pw_dir;
  4973. }
  4974. if (!home || !*home)
  4975. goto lose;
  4976. *p = c;
  4977. startloc = expdest - (char *)stackblock();
  4978. strtodest(home, SQSYNTAX, quotes);
  4979. recordregion(startloc, expdest - (char *)stackblock(), 0);
  4980. return p;
  4981. lose:
  4982. *p = c;
  4983. return startp;
  4984. }
  4985. /*
  4986. * Execute a command inside back quotes. If it's a builtin command, we
  4987. * want to save its output in a block obtained from malloc. Otherwise
  4988. * we fork off a subprocess and get the output of the command via a pipe.
  4989. * Should be called with interrupts off.
  4990. */
  4991. struct backcmd { /* result of evalbackcmd */
  4992. int fd; /* file descriptor to read from */
  4993. int nleft; /* number of chars in buffer */
  4994. char *buf; /* buffer */
  4995. struct job *jp; /* job structure for command */
  4996. };
  4997. /* These forward decls are needed to use "eval" code for backticks handling: */
  4998. static uint8_t back_exitstatus; /* exit status of backquoted command */
  4999. #define EV_EXIT 01 /* exit after evaluating tree */
  5000. static void evaltree(union node *, int);
  5001. static void
  5002. evalbackcmd(union node *n, struct backcmd *result)
  5003. {
  5004. int saveherefd;
  5005. result->fd = -1;
  5006. result->buf = NULL;
  5007. result->nleft = 0;
  5008. result->jp = NULL;
  5009. if (n == NULL) {
  5010. goto out;
  5011. }
  5012. saveherefd = herefd;
  5013. herefd = -1;
  5014. {
  5015. int pip[2];
  5016. struct job *jp;
  5017. if (pipe(pip) < 0)
  5018. ash_msg_and_raise_error("pipe call failed");
  5019. jp = makejob(/*n,*/ 1);
  5020. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5021. FORCE_INT_ON;
  5022. close(pip[0]);
  5023. if (pip[1] != 1) {
  5024. /*close(1);*/
  5025. copyfd(pip[1], 1 | COPYFD_EXACT);
  5026. close(pip[1]);
  5027. }
  5028. eflag = 0;
  5029. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5030. /* NOTREACHED */
  5031. }
  5032. close(pip[1]);
  5033. result->fd = pip[0];
  5034. result->jp = jp;
  5035. }
  5036. herefd = saveherefd;
  5037. out:
  5038. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5039. result->fd, result->buf, result->nleft, result->jp));
  5040. }
  5041. /*
  5042. * Expand stuff in backwards quotes.
  5043. */
  5044. static void
  5045. expbackq(union node *cmd, int quoted, int quotes)
  5046. {
  5047. struct backcmd in;
  5048. int i;
  5049. char buf[128];
  5050. char *p;
  5051. char *dest;
  5052. int startloc;
  5053. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5054. struct stackmark smark;
  5055. INT_OFF;
  5056. setstackmark(&smark);
  5057. dest = expdest;
  5058. startloc = dest - (char *)stackblock();
  5059. grabstackstr(dest);
  5060. evalbackcmd(cmd, &in);
  5061. popstackmark(&smark);
  5062. p = in.buf;
  5063. i = in.nleft;
  5064. if (i == 0)
  5065. goto read;
  5066. for (;;) {
  5067. memtodest(p, i, syntax, quotes);
  5068. read:
  5069. if (in.fd < 0)
  5070. break;
  5071. i = nonblock_safe_read(in.fd, buf, sizeof(buf));
  5072. TRACE(("expbackq: read returns %d\n", i));
  5073. if (i <= 0)
  5074. break;
  5075. p = buf;
  5076. }
  5077. free(in.buf);
  5078. if (in.fd >= 0) {
  5079. close(in.fd);
  5080. back_exitstatus = waitforjob(in.jp);
  5081. }
  5082. INT_ON;
  5083. /* Eat all trailing newlines */
  5084. dest = expdest;
  5085. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5086. STUNPUTC(dest);
  5087. expdest = dest;
  5088. if (quoted == 0)
  5089. recordregion(startloc, dest - (char *)stackblock(), 0);
  5090. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  5091. (dest - (char *)stackblock()) - startloc,
  5092. (dest - (char *)stackblock()) - startloc,
  5093. stackblock() + startloc));
  5094. }
  5095. #if ENABLE_ASH_MATH_SUPPORT
  5096. /*
  5097. * Expand arithmetic expression. Backup to start of expression,
  5098. * evaluate, place result in (backed up) result, adjust string position.
  5099. */
  5100. static void
  5101. expari(int quotes)
  5102. {
  5103. char *p, *start;
  5104. int begoff;
  5105. int flag;
  5106. int len;
  5107. /* ifsfree(); */
  5108. /*
  5109. * This routine is slightly over-complicated for
  5110. * efficiency. Next we scan backwards looking for the
  5111. * start of arithmetic.
  5112. */
  5113. start = stackblock();
  5114. p = expdest - 1;
  5115. *p = '\0';
  5116. p--;
  5117. do {
  5118. int esc;
  5119. while (*p != CTLARI) {
  5120. p--;
  5121. #if DEBUG
  5122. if (p < start) {
  5123. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5124. }
  5125. #endif
  5126. }
  5127. esc = esclen(start, p);
  5128. if (!(esc % 2)) {
  5129. break;
  5130. }
  5131. p -= esc + 1;
  5132. } while (1);
  5133. begoff = p - start;
  5134. removerecordregions(begoff);
  5135. flag = p[1];
  5136. expdest = p;
  5137. if (quotes)
  5138. rmescapes(p + 2);
  5139. len = cvtnum(dash_arith(p + 2));
  5140. if (flag != '"')
  5141. recordregion(begoff, begoff + len, 0);
  5142. }
  5143. #endif
  5144. /* argstr needs it */
  5145. static char *evalvar(char *p, int flag, struct strlist *var_str_list);
  5146. /*
  5147. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5148. * characters to allow for further processing. Otherwise treat
  5149. * $@ like $* since no splitting will be performed.
  5150. *
  5151. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5152. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5153. * for correct expansion of "B=$A" word.
  5154. */
  5155. static void
  5156. argstr(char *p, int flag, struct strlist *var_str_list)
  5157. {
  5158. static const char spclchars[] ALIGN1 = {
  5159. '=',
  5160. ':',
  5161. CTLQUOTEMARK,
  5162. CTLENDVAR,
  5163. CTLESC,
  5164. CTLVAR,
  5165. CTLBACKQ,
  5166. CTLBACKQ | CTLQUOTE,
  5167. #if ENABLE_ASH_MATH_SUPPORT
  5168. CTLENDARI,
  5169. #endif
  5170. 0
  5171. };
  5172. const char *reject = spclchars;
  5173. int c;
  5174. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  5175. int breakall = flag & EXP_WORD;
  5176. int inquotes;
  5177. size_t length;
  5178. int startloc;
  5179. if (!(flag & EXP_VARTILDE)) {
  5180. reject += 2;
  5181. } else if (flag & EXP_VARTILDE2) {
  5182. reject++;
  5183. }
  5184. inquotes = 0;
  5185. length = 0;
  5186. if (flag & EXP_TILDE) {
  5187. char *q;
  5188. flag &= ~EXP_TILDE;
  5189. tilde:
  5190. q = p;
  5191. if (*q == CTLESC && (flag & EXP_QWORD))
  5192. q++;
  5193. if (*q == '~')
  5194. p = exptilde(p, q, flag);
  5195. }
  5196. start:
  5197. startloc = expdest - (char *)stackblock();
  5198. for (;;) {
  5199. length += strcspn(p + length, reject);
  5200. c = p[length];
  5201. if (c && (!(c & 0x80)
  5202. #if ENABLE_ASH_MATH_SUPPORT
  5203. || c == CTLENDARI
  5204. #endif
  5205. )) {
  5206. /* c == '=' || c == ':' || c == CTLENDARI */
  5207. length++;
  5208. }
  5209. if (length > 0) {
  5210. int newloc;
  5211. expdest = stack_nputstr(p, length, expdest);
  5212. newloc = expdest - (char *)stackblock();
  5213. if (breakall && !inquotes && newloc > startloc) {
  5214. recordregion(startloc, newloc, 0);
  5215. }
  5216. startloc = newloc;
  5217. }
  5218. p += length + 1;
  5219. length = 0;
  5220. switch (c) {
  5221. case '\0':
  5222. goto breakloop;
  5223. case '=':
  5224. if (flag & EXP_VARTILDE2) {
  5225. p--;
  5226. continue;
  5227. }
  5228. flag |= EXP_VARTILDE2;
  5229. reject++;
  5230. /* fall through */
  5231. case ':':
  5232. /*
  5233. * sort of a hack - expand tildes in variable
  5234. * assignments (after the first '=' and after ':'s).
  5235. */
  5236. if (*--p == '~') {
  5237. goto tilde;
  5238. }
  5239. continue;
  5240. }
  5241. switch (c) {
  5242. case CTLENDVAR: /* ??? */
  5243. goto breakloop;
  5244. case CTLQUOTEMARK:
  5245. /* "$@" syntax adherence hack */
  5246. if (
  5247. !inquotes &&
  5248. !memcmp(p, dolatstr, 4) &&
  5249. (p[4] == CTLQUOTEMARK || (
  5250. p[4] == CTLENDVAR &&
  5251. p[5] == CTLQUOTEMARK
  5252. ))
  5253. ) {
  5254. p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
  5255. goto start;
  5256. }
  5257. inquotes = !inquotes;
  5258. addquote:
  5259. if (quotes) {
  5260. p--;
  5261. length++;
  5262. startloc++;
  5263. }
  5264. break;
  5265. case CTLESC:
  5266. startloc++;
  5267. length++;
  5268. goto addquote;
  5269. case CTLVAR:
  5270. p = evalvar(p, flag, var_str_list);
  5271. goto start;
  5272. case CTLBACKQ:
  5273. c = 0;
  5274. case CTLBACKQ|CTLQUOTE:
  5275. expbackq(argbackq->n, c, quotes);
  5276. argbackq = argbackq->next;
  5277. goto start;
  5278. #if ENABLE_ASH_MATH_SUPPORT
  5279. case CTLENDARI:
  5280. p--;
  5281. expari(quotes);
  5282. goto start;
  5283. #endif
  5284. }
  5285. }
  5286. breakloop:
  5287. ;
  5288. }
  5289. static char *
  5290. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
  5291. int zero)
  5292. {
  5293. // This commented out code was added by James Simmons <jsimmons@infradead.org>
  5294. // as part of a larger change when he added support for ${var/a/b}.
  5295. // However, it broke # and % operators:
  5296. //
  5297. //var=ababcdcd
  5298. // ok bad
  5299. //echo ${var#ab} abcdcd abcdcd
  5300. //echo ${var##ab} abcdcd abcdcd
  5301. //echo ${var#a*b} abcdcd ababcdcd (!)
  5302. //echo ${var##a*b} cdcd cdcd
  5303. //echo ${var#?} babcdcd ababcdcd (!)
  5304. //echo ${var##?} babcdcd babcdcd
  5305. //echo ${var#*} ababcdcd babcdcd (!)
  5306. //echo ${var##*}
  5307. //echo ${var%cd} ababcd ababcd
  5308. //echo ${var%%cd} ababcd abab (!)
  5309. //echo ${var%c*d} ababcd ababcd
  5310. //echo ${var%%c*d} abab ababcdcd (!)
  5311. //echo ${var%?} ababcdc ababcdc
  5312. //echo ${var%%?} ababcdc ababcdcd (!)
  5313. //echo ${var%*} ababcdcd ababcdcd
  5314. //echo ${var%%*}
  5315. //
  5316. // Commenting it back out helped. Remove it completely if it really
  5317. // is not needed.
  5318. char *loc, *loc2; //, *full;
  5319. char c;
  5320. loc = startp;
  5321. loc2 = rmesc;
  5322. do {
  5323. int match; // = strlen(str);
  5324. const char *s = loc2;
  5325. c = *loc2;
  5326. if (zero) {
  5327. *loc2 = '\0';
  5328. s = rmesc;
  5329. }
  5330. match = pmatch(str, s); // this line was deleted
  5331. // // chop off end if its '*'
  5332. // full = strrchr(str, '*');
  5333. // if (full && full != str)
  5334. // match--;
  5335. //
  5336. // // If str starts with '*' replace with s.
  5337. // if ((*str == '*') && strlen(s) >= match) {
  5338. // full = xstrdup(s);
  5339. // strncpy(full+strlen(s)-match+1, str+1, match-1);
  5340. // } else
  5341. // full = xstrndup(str, match);
  5342. // match = strncmp(s, full, strlen(full));
  5343. // free(full);
  5344. //
  5345. *loc2 = c;
  5346. if (match) // if (!match)
  5347. return loc;
  5348. if (quotes && *loc == CTLESC)
  5349. loc++;
  5350. loc++;
  5351. loc2++;
  5352. } while (c);
  5353. return 0;
  5354. }
  5355. static char *
  5356. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5357. int zero)
  5358. {
  5359. int esc = 0;
  5360. char *loc;
  5361. char *loc2;
  5362. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5363. int match;
  5364. char c = *loc2;
  5365. const char *s = loc2;
  5366. if (zero) {
  5367. *loc2 = '\0';
  5368. s = rmesc;
  5369. }
  5370. match = pmatch(str, s);
  5371. *loc2 = c;
  5372. if (match)
  5373. return loc;
  5374. loc--;
  5375. if (quotes) {
  5376. if (--esc < 0) {
  5377. esc = esclen(startp, loc);
  5378. }
  5379. if (esc % 2) {
  5380. esc--;
  5381. loc--;
  5382. }
  5383. }
  5384. }
  5385. return 0;
  5386. }
  5387. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5388. static void
  5389. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5390. {
  5391. const char *msg;
  5392. const char *tail;
  5393. tail = nullstr;
  5394. msg = "parameter not set";
  5395. if (umsg) {
  5396. if (*end == CTLENDVAR) {
  5397. if (varflags & VSNUL)
  5398. tail = " or null";
  5399. } else
  5400. msg = umsg;
  5401. }
  5402. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5403. }
  5404. #if ENABLE_ASH_BASH_COMPAT
  5405. static char *
  5406. parse_sub_pattern(char *arg, int inquotes)
  5407. {
  5408. char *idx, *repl = NULL;
  5409. unsigned char c;
  5410. idx = arg;
  5411. while (1) {
  5412. c = *arg;
  5413. if (!c)
  5414. break;
  5415. if (c == '/') {
  5416. /* Only the first '/' seen is our separator */
  5417. if (!repl) {
  5418. repl = idx + 1;
  5419. c = '\0';
  5420. }
  5421. }
  5422. *idx++ = c;
  5423. if (!inquotes && c == '\\' && arg[1] == '\\')
  5424. arg++; /* skip both \\, not just first one */
  5425. arg++;
  5426. }
  5427. *idx = c; /* NUL */
  5428. return repl;
  5429. }
  5430. #endif /* ENABLE_ASH_BASH_COMPAT */
  5431. static const char *
  5432. subevalvar(char *p, char *str, int strloc, int subtype,
  5433. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5434. {
  5435. struct nodelist *saveargbackq = argbackq;
  5436. char *startp;
  5437. char *loc;
  5438. char *rmesc, *rmescend;
  5439. USE_ASH_BASH_COMPAT(char *repl = NULL;)
  5440. USE_ASH_BASH_COMPAT(char null = '\0';)
  5441. USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5442. int saveherefd = herefd;
  5443. int amount, workloc, resetloc;
  5444. int zero;
  5445. char *(*scan)(char*, char*, char*, char*, int, int);
  5446. herefd = -1;
  5447. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5448. var_str_list);
  5449. STPUTC('\0', expdest);
  5450. herefd = saveherefd;
  5451. argbackq = saveargbackq;
  5452. startp = (char *)stackblock() + startloc;
  5453. switch (subtype) {
  5454. case VSASSIGN:
  5455. setvar(str, startp, 0);
  5456. amount = startp - expdest;
  5457. STADJUST(amount, expdest);
  5458. return startp;
  5459. #if ENABLE_ASH_BASH_COMPAT
  5460. case VSSUBSTR:
  5461. loc = str = stackblock() + strloc;
  5462. // TODO: number() instead? It does error checking...
  5463. pos = atoi(loc);
  5464. len = str - startp - 1;
  5465. /* *loc != '\0', guaranteed by parser */
  5466. if (quotes) {
  5467. char *ptr;
  5468. /* We must adjust the length by the number of escapes we find. */
  5469. for (ptr = startp; ptr < (str - 1); ptr++) {
  5470. if (*ptr == CTLESC) {
  5471. len--;
  5472. ptr++;
  5473. }
  5474. }
  5475. }
  5476. orig_len = len;
  5477. if (*loc++ == ':') {
  5478. // TODO: number() instead? It does error checking...
  5479. len = atoi(loc);
  5480. } else {
  5481. len = orig_len;
  5482. while (*loc && *loc != ':')
  5483. loc++;
  5484. if (*loc++ == ':')
  5485. // TODO: number() instead? It does error checking...
  5486. len = atoi(loc);
  5487. }
  5488. if (pos >= orig_len) {
  5489. pos = 0;
  5490. len = 0;
  5491. }
  5492. if (len > (orig_len - pos))
  5493. len = orig_len - pos;
  5494. for (str = startp; pos; str++, pos--) {
  5495. if (quotes && *str == CTLESC)
  5496. str++;
  5497. }
  5498. for (loc = startp; len; len--) {
  5499. if (quotes && *str == CTLESC)
  5500. *loc++ = *str++;
  5501. *loc++ = *str++;
  5502. }
  5503. *loc = '\0';
  5504. amount = loc - expdest;
  5505. STADJUST(amount, expdest);
  5506. return loc;
  5507. #endif
  5508. case VSQUESTION:
  5509. varunset(p, str, startp, varflags);
  5510. /* NOTREACHED */
  5511. }
  5512. resetloc = expdest - (char *)stackblock();
  5513. /* We'll comeback here if we grow the stack while handling
  5514. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5515. * stack will need rebasing, and we'll need to remove our work
  5516. * areas each time
  5517. */
  5518. USE_ASH_BASH_COMPAT(restart:)
  5519. amount = expdest - ((char *)stackblock() + resetloc);
  5520. STADJUST(-amount, expdest);
  5521. startp = (char *)stackblock() + startloc;
  5522. rmesc = startp;
  5523. rmescend = (char *)stackblock() + strloc;
  5524. if (quotes) {
  5525. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5526. if (rmesc != startp) {
  5527. rmescend = expdest;
  5528. startp = (char *)stackblock() + startloc;
  5529. }
  5530. }
  5531. rmescend--;
  5532. str = (char *)stackblock() + strloc;
  5533. preglob(str, varflags & VSQUOTE, 0);
  5534. workloc = expdest - (char *)stackblock();
  5535. #if ENABLE_ASH_BASH_COMPAT
  5536. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5537. char *idx, *end, *restart_detect;
  5538. if (!repl) {
  5539. repl = parse_sub_pattern(str, varflags & VSQUOTE);
  5540. if (!repl)
  5541. repl = &null;
  5542. }
  5543. /* If there's no pattern to match, return the expansion unmolested */
  5544. if (*str == '\0')
  5545. return 0;
  5546. len = 0;
  5547. idx = startp;
  5548. end = str - 1;
  5549. while (idx < end) {
  5550. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5551. if (!loc) {
  5552. /* No match, advance */
  5553. restart_detect = stackblock();
  5554. STPUTC(*idx, expdest);
  5555. if (quotes && *idx == CTLESC) {
  5556. idx++;
  5557. len++;
  5558. STPUTC(*idx, expdest);
  5559. }
  5560. if (stackblock() != restart_detect)
  5561. goto restart;
  5562. idx++;
  5563. len++;
  5564. rmesc++;
  5565. continue;
  5566. }
  5567. if (subtype == VSREPLACEALL) {
  5568. while (idx < loc) {
  5569. if (quotes && *idx == CTLESC)
  5570. idx++;
  5571. idx++;
  5572. rmesc++;
  5573. }
  5574. } else
  5575. idx = loc;
  5576. for (loc = repl; *loc; loc++) {
  5577. restart_detect = stackblock();
  5578. STPUTC(*loc, expdest);
  5579. if (stackblock() != restart_detect)
  5580. goto restart;
  5581. len++;
  5582. }
  5583. if (subtype == VSREPLACE) {
  5584. while (*idx) {
  5585. restart_detect = stackblock();
  5586. STPUTC(*idx, expdest);
  5587. if (stackblock() != restart_detect)
  5588. goto restart;
  5589. len++;
  5590. idx++;
  5591. }
  5592. break;
  5593. }
  5594. }
  5595. /* We've put the replaced text into a buffer at workloc, now
  5596. * move it to the right place and adjust the stack.
  5597. */
  5598. startp = stackblock() + startloc;
  5599. STPUTC('\0', expdest);
  5600. memmove(startp, stackblock() + workloc, len);
  5601. startp[len++] = '\0';
  5602. amount = expdest - ((char *)stackblock() + startloc + len - 1);
  5603. STADJUST(-amount, expdest);
  5604. return startp;
  5605. }
  5606. #endif /* ENABLE_ASH_BASH_COMPAT */
  5607. subtype -= VSTRIMRIGHT;
  5608. #if DEBUG
  5609. if (subtype < 0 || subtype > 7)
  5610. abort();
  5611. #endif
  5612. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  5613. zero = subtype >> 1;
  5614. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5615. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5616. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5617. if (loc) {
  5618. if (zero) {
  5619. memmove(startp, loc, str - loc);
  5620. loc = startp + (str - loc) - 1;
  5621. }
  5622. *loc = '\0';
  5623. amount = loc - expdest;
  5624. STADJUST(amount, expdest);
  5625. }
  5626. return loc;
  5627. }
  5628. /*
  5629. * Add the value of a specialized variable to the stack string.
  5630. */
  5631. static ssize_t
  5632. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5633. {
  5634. int num;
  5635. char *p;
  5636. int i;
  5637. int sep = 0;
  5638. int sepq = 0;
  5639. ssize_t len = 0;
  5640. char **ap;
  5641. int syntax;
  5642. int quoted = varflags & VSQUOTE;
  5643. int subtype = varflags & VSTYPE;
  5644. int quotes = flags & (EXP_FULL | EXP_CASE);
  5645. if (quoted && (flags & EXP_FULL))
  5646. sep = 1 << CHAR_BIT;
  5647. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5648. switch (*name) {
  5649. case '$':
  5650. num = rootpid;
  5651. goto numvar;
  5652. case '?':
  5653. num = exitstatus;
  5654. goto numvar;
  5655. case '#':
  5656. num = shellparam.nparam;
  5657. goto numvar;
  5658. case '!':
  5659. num = backgndpid;
  5660. if (num == 0)
  5661. return -1;
  5662. numvar:
  5663. len = cvtnum(num);
  5664. break;
  5665. case '-':
  5666. p = makestrspace(NOPTS, expdest);
  5667. for (i = NOPTS - 1; i >= 0; i--) {
  5668. if (optlist[i]) {
  5669. USTPUTC(optletters(i), p);
  5670. len++;
  5671. }
  5672. }
  5673. expdest = p;
  5674. break;
  5675. case '@':
  5676. if (sep)
  5677. goto param;
  5678. /* fall through */
  5679. case '*':
  5680. sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
  5681. if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
  5682. sepq = 1;
  5683. param:
  5684. ap = shellparam.p;
  5685. if (!ap)
  5686. return -1;
  5687. while ((p = *ap++)) {
  5688. size_t partlen;
  5689. partlen = strlen(p);
  5690. len += partlen;
  5691. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5692. memtodest(p, partlen, syntax, quotes);
  5693. if (*ap && sep) {
  5694. char *q;
  5695. len++;
  5696. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5697. continue;
  5698. }
  5699. q = expdest;
  5700. if (sepq)
  5701. STPUTC(CTLESC, q);
  5702. STPUTC(sep, q);
  5703. expdest = q;
  5704. }
  5705. }
  5706. return len;
  5707. case '0':
  5708. case '1':
  5709. case '2':
  5710. case '3':
  5711. case '4':
  5712. case '5':
  5713. case '6':
  5714. case '7':
  5715. case '8':
  5716. case '9':
  5717. // TODO: number() instead? It does error checking...
  5718. num = atoi(name);
  5719. if (num < 0 || num > shellparam.nparam)
  5720. return -1;
  5721. p = num ? shellparam.p[num - 1] : arg0;
  5722. goto value;
  5723. default:
  5724. /* NB: name has form "VAR=..." */
  5725. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  5726. * which should be considered before we check variables. */
  5727. if (var_str_list) {
  5728. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  5729. p = NULL;
  5730. do {
  5731. char *str, *eq;
  5732. str = var_str_list->text;
  5733. eq = strchr(str, '=');
  5734. if (!eq) /* stop at first non-assignment */
  5735. break;
  5736. eq++;
  5737. if (name_len == (unsigned)(eq - str)
  5738. && strncmp(str, name, name_len) == 0) {
  5739. p = eq;
  5740. /* goto value; - WRONG! */
  5741. /* think "A=1 A=2 B=$A" */
  5742. }
  5743. var_str_list = var_str_list->next;
  5744. } while (var_str_list);
  5745. if (p)
  5746. goto value;
  5747. }
  5748. p = lookupvar(name);
  5749. value:
  5750. if (!p)
  5751. return -1;
  5752. len = strlen(p);
  5753. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5754. memtodest(p, len, syntax, quotes);
  5755. return len;
  5756. }
  5757. if (subtype == VSPLUS || subtype == VSLENGTH)
  5758. STADJUST(-len, expdest);
  5759. return len;
  5760. }
  5761. /*
  5762. * Expand a variable, and return a pointer to the next character in the
  5763. * input string.
  5764. */
  5765. static char *
  5766. evalvar(char *p, int flag, struct strlist *var_str_list)
  5767. {
  5768. char varflags;
  5769. char subtype;
  5770. char quoted;
  5771. char easy;
  5772. char *var;
  5773. int patloc;
  5774. int startloc;
  5775. ssize_t varlen;
  5776. varflags = *p++;
  5777. subtype = varflags & VSTYPE;
  5778. quoted = varflags & VSQUOTE;
  5779. var = p;
  5780. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5781. startloc = expdest - (char *)stackblock();
  5782. p = strchr(p, '=') + 1;
  5783. again:
  5784. varlen = varvalue(var, varflags, flag, var_str_list);
  5785. if (varflags & VSNUL)
  5786. varlen--;
  5787. if (subtype == VSPLUS) {
  5788. varlen = -1 - varlen;
  5789. goto vsplus;
  5790. }
  5791. if (subtype == VSMINUS) {
  5792. vsplus:
  5793. if (varlen < 0) {
  5794. argstr(
  5795. p, flag | EXP_TILDE |
  5796. (quoted ? EXP_QWORD : EXP_WORD),
  5797. var_str_list
  5798. );
  5799. goto end;
  5800. }
  5801. if (easy)
  5802. goto record;
  5803. goto end;
  5804. }
  5805. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  5806. if (varlen < 0) {
  5807. if (subevalvar(p, var, /* strloc: */ 0,
  5808. subtype, startloc, varflags,
  5809. /* quotes: */ 0,
  5810. var_str_list)
  5811. ) {
  5812. varflags &= ~VSNUL;
  5813. /*
  5814. * Remove any recorded regions beyond
  5815. * start of variable
  5816. */
  5817. removerecordregions(startloc);
  5818. goto again;
  5819. }
  5820. goto end;
  5821. }
  5822. if (easy)
  5823. goto record;
  5824. goto end;
  5825. }
  5826. if (varlen < 0 && uflag)
  5827. varunset(p, var, 0, 0);
  5828. if (subtype == VSLENGTH) {
  5829. cvtnum(varlen > 0 ? varlen : 0);
  5830. goto record;
  5831. }
  5832. if (subtype == VSNORMAL) {
  5833. if (easy)
  5834. goto record;
  5835. goto end;
  5836. }
  5837. #if DEBUG
  5838. switch (subtype) {
  5839. case VSTRIMLEFT:
  5840. case VSTRIMLEFTMAX:
  5841. case VSTRIMRIGHT:
  5842. case VSTRIMRIGHTMAX:
  5843. #if ENABLE_ASH_BASH_COMPAT
  5844. case VSSUBSTR:
  5845. case VSREPLACE:
  5846. case VSREPLACEALL:
  5847. #endif
  5848. break;
  5849. default:
  5850. abort();
  5851. }
  5852. #endif
  5853. if (varlen >= 0) {
  5854. /*
  5855. * Terminate the string and start recording the pattern
  5856. * right after it
  5857. */
  5858. STPUTC('\0', expdest);
  5859. patloc = expdest - (char *)stackblock();
  5860. if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
  5861. startloc, varflags,
  5862. /* quotes: */ flag & (EXP_FULL | EXP_CASE),
  5863. var_str_list)
  5864. ) {
  5865. int amount = expdest - (
  5866. (char *)stackblock() + patloc - 1
  5867. );
  5868. STADJUST(-amount, expdest);
  5869. }
  5870. /* Remove any recorded regions beyond start of variable */
  5871. removerecordregions(startloc);
  5872. record:
  5873. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  5874. }
  5875. end:
  5876. if (subtype != VSNORMAL) { /* skip to end of alternative */
  5877. int nesting = 1;
  5878. for (;;) {
  5879. char c = *p++;
  5880. if (c == CTLESC)
  5881. p++;
  5882. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  5883. if (varlen >= 0)
  5884. argbackq = argbackq->next;
  5885. } else if (c == CTLVAR) {
  5886. if ((*p++ & VSTYPE) != VSNORMAL)
  5887. nesting++;
  5888. } else if (c == CTLENDVAR) {
  5889. if (--nesting == 0)
  5890. break;
  5891. }
  5892. }
  5893. }
  5894. return p;
  5895. }
  5896. /*
  5897. * Break the argument string into pieces based upon IFS and add the
  5898. * strings to the argument list. The regions of the string to be
  5899. * searched for IFS characters have been stored by recordregion.
  5900. */
  5901. static void
  5902. ifsbreakup(char *string, struct arglist *arglist)
  5903. {
  5904. struct ifsregion *ifsp;
  5905. struct strlist *sp;
  5906. char *start;
  5907. char *p;
  5908. char *q;
  5909. const char *ifs, *realifs;
  5910. int ifsspc;
  5911. int nulonly;
  5912. start = string;
  5913. if (ifslastp != NULL) {
  5914. ifsspc = 0;
  5915. nulonly = 0;
  5916. realifs = ifsset() ? ifsval() : defifs;
  5917. ifsp = &ifsfirst;
  5918. do {
  5919. p = string + ifsp->begoff;
  5920. nulonly = ifsp->nulonly;
  5921. ifs = nulonly ? nullstr : realifs;
  5922. ifsspc = 0;
  5923. while (p < string + ifsp->endoff) {
  5924. q = p;
  5925. if (*p == CTLESC)
  5926. p++;
  5927. if (!strchr(ifs, *p)) {
  5928. p++;
  5929. continue;
  5930. }
  5931. if (!nulonly)
  5932. ifsspc = (strchr(defifs, *p) != NULL);
  5933. /* Ignore IFS whitespace at start */
  5934. if (q == start && ifsspc) {
  5935. p++;
  5936. start = p;
  5937. continue;
  5938. }
  5939. *q = '\0';
  5940. sp = stzalloc(sizeof(*sp));
  5941. sp->text = start;
  5942. *arglist->lastp = sp;
  5943. arglist->lastp = &sp->next;
  5944. p++;
  5945. if (!nulonly) {
  5946. for (;;) {
  5947. if (p >= string + ifsp->endoff) {
  5948. break;
  5949. }
  5950. q = p;
  5951. if (*p == CTLESC)
  5952. p++;
  5953. if (strchr(ifs, *p) == NULL) {
  5954. p = q;
  5955. break;
  5956. }
  5957. if (strchr(defifs, *p) == NULL) {
  5958. if (ifsspc) {
  5959. p++;
  5960. ifsspc = 0;
  5961. } else {
  5962. p = q;
  5963. break;
  5964. }
  5965. } else
  5966. p++;
  5967. }
  5968. }
  5969. start = p;
  5970. } /* while */
  5971. ifsp = ifsp->next;
  5972. } while (ifsp != NULL);
  5973. if (nulonly)
  5974. goto add;
  5975. }
  5976. if (!*start)
  5977. return;
  5978. add:
  5979. sp = stzalloc(sizeof(*sp));
  5980. sp->text = start;
  5981. *arglist->lastp = sp;
  5982. arglist->lastp = &sp->next;
  5983. }
  5984. static void
  5985. ifsfree(void)
  5986. {
  5987. struct ifsregion *p;
  5988. INT_OFF;
  5989. p = ifsfirst.next;
  5990. do {
  5991. struct ifsregion *ifsp;
  5992. ifsp = p->next;
  5993. free(p);
  5994. p = ifsp;
  5995. } while (p);
  5996. ifslastp = NULL;
  5997. ifsfirst.next = NULL;
  5998. INT_ON;
  5999. }
  6000. /*
  6001. * Add a file name to the list.
  6002. */
  6003. static void
  6004. addfname(const char *name)
  6005. {
  6006. struct strlist *sp;
  6007. sp = stzalloc(sizeof(*sp));
  6008. sp->text = ststrdup(name);
  6009. *exparg.lastp = sp;
  6010. exparg.lastp = &sp->next;
  6011. }
  6012. static char *expdir;
  6013. /*
  6014. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6015. */
  6016. static void
  6017. expmeta(char *enddir, char *name)
  6018. {
  6019. char *p;
  6020. const char *cp;
  6021. char *start;
  6022. char *endname;
  6023. int metaflag;
  6024. struct stat statb;
  6025. DIR *dirp;
  6026. struct dirent *dp;
  6027. int atend;
  6028. int matchdot;
  6029. metaflag = 0;
  6030. start = name;
  6031. for (p = name; *p; p++) {
  6032. if (*p == '*' || *p == '?')
  6033. metaflag = 1;
  6034. else if (*p == '[') {
  6035. char *q = p + 1;
  6036. if (*q == '!')
  6037. q++;
  6038. for (;;) {
  6039. if (*q == '\\')
  6040. q++;
  6041. if (*q == '/' || *q == '\0')
  6042. break;
  6043. if (*++q == ']') {
  6044. metaflag = 1;
  6045. break;
  6046. }
  6047. }
  6048. } else if (*p == '\\')
  6049. p++;
  6050. else if (*p == '/') {
  6051. if (metaflag)
  6052. goto out;
  6053. start = p + 1;
  6054. }
  6055. }
  6056. out:
  6057. if (metaflag == 0) { /* we've reached the end of the file name */
  6058. if (enddir != expdir)
  6059. metaflag++;
  6060. p = name;
  6061. do {
  6062. if (*p == '\\')
  6063. p++;
  6064. *enddir++ = *p;
  6065. } while (*p++);
  6066. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6067. addfname(expdir);
  6068. return;
  6069. }
  6070. endname = p;
  6071. if (name < start) {
  6072. p = name;
  6073. do {
  6074. if (*p == '\\')
  6075. p++;
  6076. *enddir++ = *p++;
  6077. } while (p < start);
  6078. }
  6079. if (enddir == expdir) {
  6080. cp = ".";
  6081. } else if (enddir == expdir + 1 && *expdir == '/') {
  6082. cp = "/";
  6083. } else {
  6084. cp = expdir;
  6085. enddir[-1] = '\0';
  6086. }
  6087. dirp = opendir(cp);
  6088. if (dirp == NULL)
  6089. return;
  6090. if (enddir != expdir)
  6091. enddir[-1] = '/';
  6092. if (*endname == 0) {
  6093. atend = 1;
  6094. } else {
  6095. atend = 0;
  6096. *endname++ = '\0';
  6097. }
  6098. matchdot = 0;
  6099. p = start;
  6100. if (*p == '\\')
  6101. p++;
  6102. if (*p == '.')
  6103. matchdot++;
  6104. while (!intpending && (dp = readdir(dirp)) != NULL) {
  6105. if (dp->d_name[0] == '.' && !matchdot)
  6106. continue;
  6107. if (pmatch(start, dp->d_name)) {
  6108. if (atend) {
  6109. strcpy(enddir, dp->d_name);
  6110. addfname(expdir);
  6111. } else {
  6112. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6113. continue;
  6114. p[-1] = '/';
  6115. expmeta(p, endname);
  6116. }
  6117. }
  6118. }
  6119. closedir(dirp);
  6120. if (!atend)
  6121. endname[-1] = '/';
  6122. }
  6123. static struct strlist *
  6124. msort(struct strlist *list, int len)
  6125. {
  6126. struct strlist *p, *q = NULL;
  6127. struct strlist **lpp;
  6128. int half;
  6129. int n;
  6130. if (len <= 1)
  6131. return list;
  6132. half = len >> 1;
  6133. p = list;
  6134. for (n = half; --n >= 0;) {
  6135. q = p;
  6136. p = p->next;
  6137. }
  6138. q->next = NULL; /* terminate first half of list */
  6139. q = msort(list, half); /* sort first half of list */
  6140. p = msort(p, len - half); /* sort second half */
  6141. lpp = &list;
  6142. for (;;) {
  6143. #if ENABLE_LOCALE_SUPPORT
  6144. if (strcoll(p->text, q->text) < 0)
  6145. #else
  6146. if (strcmp(p->text, q->text) < 0)
  6147. #endif
  6148. {
  6149. *lpp = p;
  6150. lpp = &p->next;
  6151. p = *lpp;
  6152. if (p == NULL) {
  6153. *lpp = q;
  6154. break;
  6155. }
  6156. } else {
  6157. *lpp = q;
  6158. lpp = &q->next;
  6159. q = *lpp;
  6160. if (q == NULL) {
  6161. *lpp = p;
  6162. break;
  6163. }
  6164. }
  6165. }
  6166. return list;
  6167. }
  6168. /*
  6169. * Sort the results of file name expansion. It calculates the number of
  6170. * strings to sort and then calls msort (short for merge sort) to do the
  6171. * work.
  6172. */
  6173. static struct strlist *
  6174. expsort(struct strlist *str)
  6175. {
  6176. int len;
  6177. struct strlist *sp;
  6178. len = 0;
  6179. for (sp = str; sp; sp = sp->next)
  6180. len++;
  6181. return msort(str, len);
  6182. }
  6183. static void
  6184. expandmeta(struct strlist *str /*, int flag*/)
  6185. {
  6186. static const char metachars[] ALIGN1 = {
  6187. '*', '?', '[', 0
  6188. };
  6189. /* TODO - EXP_REDIR */
  6190. while (str) {
  6191. struct strlist **savelastp;
  6192. struct strlist *sp;
  6193. char *p;
  6194. if (fflag)
  6195. goto nometa;
  6196. if (!strpbrk(str->text, metachars))
  6197. goto nometa;
  6198. savelastp = exparg.lastp;
  6199. INT_OFF;
  6200. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6201. {
  6202. int i = strlen(str->text);
  6203. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6204. }
  6205. expmeta(expdir, p);
  6206. free(expdir);
  6207. if (p != str->text)
  6208. free(p);
  6209. INT_ON;
  6210. if (exparg.lastp == savelastp) {
  6211. /*
  6212. * no matches
  6213. */
  6214. nometa:
  6215. *exparg.lastp = str;
  6216. rmescapes(str->text);
  6217. exparg.lastp = &str->next;
  6218. } else {
  6219. *exparg.lastp = NULL;
  6220. *savelastp = sp = expsort(*savelastp);
  6221. while (sp->next != NULL)
  6222. sp = sp->next;
  6223. exparg.lastp = &sp->next;
  6224. }
  6225. str = str->next;
  6226. }
  6227. }
  6228. /*
  6229. * Perform variable substitution and command substitution on an argument,
  6230. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6231. * perform splitting and file name expansion. When arglist is NULL, perform
  6232. * here document expansion.
  6233. */
  6234. static void
  6235. expandarg(union node *arg, struct arglist *arglist, int flag)
  6236. {
  6237. struct strlist *sp;
  6238. char *p;
  6239. argbackq = arg->narg.backquote;
  6240. STARTSTACKSTR(expdest);
  6241. ifsfirst.next = NULL;
  6242. ifslastp = NULL;
  6243. argstr(arg->narg.text, flag,
  6244. /* var_str_list: */ arglist ? arglist->list : NULL);
  6245. p = _STPUTC('\0', expdest);
  6246. expdest = p - 1;
  6247. if (arglist == NULL) {
  6248. return; /* here document expanded */
  6249. }
  6250. p = grabstackstr(p);
  6251. exparg.lastp = &exparg.list;
  6252. /*
  6253. * TODO - EXP_REDIR
  6254. */
  6255. if (flag & EXP_FULL) {
  6256. ifsbreakup(p, &exparg);
  6257. *exparg.lastp = NULL;
  6258. exparg.lastp = &exparg.list;
  6259. expandmeta(exparg.list /*, flag*/);
  6260. } else {
  6261. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6262. rmescapes(p);
  6263. sp = stzalloc(sizeof(*sp));
  6264. sp->text = p;
  6265. *exparg.lastp = sp;
  6266. exparg.lastp = &sp->next;
  6267. }
  6268. if (ifsfirst.next)
  6269. ifsfree();
  6270. *exparg.lastp = NULL;
  6271. if (exparg.list) {
  6272. *arglist->lastp = exparg.list;
  6273. arglist->lastp = exparg.lastp;
  6274. }
  6275. }
  6276. /*
  6277. * Expand shell variables and backquotes inside a here document.
  6278. */
  6279. static void
  6280. expandhere(union node *arg, int fd)
  6281. {
  6282. herefd = fd;
  6283. expandarg(arg, (struct arglist *)NULL, 0);
  6284. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6285. }
  6286. /*
  6287. * Returns true if the pattern matches the string.
  6288. */
  6289. static int
  6290. patmatch(char *pattern, const char *string)
  6291. {
  6292. return pmatch(preglob(pattern, 0, 0), string);
  6293. }
  6294. /*
  6295. * See if a pattern matches in a case statement.
  6296. */
  6297. static int
  6298. casematch(union node *pattern, char *val)
  6299. {
  6300. struct stackmark smark;
  6301. int result;
  6302. setstackmark(&smark);
  6303. argbackq = pattern->narg.backquote;
  6304. STARTSTACKSTR(expdest);
  6305. ifslastp = NULL;
  6306. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6307. /* var_str_list: */ NULL);
  6308. STACKSTRNUL(expdest);
  6309. result = patmatch(stackblock(), val);
  6310. popstackmark(&smark);
  6311. return result;
  6312. }
  6313. /* ============ find_command */
  6314. struct builtincmd {
  6315. const char *name;
  6316. int (*builtin)(int, char **);
  6317. /* unsigned flags; */
  6318. };
  6319. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6320. /* "regular" builtins always take precedence over commands,
  6321. * regardless of PATH=....%builtin... position */
  6322. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6323. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6324. struct cmdentry {
  6325. smallint cmdtype; /* CMDxxx */
  6326. union param {
  6327. int index;
  6328. /* index >= 0 for commands without path (slashes) */
  6329. /* (TODO: what exactly does the value mean? PATH position?) */
  6330. /* index == -1 for commands with slashes */
  6331. /* index == (-2 - applet_no) for NOFORK applets */
  6332. const struct builtincmd *cmd;
  6333. struct funcnode *func;
  6334. } u;
  6335. };
  6336. /* values of cmdtype */
  6337. #define CMDUNKNOWN -1 /* no entry in table for command */
  6338. #define CMDNORMAL 0 /* command is an executable program */
  6339. #define CMDFUNCTION 1 /* command is a shell function */
  6340. #define CMDBUILTIN 2 /* command is a shell builtin */
  6341. /* action to find_command() */
  6342. #define DO_ERR 0x01 /* prints errors */
  6343. #define DO_ABS 0x02 /* checks absolute paths */
  6344. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6345. #define DO_ALTPATH 0x08 /* using alternate path */
  6346. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6347. static void find_command(char *, struct cmdentry *, int, const char *);
  6348. /* ============ Hashing commands */
  6349. /*
  6350. * When commands are first encountered, they are entered in a hash table.
  6351. * This ensures that a full path search will not have to be done for them
  6352. * on each invocation.
  6353. *
  6354. * We should investigate converting to a linear search, even though that
  6355. * would make the command name "hash" a misnomer.
  6356. */
  6357. struct tblentry {
  6358. struct tblentry *next; /* next entry in hash chain */
  6359. union param param; /* definition of builtin function */
  6360. smallint cmdtype; /* CMDxxx */
  6361. char rehash; /* if set, cd done since entry created */
  6362. char cmdname[1]; /* name of command */
  6363. };
  6364. static struct tblentry **cmdtable;
  6365. #define INIT_G_cmdtable() do { \
  6366. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6367. } while (0)
  6368. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6369. static void
  6370. tryexec(USE_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6371. {
  6372. int repeated = 0;
  6373. #if ENABLE_FEATURE_SH_STANDALONE
  6374. if (applet_no >= 0) {
  6375. if (APPLET_IS_NOEXEC(applet_no)) {
  6376. while (*envp)
  6377. putenv(*envp++);
  6378. run_applet_no_and_exit(applet_no, argv);
  6379. }
  6380. /* re-exec ourselves with the new arguments */
  6381. execve(bb_busybox_exec_path, argv, envp);
  6382. /* If they called chroot or otherwise made the binary no longer
  6383. * executable, fall through */
  6384. }
  6385. #endif
  6386. repeat:
  6387. #ifdef SYSV
  6388. do {
  6389. execve(cmd, argv, envp);
  6390. } while (errno == EINTR);
  6391. #else
  6392. execve(cmd, argv, envp);
  6393. #endif
  6394. if (repeated) {
  6395. free(argv);
  6396. return;
  6397. }
  6398. if (errno == ENOEXEC) {
  6399. char **ap;
  6400. char **new;
  6401. for (ap = argv; *ap; ap++)
  6402. continue;
  6403. ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
  6404. ap[1] = cmd;
  6405. ap[0] = cmd = (char *)DEFAULT_SHELL;
  6406. ap += 2;
  6407. argv++;
  6408. while ((*ap++ = *argv++) != NULL)
  6409. continue;
  6410. argv = new;
  6411. repeated++;
  6412. goto repeat;
  6413. }
  6414. }
  6415. /*
  6416. * Exec a program. Never returns. If you change this routine, you may
  6417. * have to change the find_command routine as well.
  6418. */
  6419. static void shellexec(char **, const char *, int) NORETURN;
  6420. static void
  6421. shellexec(char **argv, const char *path, int idx)
  6422. {
  6423. char *cmdname;
  6424. int e;
  6425. char **envp;
  6426. int exerrno;
  6427. #if ENABLE_FEATURE_SH_STANDALONE
  6428. int applet_no = -1;
  6429. #endif
  6430. clearredir(/*drop:*/ 1);
  6431. envp = listvars(VEXPORT, VUNSET, 0);
  6432. if (strchr(argv[0], '/') != NULL
  6433. #if ENABLE_FEATURE_SH_STANDALONE
  6434. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6435. #endif
  6436. ) {
  6437. tryexec(USE_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6438. e = errno;
  6439. } else {
  6440. e = ENOENT;
  6441. while ((cmdname = padvance(&path, argv[0])) != NULL) {
  6442. if (--idx < 0 && pathopt == NULL) {
  6443. tryexec(USE_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6444. if (errno != ENOENT && errno != ENOTDIR)
  6445. e = errno;
  6446. }
  6447. stunalloc(cmdname);
  6448. }
  6449. }
  6450. /* Map to POSIX errors */
  6451. switch (e) {
  6452. case EACCES:
  6453. exerrno = 126;
  6454. break;
  6455. case ENOENT:
  6456. exerrno = 127;
  6457. break;
  6458. default:
  6459. exerrno = 2;
  6460. break;
  6461. }
  6462. exitstatus = exerrno;
  6463. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  6464. argv[0], e, suppressint));
  6465. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6466. /* NOTREACHED */
  6467. }
  6468. static void
  6469. printentry(struct tblentry *cmdp)
  6470. {
  6471. int idx;
  6472. const char *path;
  6473. char *name;
  6474. idx = cmdp->param.index;
  6475. path = pathval();
  6476. do {
  6477. name = padvance(&path, cmdp->cmdname);
  6478. stunalloc(name);
  6479. } while (--idx >= 0);
  6480. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6481. }
  6482. /*
  6483. * Clear out command entries. The argument specifies the first entry in
  6484. * PATH which has changed.
  6485. */
  6486. static void
  6487. clearcmdentry(int firstchange)
  6488. {
  6489. struct tblentry **tblp;
  6490. struct tblentry **pp;
  6491. struct tblentry *cmdp;
  6492. INT_OFF;
  6493. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6494. pp = tblp;
  6495. while ((cmdp = *pp) != NULL) {
  6496. if ((cmdp->cmdtype == CMDNORMAL &&
  6497. cmdp->param.index >= firstchange)
  6498. || (cmdp->cmdtype == CMDBUILTIN &&
  6499. builtinloc >= firstchange)
  6500. ) {
  6501. *pp = cmdp->next;
  6502. free(cmdp);
  6503. } else {
  6504. pp = &cmdp->next;
  6505. }
  6506. }
  6507. }
  6508. INT_ON;
  6509. }
  6510. /*
  6511. * Locate a command in the command hash table. If "add" is nonzero,
  6512. * add the command to the table if it is not already present. The
  6513. * variable "lastcmdentry" is set to point to the address of the link
  6514. * pointing to the entry, so that delete_cmd_entry can delete the
  6515. * entry.
  6516. *
  6517. * Interrupts must be off if called with add != 0.
  6518. */
  6519. static struct tblentry **lastcmdentry;
  6520. static struct tblentry *
  6521. cmdlookup(const char *name, int add)
  6522. {
  6523. unsigned int hashval;
  6524. const char *p;
  6525. struct tblentry *cmdp;
  6526. struct tblentry **pp;
  6527. p = name;
  6528. hashval = (unsigned char)*p << 4;
  6529. while (*p)
  6530. hashval += (unsigned char)*p++;
  6531. hashval &= 0x7FFF;
  6532. pp = &cmdtable[hashval % CMDTABLESIZE];
  6533. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6534. if (strcmp(cmdp->cmdname, name) == 0)
  6535. break;
  6536. pp = &cmdp->next;
  6537. }
  6538. if (add && cmdp == NULL) {
  6539. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6540. + strlen(name)
  6541. /* + 1 - already done because
  6542. * tblentry::cmdname is char[1] */);
  6543. /*cmdp->next = NULL; - ckzalloc did it */
  6544. cmdp->cmdtype = CMDUNKNOWN;
  6545. strcpy(cmdp->cmdname, name);
  6546. }
  6547. lastcmdentry = pp;
  6548. return cmdp;
  6549. }
  6550. /*
  6551. * Delete the command entry returned on the last lookup.
  6552. */
  6553. static void
  6554. delete_cmd_entry(void)
  6555. {
  6556. struct tblentry *cmdp;
  6557. INT_OFF;
  6558. cmdp = *lastcmdentry;
  6559. *lastcmdentry = cmdp->next;
  6560. if (cmdp->cmdtype == CMDFUNCTION)
  6561. freefunc(cmdp->param.func);
  6562. free(cmdp);
  6563. INT_ON;
  6564. }
  6565. /*
  6566. * Add a new command entry, replacing any existing command entry for
  6567. * the same name - except special builtins.
  6568. */
  6569. static void
  6570. addcmdentry(char *name, struct cmdentry *entry)
  6571. {
  6572. struct tblentry *cmdp;
  6573. cmdp = cmdlookup(name, 1);
  6574. if (cmdp->cmdtype == CMDFUNCTION) {
  6575. freefunc(cmdp->param.func);
  6576. }
  6577. cmdp->cmdtype = entry->cmdtype;
  6578. cmdp->param = entry->u;
  6579. cmdp->rehash = 0;
  6580. }
  6581. static int
  6582. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6583. {
  6584. struct tblentry **pp;
  6585. struct tblentry *cmdp;
  6586. int c;
  6587. struct cmdentry entry;
  6588. char *name;
  6589. if (nextopt("r") != '\0') {
  6590. clearcmdentry(0);
  6591. return 0;
  6592. }
  6593. if (*argptr == NULL) {
  6594. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6595. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6596. if (cmdp->cmdtype == CMDNORMAL)
  6597. printentry(cmdp);
  6598. }
  6599. }
  6600. return 0;
  6601. }
  6602. c = 0;
  6603. while ((name = *argptr) != NULL) {
  6604. cmdp = cmdlookup(name, 0);
  6605. if (cmdp != NULL
  6606. && (cmdp->cmdtype == CMDNORMAL
  6607. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6608. ) {
  6609. delete_cmd_entry();
  6610. }
  6611. find_command(name, &entry, DO_ERR, pathval());
  6612. if (entry.cmdtype == CMDUNKNOWN)
  6613. c = 1;
  6614. argptr++;
  6615. }
  6616. return c;
  6617. }
  6618. /*
  6619. * Called when a cd is done. Marks all commands so the next time they
  6620. * are executed they will be rehashed.
  6621. */
  6622. static void
  6623. hashcd(void)
  6624. {
  6625. struct tblentry **pp;
  6626. struct tblentry *cmdp;
  6627. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6628. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6629. if (cmdp->cmdtype == CMDNORMAL
  6630. || (cmdp->cmdtype == CMDBUILTIN
  6631. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  6632. && builtinloc > 0)
  6633. ) {
  6634. cmdp->rehash = 1;
  6635. }
  6636. }
  6637. }
  6638. }
  6639. /*
  6640. * Fix command hash table when PATH changed.
  6641. * Called before PATH is changed. The argument is the new value of PATH;
  6642. * pathval() still returns the old value at this point.
  6643. * Called with interrupts off.
  6644. */
  6645. static void
  6646. changepath(const char *new)
  6647. {
  6648. const char *old;
  6649. int firstchange;
  6650. int idx;
  6651. int idx_bltin;
  6652. old = pathval();
  6653. firstchange = 9999; /* assume no change */
  6654. idx = 0;
  6655. idx_bltin = -1;
  6656. for (;;) {
  6657. if (*old != *new) {
  6658. firstchange = idx;
  6659. if ((*old == '\0' && *new == ':')
  6660. || (*old == ':' && *new == '\0'))
  6661. firstchange++;
  6662. old = new; /* ignore subsequent differences */
  6663. }
  6664. if (*new == '\0')
  6665. break;
  6666. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6667. idx_bltin = idx;
  6668. if (*new == ':')
  6669. idx++;
  6670. new++, old++;
  6671. }
  6672. if (builtinloc < 0 && idx_bltin >= 0)
  6673. builtinloc = idx_bltin; /* zap builtins */
  6674. if (builtinloc >= 0 && idx_bltin < 0)
  6675. firstchange = 0;
  6676. clearcmdentry(firstchange);
  6677. builtinloc = idx_bltin;
  6678. }
  6679. #define TEOF 0
  6680. #define TNL 1
  6681. #define TREDIR 2
  6682. #define TWORD 3
  6683. #define TSEMI 4
  6684. #define TBACKGND 5
  6685. #define TAND 6
  6686. #define TOR 7
  6687. #define TPIPE 8
  6688. #define TLP 9
  6689. #define TRP 10
  6690. #define TENDCASE 11
  6691. #define TENDBQUOTE 12
  6692. #define TNOT 13
  6693. #define TCASE 14
  6694. #define TDO 15
  6695. #define TDONE 16
  6696. #define TELIF 17
  6697. #define TELSE 18
  6698. #define TESAC 19
  6699. #define TFI 20
  6700. #define TFOR 21
  6701. #define TIF 22
  6702. #define TIN 23
  6703. #define TTHEN 24
  6704. #define TUNTIL 25
  6705. #define TWHILE 26
  6706. #define TBEGIN 27
  6707. #define TEND 28
  6708. typedef smallint token_id_t;
  6709. /* first char is indicating which tokens mark the end of a list */
  6710. static const char *const tokname_array[] = {
  6711. "\1end of file",
  6712. "\0newline",
  6713. "\0redirection",
  6714. "\0word",
  6715. "\0;",
  6716. "\0&",
  6717. "\0&&",
  6718. "\0||",
  6719. "\0|",
  6720. "\0(",
  6721. "\1)",
  6722. "\1;;",
  6723. "\1`",
  6724. #define KWDOFFSET 13
  6725. /* the following are keywords */
  6726. "\0!",
  6727. "\0case",
  6728. "\1do",
  6729. "\1done",
  6730. "\1elif",
  6731. "\1else",
  6732. "\1esac",
  6733. "\1fi",
  6734. "\0for",
  6735. "\0if",
  6736. "\0in",
  6737. "\1then",
  6738. "\0until",
  6739. "\0while",
  6740. "\0{",
  6741. "\1}",
  6742. };
  6743. static const char *
  6744. tokname(int tok)
  6745. {
  6746. static char buf[16];
  6747. //try this:
  6748. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6749. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6750. //return buf;
  6751. if (tok >= TSEMI)
  6752. buf[0] = '"';
  6753. sprintf(buf + (tok >= TSEMI), "%s%c",
  6754. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6755. return buf;
  6756. }
  6757. /* Wrapper around strcmp for qsort/bsearch/... */
  6758. static int
  6759. pstrcmp(const void *a, const void *b)
  6760. {
  6761. return strcmp((char*) a, (*(char**) b) + 1);
  6762. }
  6763. static const char *const *
  6764. findkwd(const char *s)
  6765. {
  6766. return bsearch(s, tokname_array + KWDOFFSET,
  6767. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6768. sizeof(tokname_array[0]), pstrcmp);
  6769. }
  6770. /*
  6771. * Locate and print what a word is...
  6772. */
  6773. static int
  6774. describe_command(char *command, int describe_command_verbose)
  6775. {
  6776. struct cmdentry entry;
  6777. struct tblentry *cmdp;
  6778. #if ENABLE_ASH_ALIAS
  6779. const struct alias *ap;
  6780. #endif
  6781. const char *path = pathval();
  6782. if (describe_command_verbose) {
  6783. out1str(command);
  6784. }
  6785. /* First look at the keywords */
  6786. if (findkwd(command)) {
  6787. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6788. goto out;
  6789. }
  6790. #if ENABLE_ASH_ALIAS
  6791. /* Then look at the aliases */
  6792. ap = lookupalias(command, 0);
  6793. if (ap != NULL) {
  6794. if (!describe_command_verbose) {
  6795. out1str("alias ");
  6796. printalias(ap);
  6797. return 0;
  6798. }
  6799. out1fmt(" is an alias for %s", ap->val);
  6800. goto out;
  6801. }
  6802. #endif
  6803. /* Then check if it is a tracked alias */
  6804. cmdp = cmdlookup(command, 0);
  6805. if (cmdp != NULL) {
  6806. entry.cmdtype = cmdp->cmdtype;
  6807. entry.u = cmdp->param;
  6808. } else {
  6809. /* Finally use brute force */
  6810. find_command(command, &entry, DO_ABS, path);
  6811. }
  6812. switch (entry.cmdtype) {
  6813. case CMDNORMAL: {
  6814. int j = entry.u.index;
  6815. char *p;
  6816. if (j < 0) {
  6817. p = command;
  6818. } else {
  6819. do {
  6820. p = padvance(&path, command);
  6821. stunalloc(p);
  6822. } while (--j >= 0);
  6823. }
  6824. if (describe_command_verbose) {
  6825. out1fmt(" is%s %s",
  6826. (cmdp ? " a tracked alias for" : nullstr), p
  6827. );
  6828. } else {
  6829. out1str(p);
  6830. }
  6831. break;
  6832. }
  6833. case CMDFUNCTION:
  6834. if (describe_command_verbose) {
  6835. out1str(" is a shell function");
  6836. } else {
  6837. out1str(command);
  6838. }
  6839. break;
  6840. case CMDBUILTIN:
  6841. if (describe_command_verbose) {
  6842. out1fmt(" is a %sshell builtin",
  6843. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  6844. "special " : nullstr
  6845. );
  6846. } else {
  6847. out1str(command);
  6848. }
  6849. break;
  6850. default:
  6851. if (describe_command_verbose) {
  6852. out1str(": not found\n");
  6853. }
  6854. return 127;
  6855. }
  6856. out:
  6857. outstr("\n", stdout);
  6858. return 0;
  6859. }
  6860. static int
  6861. typecmd(int argc UNUSED_PARAM, char **argv)
  6862. {
  6863. int i = 1;
  6864. int err = 0;
  6865. int verbose = 1;
  6866. /* type -p ... ? (we don't bother checking for 'p') */
  6867. if (argv[1] && argv[1][0] == '-') {
  6868. i++;
  6869. verbose = 0;
  6870. }
  6871. while (argv[i]) {
  6872. err |= describe_command(argv[i++], verbose);
  6873. }
  6874. return err;
  6875. }
  6876. #if ENABLE_ASH_CMDCMD
  6877. static int
  6878. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6879. {
  6880. int c;
  6881. enum {
  6882. VERIFY_BRIEF = 1,
  6883. VERIFY_VERBOSE = 2,
  6884. } verify = 0;
  6885. while ((c = nextopt("pvV")) != '\0')
  6886. if (c == 'V')
  6887. verify |= VERIFY_VERBOSE;
  6888. else if (c == 'v')
  6889. verify |= VERIFY_BRIEF;
  6890. #if DEBUG
  6891. else if (c != 'p')
  6892. abort();
  6893. #endif
  6894. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  6895. if (verify && (*argptr != NULL)) {
  6896. return describe_command(*argptr, verify - VERIFY_BRIEF);
  6897. }
  6898. return 0;
  6899. }
  6900. #endif
  6901. /* ============ eval.c */
  6902. static int funcblocksize; /* size of structures in function */
  6903. static int funcstringsize; /* size of strings in node */
  6904. static void *funcblock; /* block to allocate function from */
  6905. static char *funcstring; /* block to allocate strings from */
  6906. /* flags in argument to evaltree */
  6907. #define EV_EXIT 01 /* exit after evaluating tree */
  6908. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  6909. #define EV_BACKCMD 04 /* command executing within back quotes */
  6910. static const short nodesize[N_NUMBER] = {
  6911. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  6912. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  6913. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  6914. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  6915. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  6916. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6917. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6918. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6919. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  6920. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6921. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6922. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  6923. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  6924. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  6925. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  6926. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  6927. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  6928. #if ENABLE_ASH_BASH_COMPAT
  6929. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  6930. #endif
  6931. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  6932. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  6933. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  6934. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  6935. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  6936. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  6937. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  6938. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  6939. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  6940. };
  6941. static void calcsize(union node *n);
  6942. static void
  6943. sizenodelist(struct nodelist *lp)
  6944. {
  6945. while (lp) {
  6946. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  6947. calcsize(lp->n);
  6948. lp = lp->next;
  6949. }
  6950. }
  6951. static void
  6952. calcsize(union node *n)
  6953. {
  6954. if (n == NULL)
  6955. return;
  6956. funcblocksize += nodesize[n->type];
  6957. switch (n->type) {
  6958. case NCMD:
  6959. calcsize(n->ncmd.redirect);
  6960. calcsize(n->ncmd.args);
  6961. calcsize(n->ncmd.assign);
  6962. break;
  6963. case NPIPE:
  6964. sizenodelist(n->npipe.cmdlist);
  6965. break;
  6966. case NREDIR:
  6967. case NBACKGND:
  6968. case NSUBSHELL:
  6969. calcsize(n->nredir.redirect);
  6970. calcsize(n->nredir.n);
  6971. break;
  6972. case NAND:
  6973. case NOR:
  6974. case NSEMI:
  6975. case NWHILE:
  6976. case NUNTIL:
  6977. calcsize(n->nbinary.ch2);
  6978. calcsize(n->nbinary.ch1);
  6979. break;
  6980. case NIF:
  6981. calcsize(n->nif.elsepart);
  6982. calcsize(n->nif.ifpart);
  6983. calcsize(n->nif.test);
  6984. break;
  6985. case NFOR:
  6986. funcstringsize += strlen(n->nfor.var) + 1;
  6987. calcsize(n->nfor.body);
  6988. calcsize(n->nfor.args);
  6989. break;
  6990. case NCASE:
  6991. calcsize(n->ncase.cases);
  6992. calcsize(n->ncase.expr);
  6993. break;
  6994. case NCLIST:
  6995. calcsize(n->nclist.body);
  6996. calcsize(n->nclist.pattern);
  6997. calcsize(n->nclist.next);
  6998. break;
  6999. case NDEFUN:
  7000. case NARG:
  7001. sizenodelist(n->narg.backquote);
  7002. funcstringsize += strlen(n->narg.text) + 1;
  7003. calcsize(n->narg.next);
  7004. break;
  7005. case NTO:
  7006. #if ENABLE_ASH_BASH_COMPAT
  7007. case NTO2:
  7008. #endif
  7009. case NCLOBBER:
  7010. case NFROM:
  7011. case NFROMTO:
  7012. case NAPPEND:
  7013. calcsize(n->nfile.fname);
  7014. calcsize(n->nfile.next);
  7015. break;
  7016. case NTOFD:
  7017. case NFROMFD:
  7018. calcsize(n->ndup.vname);
  7019. calcsize(n->ndup.next);
  7020. break;
  7021. case NHERE:
  7022. case NXHERE:
  7023. calcsize(n->nhere.doc);
  7024. calcsize(n->nhere.next);
  7025. break;
  7026. case NNOT:
  7027. calcsize(n->nnot.com);
  7028. break;
  7029. };
  7030. }
  7031. static char *
  7032. nodeckstrdup(char *s)
  7033. {
  7034. char *rtn = funcstring;
  7035. strcpy(funcstring, s);
  7036. funcstring += strlen(s) + 1;
  7037. return rtn;
  7038. }
  7039. static union node *copynode(union node *);
  7040. static struct nodelist *
  7041. copynodelist(struct nodelist *lp)
  7042. {
  7043. struct nodelist *start;
  7044. struct nodelist **lpp;
  7045. lpp = &start;
  7046. while (lp) {
  7047. *lpp = funcblock;
  7048. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7049. (*lpp)->n = copynode(lp->n);
  7050. lp = lp->next;
  7051. lpp = &(*lpp)->next;
  7052. }
  7053. *lpp = NULL;
  7054. return start;
  7055. }
  7056. static union node *
  7057. copynode(union node *n)
  7058. {
  7059. union node *new;
  7060. if (n == NULL)
  7061. return NULL;
  7062. new = funcblock;
  7063. funcblock = (char *) funcblock + nodesize[n->type];
  7064. switch (n->type) {
  7065. case NCMD:
  7066. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7067. new->ncmd.args = copynode(n->ncmd.args);
  7068. new->ncmd.assign = copynode(n->ncmd.assign);
  7069. break;
  7070. case NPIPE:
  7071. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7072. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7073. break;
  7074. case NREDIR:
  7075. case NBACKGND:
  7076. case NSUBSHELL:
  7077. new->nredir.redirect = copynode(n->nredir.redirect);
  7078. new->nredir.n = copynode(n->nredir.n);
  7079. break;
  7080. case NAND:
  7081. case NOR:
  7082. case NSEMI:
  7083. case NWHILE:
  7084. case NUNTIL:
  7085. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7086. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7087. break;
  7088. case NIF:
  7089. new->nif.elsepart = copynode(n->nif.elsepart);
  7090. new->nif.ifpart = copynode(n->nif.ifpart);
  7091. new->nif.test = copynode(n->nif.test);
  7092. break;
  7093. case NFOR:
  7094. new->nfor.var = nodeckstrdup(n->nfor.var);
  7095. new->nfor.body = copynode(n->nfor.body);
  7096. new->nfor.args = copynode(n->nfor.args);
  7097. break;
  7098. case NCASE:
  7099. new->ncase.cases = copynode(n->ncase.cases);
  7100. new->ncase.expr = copynode(n->ncase.expr);
  7101. break;
  7102. case NCLIST:
  7103. new->nclist.body = copynode(n->nclist.body);
  7104. new->nclist.pattern = copynode(n->nclist.pattern);
  7105. new->nclist.next = copynode(n->nclist.next);
  7106. break;
  7107. case NDEFUN:
  7108. case NARG:
  7109. new->narg.backquote = copynodelist(n->narg.backquote);
  7110. new->narg.text = nodeckstrdup(n->narg.text);
  7111. new->narg.next = copynode(n->narg.next);
  7112. break;
  7113. case NTO:
  7114. #if ENABLE_ASH_BASH_COMPAT
  7115. case NTO2:
  7116. #endif
  7117. case NCLOBBER:
  7118. case NFROM:
  7119. case NFROMTO:
  7120. case NAPPEND:
  7121. new->nfile.fname = copynode(n->nfile.fname);
  7122. new->nfile.fd = n->nfile.fd;
  7123. new->nfile.next = copynode(n->nfile.next);
  7124. break;
  7125. case NTOFD:
  7126. case NFROMFD:
  7127. new->ndup.vname = copynode(n->ndup.vname);
  7128. new->ndup.dupfd = n->ndup.dupfd;
  7129. new->ndup.fd = n->ndup.fd;
  7130. new->ndup.next = copynode(n->ndup.next);
  7131. break;
  7132. case NHERE:
  7133. case NXHERE:
  7134. new->nhere.doc = copynode(n->nhere.doc);
  7135. new->nhere.fd = n->nhere.fd;
  7136. new->nhere.next = copynode(n->nhere.next);
  7137. break;
  7138. case NNOT:
  7139. new->nnot.com = copynode(n->nnot.com);
  7140. break;
  7141. };
  7142. new->type = n->type;
  7143. return new;
  7144. }
  7145. /*
  7146. * Make a copy of a parse tree.
  7147. */
  7148. static struct funcnode *
  7149. copyfunc(union node *n)
  7150. {
  7151. struct funcnode *f;
  7152. size_t blocksize;
  7153. funcblocksize = offsetof(struct funcnode, n);
  7154. funcstringsize = 0;
  7155. calcsize(n);
  7156. blocksize = funcblocksize;
  7157. f = ckmalloc(blocksize + funcstringsize);
  7158. funcblock = (char *) f + offsetof(struct funcnode, n);
  7159. funcstring = (char *) f + blocksize;
  7160. copynode(n);
  7161. f->count = 0;
  7162. return f;
  7163. }
  7164. /*
  7165. * Define a shell function.
  7166. */
  7167. static void
  7168. defun(char *name, union node *func)
  7169. {
  7170. struct cmdentry entry;
  7171. INT_OFF;
  7172. entry.cmdtype = CMDFUNCTION;
  7173. entry.u.func = copyfunc(func);
  7174. addcmdentry(name, &entry);
  7175. INT_ON;
  7176. }
  7177. static int evalskip; /* set if we are skipping commands */
  7178. /* reasons for skipping commands (see comment on breakcmd routine) */
  7179. #define SKIPBREAK (1 << 0)
  7180. #define SKIPCONT (1 << 1)
  7181. #define SKIPFUNC (1 << 2)
  7182. #define SKIPFILE (1 << 3)
  7183. #define SKIPEVAL (1 << 4)
  7184. static int skipcount; /* number of levels to skip */
  7185. static int funcnest; /* depth of function calls */
  7186. static int loopnest; /* current loop nesting level */
  7187. /* forward decl way out to parsing code - dotrap needs it */
  7188. static int evalstring(char *s, int mask);
  7189. /*
  7190. * Called to execute a trap. Perhaps we should avoid entering new trap
  7191. * handlers while we are executing a trap handler.
  7192. */
  7193. static int
  7194. dotrap(void)
  7195. {
  7196. char *p;
  7197. char *q;
  7198. int i;
  7199. int savestatus;
  7200. int skip;
  7201. savestatus = exitstatus;
  7202. pendingsig = 0;
  7203. xbarrier();
  7204. TRACE(("dotrap entered\n"));
  7205. for (i = 1, q = gotsig; i < NSIG; i++, q++) {
  7206. if (!*q)
  7207. continue;
  7208. p = trap[i];
  7209. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7210. * don't upset it by resetting gotsig[SIGINT-1] */
  7211. if (i == SIGINT && !p)
  7212. continue;
  7213. TRACE(("sig %d is active, will run handler '%s'\n", i, p));
  7214. *q = '\0';
  7215. if (!p)
  7216. continue;
  7217. skip = evalstring(p, SKIPEVAL);
  7218. exitstatus = savestatus;
  7219. if (skip) {
  7220. TRACE(("dotrap returns %d\n", skip));
  7221. return skip;
  7222. }
  7223. }
  7224. TRACE(("dotrap returns 0\n"));
  7225. return 0;
  7226. }
  7227. /* forward declarations - evaluation is fairly recursive business... */
  7228. static void evalloop(union node *, int);
  7229. static void evalfor(union node *, int);
  7230. static void evalcase(union node *, int);
  7231. static void evalsubshell(union node *, int);
  7232. static void expredir(union node *);
  7233. static void evalpipe(union node *, int);
  7234. static void evalcommand(union node *, int);
  7235. static int evalbltin(const struct builtincmd *, int, char **);
  7236. static void prehash(union node *);
  7237. /*
  7238. * Evaluate a parse tree. The value is left in the global variable
  7239. * exitstatus.
  7240. */
  7241. static void
  7242. evaltree(union node *n, int flags)
  7243. {
  7244. struct jmploc *volatile savehandler = exception_handler;
  7245. struct jmploc jmploc;
  7246. int checkexit = 0;
  7247. void (*evalfn)(union node *, int);
  7248. int status;
  7249. int int_level;
  7250. SAVE_INT(int_level);
  7251. if (n == NULL) {
  7252. TRACE(("evaltree(NULL) called\n"));
  7253. goto out1;
  7254. }
  7255. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7256. exception_handler = &jmploc;
  7257. {
  7258. int err = setjmp(jmploc.loc);
  7259. if (err) {
  7260. /* if it was a signal, check for trap handlers */
  7261. if (exception == EXSIG) {
  7262. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n", exception, err));
  7263. goto out;
  7264. }
  7265. /* continue on the way out */
  7266. TRACE(("exception %d in evaltree, propagating err=%d\n", exception, err));
  7267. exception_handler = savehandler;
  7268. longjmp(exception_handler->loc, err);
  7269. }
  7270. }
  7271. switch (n->type) {
  7272. default:
  7273. #if DEBUG
  7274. out1fmt("Node type = %d\n", n->type);
  7275. fflush(stdout);
  7276. break;
  7277. #endif
  7278. case NNOT:
  7279. evaltree(n->nnot.com, EV_TESTED);
  7280. status = !exitstatus;
  7281. goto setstatus;
  7282. case NREDIR:
  7283. expredir(n->nredir.redirect);
  7284. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7285. if (!status) {
  7286. evaltree(n->nredir.n, flags & EV_TESTED);
  7287. status = exitstatus;
  7288. }
  7289. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7290. goto setstatus;
  7291. case NCMD:
  7292. evalfn = evalcommand;
  7293. checkexit:
  7294. if (eflag && !(flags & EV_TESTED))
  7295. checkexit = ~0;
  7296. goto calleval;
  7297. case NFOR:
  7298. evalfn = evalfor;
  7299. goto calleval;
  7300. case NWHILE:
  7301. case NUNTIL:
  7302. evalfn = evalloop;
  7303. goto calleval;
  7304. case NSUBSHELL:
  7305. case NBACKGND:
  7306. evalfn = evalsubshell;
  7307. goto calleval;
  7308. case NPIPE:
  7309. evalfn = evalpipe;
  7310. goto checkexit;
  7311. case NCASE:
  7312. evalfn = evalcase;
  7313. goto calleval;
  7314. case NAND:
  7315. case NOR:
  7316. case NSEMI: {
  7317. #if NAND + 1 != NOR
  7318. #error NAND + 1 != NOR
  7319. #endif
  7320. #if NOR + 1 != NSEMI
  7321. #error NOR + 1 != NSEMI
  7322. #endif
  7323. unsigned is_or = n->type - NAND;
  7324. evaltree(
  7325. n->nbinary.ch1,
  7326. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7327. );
  7328. if (!exitstatus == is_or)
  7329. break;
  7330. if (!evalskip) {
  7331. n = n->nbinary.ch2;
  7332. evaln:
  7333. evalfn = evaltree;
  7334. calleval:
  7335. evalfn(n, flags);
  7336. break;
  7337. }
  7338. break;
  7339. }
  7340. case NIF:
  7341. evaltree(n->nif.test, EV_TESTED);
  7342. if (evalskip)
  7343. break;
  7344. if (exitstatus == 0) {
  7345. n = n->nif.ifpart;
  7346. goto evaln;
  7347. }
  7348. if (n->nif.elsepart) {
  7349. n = n->nif.elsepart;
  7350. goto evaln;
  7351. }
  7352. goto success;
  7353. case NDEFUN:
  7354. defun(n->narg.text, n->narg.next);
  7355. success:
  7356. status = 0;
  7357. setstatus:
  7358. exitstatus = status;
  7359. break;
  7360. }
  7361. out:
  7362. exception_handler = savehandler;
  7363. out1:
  7364. if (checkexit & exitstatus)
  7365. evalskip |= SKIPEVAL;
  7366. else if (pendingsig && dotrap())
  7367. goto exexit;
  7368. if (flags & EV_EXIT) {
  7369. exexit:
  7370. raise_exception(EXEXIT);
  7371. }
  7372. RESTORE_INT(int_level);
  7373. TRACE(("leaving evaltree (no interrupts)\n"));
  7374. }
  7375. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7376. static
  7377. #endif
  7378. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7379. static void
  7380. evalloop(union node *n, int flags)
  7381. {
  7382. int status;
  7383. loopnest++;
  7384. status = 0;
  7385. flags &= EV_TESTED;
  7386. for (;;) {
  7387. int i;
  7388. evaltree(n->nbinary.ch1, EV_TESTED);
  7389. if (evalskip) {
  7390. skipping:
  7391. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7392. evalskip = 0;
  7393. continue;
  7394. }
  7395. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7396. evalskip = 0;
  7397. break;
  7398. }
  7399. i = exitstatus;
  7400. if (n->type != NWHILE)
  7401. i = !i;
  7402. if (i != 0)
  7403. break;
  7404. evaltree(n->nbinary.ch2, flags);
  7405. status = exitstatus;
  7406. if (evalskip)
  7407. goto skipping;
  7408. }
  7409. loopnest--;
  7410. exitstatus = status;
  7411. }
  7412. static void
  7413. evalfor(union node *n, int flags)
  7414. {
  7415. struct arglist arglist;
  7416. union node *argp;
  7417. struct strlist *sp;
  7418. struct stackmark smark;
  7419. setstackmark(&smark);
  7420. arglist.list = NULL;
  7421. arglist.lastp = &arglist.list;
  7422. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7423. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7424. /* XXX */
  7425. if (evalskip)
  7426. goto out;
  7427. }
  7428. *arglist.lastp = NULL;
  7429. exitstatus = 0;
  7430. loopnest++;
  7431. flags &= EV_TESTED;
  7432. for (sp = arglist.list; sp; sp = sp->next) {
  7433. setvar(n->nfor.var, sp->text, 0);
  7434. evaltree(n->nfor.body, flags);
  7435. if (evalskip) {
  7436. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7437. evalskip = 0;
  7438. continue;
  7439. }
  7440. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7441. evalskip = 0;
  7442. break;
  7443. }
  7444. }
  7445. loopnest--;
  7446. out:
  7447. popstackmark(&smark);
  7448. }
  7449. static void
  7450. evalcase(union node *n, int flags)
  7451. {
  7452. union node *cp;
  7453. union node *patp;
  7454. struct arglist arglist;
  7455. struct stackmark smark;
  7456. setstackmark(&smark);
  7457. arglist.list = NULL;
  7458. arglist.lastp = &arglist.list;
  7459. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7460. exitstatus = 0;
  7461. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7462. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7463. if (casematch(patp, arglist.list->text)) {
  7464. if (evalskip == 0) {
  7465. evaltree(cp->nclist.body, flags);
  7466. }
  7467. goto out;
  7468. }
  7469. }
  7470. }
  7471. out:
  7472. popstackmark(&smark);
  7473. }
  7474. /*
  7475. * Kick off a subshell to evaluate a tree.
  7476. */
  7477. static void
  7478. evalsubshell(union node *n, int flags)
  7479. {
  7480. struct job *jp;
  7481. int backgnd = (n->type == NBACKGND);
  7482. int status;
  7483. expredir(n->nredir.redirect);
  7484. if (!backgnd && flags & EV_EXIT && !trap[0])
  7485. goto nofork;
  7486. INT_OFF;
  7487. jp = makejob(/*n,*/ 1);
  7488. if (forkshell(jp, n, backgnd) == 0) {
  7489. INT_ON;
  7490. flags |= EV_EXIT;
  7491. if (backgnd)
  7492. flags &=~ EV_TESTED;
  7493. nofork:
  7494. redirect(n->nredir.redirect, 0);
  7495. evaltreenr(n->nredir.n, flags);
  7496. /* never returns */
  7497. }
  7498. status = 0;
  7499. if (!backgnd)
  7500. status = waitforjob(jp);
  7501. exitstatus = status;
  7502. INT_ON;
  7503. }
  7504. /*
  7505. * Compute the names of the files in a redirection list.
  7506. */
  7507. static void fixredir(union node *, const char *, int);
  7508. static void
  7509. expredir(union node *n)
  7510. {
  7511. union node *redir;
  7512. for (redir = n; redir; redir = redir->nfile.next) {
  7513. struct arglist fn;
  7514. fn.list = NULL;
  7515. fn.lastp = &fn.list;
  7516. switch (redir->type) {
  7517. case NFROMTO:
  7518. case NFROM:
  7519. case NTO:
  7520. #if ENABLE_ASH_BASH_COMPAT
  7521. case NTO2:
  7522. #endif
  7523. case NCLOBBER:
  7524. case NAPPEND:
  7525. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7526. #if ENABLE_ASH_BASH_COMPAT
  7527. store_expfname:
  7528. #endif
  7529. redir->nfile.expfname = fn.list->text;
  7530. break;
  7531. case NFROMFD:
  7532. case NTOFD: /* >& */
  7533. if (redir->ndup.vname) {
  7534. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7535. if (fn.list == NULL)
  7536. ash_msg_and_raise_error("redir error");
  7537. #if ENABLE_ASH_BASH_COMPAT
  7538. //FIXME: we used expandarg with different args!
  7539. if (!isdigit_str9(fn.list->text)) {
  7540. /* >&file, not >&fd */
  7541. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7542. ash_msg_and_raise_error("redir error");
  7543. redir->type = NTO2;
  7544. goto store_expfname;
  7545. }
  7546. #endif
  7547. fixredir(redir, fn.list->text, 1);
  7548. }
  7549. break;
  7550. }
  7551. }
  7552. }
  7553. /*
  7554. * Evaluate a pipeline. All the processes in the pipeline are children
  7555. * of the process creating the pipeline. (This differs from some versions
  7556. * of the shell, which make the last process in a pipeline the parent
  7557. * of all the rest.)
  7558. */
  7559. static void
  7560. evalpipe(union node *n, int flags)
  7561. {
  7562. struct job *jp;
  7563. struct nodelist *lp;
  7564. int pipelen;
  7565. int prevfd;
  7566. int pip[2];
  7567. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7568. pipelen = 0;
  7569. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7570. pipelen++;
  7571. flags |= EV_EXIT;
  7572. INT_OFF;
  7573. jp = makejob(/*n,*/ pipelen);
  7574. prevfd = -1;
  7575. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7576. prehash(lp->n);
  7577. pip[1] = -1;
  7578. if (lp->next) {
  7579. if (pipe(pip) < 0) {
  7580. close(prevfd);
  7581. ash_msg_and_raise_error("pipe call failed");
  7582. }
  7583. }
  7584. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7585. INT_ON;
  7586. if (pip[1] >= 0) {
  7587. close(pip[0]);
  7588. }
  7589. if (prevfd > 0) {
  7590. dup2(prevfd, 0);
  7591. close(prevfd);
  7592. }
  7593. if (pip[1] > 1) {
  7594. dup2(pip[1], 1);
  7595. close(pip[1]);
  7596. }
  7597. evaltreenr(lp->n, flags);
  7598. /* never returns */
  7599. }
  7600. if (prevfd >= 0)
  7601. close(prevfd);
  7602. prevfd = pip[0];
  7603. /* Don't want to trigger debugging */
  7604. if (pip[1] != -1)
  7605. close(pip[1]);
  7606. }
  7607. if (n->npipe.pipe_backgnd == 0) {
  7608. exitstatus = waitforjob(jp);
  7609. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7610. }
  7611. INT_ON;
  7612. }
  7613. /*
  7614. * Controls whether the shell is interactive or not.
  7615. */
  7616. static void
  7617. setinteractive(int on)
  7618. {
  7619. static smallint is_interactive;
  7620. if (++on == is_interactive)
  7621. return;
  7622. is_interactive = on;
  7623. setsignal(SIGINT);
  7624. setsignal(SIGQUIT);
  7625. setsignal(SIGTERM);
  7626. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7627. if (is_interactive > 1) {
  7628. /* Looks like they want an interactive shell */
  7629. static smallint did_banner;
  7630. if (!did_banner) {
  7631. out1fmt(
  7632. "\n\n"
  7633. "%s built-in shell (ash)\n"
  7634. "Enter 'help' for a list of built-in commands."
  7635. "\n\n",
  7636. bb_banner);
  7637. did_banner = 1;
  7638. }
  7639. }
  7640. #endif
  7641. }
  7642. static void
  7643. optschanged(void)
  7644. {
  7645. #if DEBUG
  7646. opentrace();
  7647. #endif
  7648. setinteractive(iflag);
  7649. setjobctl(mflag);
  7650. #if ENABLE_FEATURE_EDITING_VI
  7651. if (viflag)
  7652. line_input_state->flags |= VI_MODE;
  7653. else
  7654. line_input_state->flags &= ~VI_MODE;
  7655. #else
  7656. viflag = 0; /* forcibly keep the option off */
  7657. #endif
  7658. }
  7659. static struct localvar *localvars;
  7660. /*
  7661. * Called after a function returns.
  7662. * Interrupts must be off.
  7663. */
  7664. static void
  7665. poplocalvars(void)
  7666. {
  7667. struct localvar *lvp;
  7668. struct var *vp;
  7669. while ((lvp = localvars) != NULL) {
  7670. localvars = lvp->next;
  7671. vp = lvp->vp;
  7672. TRACE(("poplocalvar %s", vp ? vp->text : "-"));
  7673. if (vp == NULL) { /* $- saved */
  7674. memcpy(optlist, lvp->text, sizeof(optlist));
  7675. free((char*)lvp->text);
  7676. optschanged();
  7677. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7678. unsetvar(vp->text);
  7679. } else {
  7680. if (vp->func)
  7681. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7682. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7683. free((char*)vp->text);
  7684. vp->flags = lvp->flags;
  7685. vp->text = lvp->text;
  7686. }
  7687. free(lvp);
  7688. }
  7689. }
  7690. static int
  7691. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7692. {
  7693. volatile struct shparam saveparam;
  7694. struct localvar *volatile savelocalvars;
  7695. struct jmploc *volatile savehandler;
  7696. struct jmploc jmploc;
  7697. int e;
  7698. saveparam = shellparam;
  7699. savelocalvars = localvars;
  7700. e = setjmp(jmploc.loc);
  7701. if (e) {
  7702. goto funcdone;
  7703. }
  7704. INT_OFF;
  7705. savehandler = exception_handler;
  7706. exception_handler = &jmploc;
  7707. localvars = NULL;
  7708. shellparam.malloced = 0;
  7709. func->count++;
  7710. funcnest++;
  7711. INT_ON;
  7712. shellparam.nparam = argc - 1;
  7713. shellparam.p = argv + 1;
  7714. #if ENABLE_ASH_GETOPTS
  7715. shellparam.optind = 1;
  7716. shellparam.optoff = -1;
  7717. #endif
  7718. evaltree(&func->n, flags & EV_TESTED);
  7719. funcdone:
  7720. INT_OFF;
  7721. funcnest--;
  7722. freefunc(func);
  7723. poplocalvars();
  7724. localvars = savelocalvars;
  7725. freeparam(&shellparam);
  7726. shellparam = saveparam;
  7727. exception_handler = savehandler;
  7728. INT_ON;
  7729. evalskip &= ~SKIPFUNC;
  7730. return e;
  7731. }
  7732. #if ENABLE_ASH_CMDCMD
  7733. static char **
  7734. parse_command_args(char **argv, const char **path)
  7735. {
  7736. char *cp, c;
  7737. for (;;) {
  7738. cp = *++argv;
  7739. if (!cp)
  7740. return 0;
  7741. if (*cp++ != '-')
  7742. break;
  7743. c = *cp++;
  7744. if (!c)
  7745. break;
  7746. if (c == '-' && !*cp) {
  7747. argv++;
  7748. break;
  7749. }
  7750. do {
  7751. switch (c) {
  7752. case 'p':
  7753. *path = bb_default_path;
  7754. break;
  7755. default:
  7756. /* run 'typecmd' for other options */
  7757. return 0;
  7758. }
  7759. c = *cp++;
  7760. } while (c);
  7761. }
  7762. return argv;
  7763. }
  7764. #endif
  7765. /*
  7766. * Make a variable a local variable. When a variable is made local, it's
  7767. * value and flags are saved in a localvar structure. The saved values
  7768. * will be restored when the shell function returns. We handle the name
  7769. * "-" as a special case.
  7770. */
  7771. static void
  7772. mklocal(char *name)
  7773. {
  7774. struct localvar *lvp;
  7775. struct var **vpp;
  7776. struct var *vp;
  7777. INT_OFF;
  7778. lvp = ckzalloc(sizeof(struct localvar));
  7779. if (LONE_DASH(name)) {
  7780. char *p;
  7781. p = ckmalloc(sizeof(optlist));
  7782. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7783. vp = NULL;
  7784. } else {
  7785. char *eq;
  7786. vpp = hashvar(name);
  7787. vp = *findvar(vpp, name);
  7788. eq = strchr(name, '=');
  7789. if (vp == NULL) {
  7790. if (eq)
  7791. setvareq(name, VSTRFIXED);
  7792. else
  7793. setvar(name, NULL, VSTRFIXED);
  7794. vp = *vpp; /* the new variable */
  7795. lvp->flags = VUNSET;
  7796. } else {
  7797. lvp->text = vp->text;
  7798. lvp->flags = vp->flags;
  7799. vp->flags |= VSTRFIXED|VTEXTFIXED;
  7800. if (eq)
  7801. setvareq(name, 0);
  7802. }
  7803. }
  7804. lvp->vp = vp;
  7805. lvp->next = localvars;
  7806. localvars = lvp;
  7807. INT_ON;
  7808. }
  7809. /*
  7810. * The "local" command.
  7811. */
  7812. static int
  7813. localcmd(int argc UNUSED_PARAM, char **argv)
  7814. {
  7815. char *name;
  7816. argv = argptr;
  7817. while ((name = *argv++) != NULL) {
  7818. mklocal(name);
  7819. }
  7820. return 0;
  7821. }
  7822. static int
  7823. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7824. {
  7825. return 1;
  7826. }
  7827. static int
  7828. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7829. {
  7830. return 0;
  7831. }
  7832. static int
  7833. execcmd(int argc UNUSED_PARAM, char **argv)
  7834. {
  7835. if (argv[1]) {
  7836. iflag = 0; /* exit on error */
  7837. mflag = 0;
  7838. optschanged();
  7839. shellexec(argv + 1, pathval(), 0);
  7840. }
  7841. return 0;
  7842. }
  7843. /*
  7844. * The return command.
  7845. */
  7846. static int
  7847. returncmd(int argc UNUSED_PARAM, char **argv)
  7848. {
  7849. /*
  7850. * If called outside a function, do what ksh does;
  7851. * skip the rest of the file.
  7852. */
  7853. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  7854. return argv[1] ? number(argv[1]) : exitstatus;
  7855. }
  7856. /* Forward declarations for builtintab[] */
  7857. static int breakcmd(int, char **);
  7858. static int dotcmd(int, char **);
  7859. static int evalcmd(int, char **);
  7860. static int exitcmd(int, char **);
  7861. static int exportcmd(int, char **);
  7862. #if ENABLE_ASH_GETOPTS
  7863. static int getoptscmd(int, char **);
  7864. #endif
  7865. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7866. static int helpcmd(int, char **);
  7867. #endif
  7868. #if ENABLE_ASH_MATH_SUPPORT
  7869. static int letcmd(int, char **);
  7870. #endif
  7871. static int readcmd(int, char **);
  7872. static int setcmd(int, char **);
  7873. static int shiftcmd(int, char **);
  7874. static int timescmd(int, char **);
  7875. static int trapcmd(int, char **);
  7876. static int umaskcmd(int, char **);
  7877. static int unsetcmd(int, char **);
  7878. static int ulimitcmd(int, char **);
  7879. #define BUILTIN_NOSPEC "0"
  7880. #define BUILTIN_SPECIAL "1"
  7881. #define BUILTIN_REGULAR "2"
  7882. #define BUILTIN_SPEC_REG "3"
  7883. #define BUILTIN_ASSIGN "4"
  7884. #define BUILTIN_SPEC_ASSG "5"
  7885. #define BUILTIN_REG_ASSG "6"
  7886. #define BUILTIN_SPEC_REG_ASSG "7"
  7887. /* We do not handle [[ expr ]] bashism bash-compatibly,
  7888. * we make it a synonym of [ expr ].
  7889. * Basically, word splitting and pathname expansion should NOT be performed
  7890. * Examples:
  7891. * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
  7892. * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
  7893. * Additional operators:
  7894. * || and && should work as -o and -a
  7895. * =~ regexp match
  7896. * Apart from the above, [[ expr ]] should work as [ expr ]
  7897. */
  7898. #define echocmd echo_main
  7899. #define printfcmd printf_main
  7900. #define testcmd test_main
  7901. /* Keep these in proper order since it is searched via bsearch() */
  7902. static const struct builtincmd builtintab[] = {
  7903. { BUILTIN_SPEC_REG ".", dotcmd },
  7904. { BUILTIN_SPEC_REG ":", truecmd },
  7905. #if ENABLE_ASH_BUILTIN_TEST
  7906. { BUILTIN_REGULAR "[", testcmd },
  7907. #if ENABLE_ASH_BASH_COMPAT
  7908. { BUILTIN_REGULAR "[[", testcmd },
  7909. #endif
  7910. #endif
  7911. #if ENABLE_ASH_ALIAS
  7912. { BUILTIN_REG_ASSG "alias", aliascmd },
  7913. #endif
  7914. #if JOBS
  7915. { BUILTIN_REGULAR "bg", fg_bgcmd },
  7916. #endif
  7917. { BUILTIN_SPEC_REG "break", breakcmd },
  7918. { BUILTIN_REGULAR "cd", cdcmd },
  7919. { BUILTIN_NOSPEC "chdir", cdcmd },
  7920. #if ENABLE_ASH_CMDCMD
  7921. { BUILTIN_REGULAR "command", commandcmd },
  7922. #endif
  7923. { BUILTIN_SPEC_REG "continue", breakcmd },
  7924. #if ENABLE_ASH_BUILTIN_ECHO
  7925. { BUILTIN_REGULAR "echo", echocmd },
  7926. #endif
  7927. { BUILTIN_SPEC_REG "eval", evalcmd },
  7928. { BUILTIN_SPEC_REG "exec", execcmd },
  7929. { BUILTIN_SPEC_REG "exit", exitcmd },
  7930. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  7931. { BUILTIN_REGULAR "false", falsecmd },
  7932. #if JOBS
  7933. { BUILTIN_REGULAR "fg", fg_bgcmd },
  7934. #endif
  7935. #if ENABLE_ASH_GETOPTS
  7936. { BUILTIN_REGULAR "getopts", getoptscmd },
  7937. #endif
  7938. { BUILTIN_NOSPEC "hash", hashcmd },
  7939. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7940. { BUILTIN_NOSPEC "help", helpcmd },
  7941. #endif
  7942. #if JOBS
  7943. { BUILTIN_REGULAR "jobs", jobscmd },
  7944. { BUILTIN_REGULAR "kill", killcmd },
  7945. #endif
  7946. #if ENABLE_ASH_MATH_SUPPORT
  7947. { BUILTIN_NOSPEC "let", letcmd },
  7948. #endif
  7949. { BUILTIN_ASSIGN "local", localcmd },
  7950. #if ENABLE_ASH_BUILTIN_PRINTF
  7951. { BUILTIN_REGULAR "printf", printfcmd },
  7952. #endif
  7953. { BUILTIN_NOSPEC "pwd", pwdcmd },
  7954. { BUILTIN_REGULAR "read", readcmd },
  7955. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  7956. { BUILTIN_SPEC_REG "return", returncmd },
  7957. { BUILTIN_SPEC_REG "set", setcmd },
  7958. { BUILTIN_SPEC_REG "shift", shiftcmd },
  7959. { BUILTIN_SPEC_REG "source", dotcmd },
  7960. #if ENABLE_ASH_BUILTIN_TEST
  7961. { BUILTIN_REGULAR "test", testcmd },
  7962. #endif
  7963. { BUILTIN_SPEC_REG "times", timescmd },
  7964. { BUILTIN_SPEC_REG "trap", trapcmd },
  7965. { BUILTIN_REGULAR "true", truecmd },
  7966. { BUILTIN_NOSPEC "type", typecmd },
  7967. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  7968. { BUILTIN_REGULAR "umask", umaskcmd },
  7969. #if ENABLE_ASH_ALIAS
  7970. { BUILTIN_REGULAR "unalias", unaliascmd },
  7971. #endif
  7972. { BUILTIN_SPEC_REG "unset", unsetcmd },
  7973. { BUILTIN_REGULAR "wait", waitcmd },
  7974. };
  7975. /* Should match the above table! */
  7976. #define COMMANDCMD (builtintab + \
  7977. 2 + \
  7978. 1 * ENABLE_ASH_BUILTIN_TEST + \
  7979. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  7980. 1 * ENABLE_ASH_ALIAS + \
  7981. 1 * ENABLE_ASH_JOB_CONTROL + \
  7982. 3)
  7983. #define EXECCMD (builtintab + \
  7984. 2 + \
  7985. 1 * ENABLE_ASH_BUILTIN_TEST + \
  7986. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  7987. 1 * ENABLE_ASH_ALIAS + \
  7988. 1 * ENABLE_ASH_JOB_CONTROL + \
  7989. 3 + \
  7990. 1 * ENABLE_ASH_CMDCMD + \
  7991. 1 + \
  7992. ENABLE_ASH_BUILTIN_ECHO + \
  7993. 1)
  7994. /*
  7995. * Search the table of builtin commands.
  7996. */
  7997. static struct builtincmd *
  7998. find_builtin(const char *name)
  7999. {
  8000. struct builtincmd *bp;
  8001. bp = bsearch(
  8002. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8003. pstrcmp
  8004. );
  8005. return bp;
  8006. }
  8007. /*
  8008. * Execute a simple command.
  8009. */
  8010. static int
  8011. isassignment(const char *p)
  8012. {
  8013. const char *q = endofname(p);
  8014. if (p == q)
  8015. return 0;
  8016. return *q == '=';
  8017. }
  8018. static int
  8019. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8020. {
  8021. /* Preserve exitstatus of a previous possible redirection
  8022. * as POSIX mandates */
  8023. return back_exitstatus;
  8024. }
  8025. static void
  8026. evalcommand(union node *cmd, int flags)
  8027. {
  8028. static const struct builtincmd null_bltin = {
  8029. "\0\0", bltincmd /* why three NULs? */
  8030. };
  8031. struct stackmark smark;
  8032. union node *argp;
  8033. struct arglist arglist;
  8034. struct arglist varlist;
  8035. char **argv;
  8036. int argc;
  8037. const struct strlist *sp;
  8038. struct cmdentry cmdentry;
  8039. struct job *jp;
  8040. char *lastarg;
  8041. const char *path;
  8042. int spclbltin;
  8043. int status;
  8044. char **nargv;
  8045. struct builtincmd *bcmd;
  8046. smallint cmd_is_exec;
  8047. smallint pseudovarflag = 0;
  8048. /* First expand the arguments. */
  8049. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8050. setstackmark(&smark);
  8051. back_exitstatus = 0;
  8052. cmdentry.cmdtype = CMDBUILTIN;
  8053. cmdentry.u.cmd = &null_bltin;
  8054. varlist.lastp = &varlist.list;
  8055. *varlist.lastp = NULL;
  8056. arglist.lastp = &arglist.list;
  8057. *arglist.lastp = NULL;
  8058. argc = 0;
  8059. if (cmd->ncmd.args) {
  8060. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8061. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8062. }
  8063. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8064. struct strlist **spp;
  8065. spp = arglist.lastp;
  8066. if (pseudovarflag && isassignment(argp->narg.text))
  8067. expandarg(argp, &arglist, EXP_VARTILDE);
  8068. else
  8069. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8070. for (sp = *spp; sp; sp = sp->next)
  8071. argc++;
  8072. }
  8073. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8074. for (sp = arglist.list; sp; sp = sp->next) {
  8075. TRACE(("evalcommand arg: %s\n", sp->text));
  8076. *nargv++ = sp->text;
  8077. }
  8078. *nargv = NULL;
  8079. lastarg = NULL;
  8080. if (iflag && funcnest == 0 && argc > 0)
  8081. lastarg = nargv[-1];
  8082. preverrout_fd = 2;
  8083. expredir(cmd->ncmd.redirect);
  8084. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8085. path = vpath.text;
  8086. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8087. struct strlist **spp;
  8088. char *p;
  8089. spp = varlist.lastp;
  8090. expandarg(argp, &varlist, EXP_VARTILDE);
  8091. /*
  8092. * Modify the command lookup path, if a PATH= assignment
  8093. * is present
  8094. */
  8095. p = (*spp)->text;
  8096. if (varequal(p, path))
  8097. path = p;
  8098. }
  8099. /* Print the command if xflag is set. */
  8100. if (xflag) {
  8101. int n;
  8102. const char *p = " %s";
  8103. p++;
  8104. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8105. sp = varlist.list;
  8106. for (n = 0; n < 2; n++) {
  8107. while (sp) {
  8108. fdprintf(preverrout_fd, p, sp->text);
  8109. sp = sp->next;
  8110. if (*p == '%') {
  8111. p--;
  8112. }
  8113. }
  8114. sp = arglist.list;
  8115. }
  8116. safe_write(preverrout_fd, "\n", 1);
  8117. }
  8118. cmd_is_exec = 0;
  8119. spclbltin = -1;
  8120. /* Now locate the command. */
  8121. if (argc) {
  8122. const char *oldpath;
  8123. int cmd_flag = DO_ERR;
  8124. path += 5;
  8125. oldpath = path;
  8126. for (;;) {
  8127. find_command(argv[0], &cmdentry, cmd_flag, path);
  8128. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8129. flush_stderr();
  8130. status = 127;
  8131. goto bail;
  8132. }
  8133. /* implement bltin and command here */
  8134. if (cmdentry.cmdtype != CMDBUILTIN)
  8135. break;
  8136. if (spclbltin < 0)
  8137. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8138. if (cmdentry.u.cmd == EXECCMD)
  8139. cmd_is_exec = 1;
  8140. #if ENABLE_ASH_CMDCMD
  8141. if (cmdentry.u.cmd == COMMANDCMD) {
  8142. path = oldpath;
  8143. nargv = parse_command_args(argv, &path);
  8144. if (!nargv)
  8145. break;
  8146. argc -= nargv - argv;
  8147. argv = nargv;
  8148. cmd_flag |= DO_NOFUNC;
  8149. } else
  8150. #endif
  8151. break;
  8152. }
  8153. }
  8154. if (status) {
  8155. /* We have a redirection error. */
  8156. if (spclbltin > 0)
  8157. raise_exception(EXERROR);
  8158. bail:
  8159. exitstatus = status;
  8160. goto out;
  8161. }
  8162. /* Execute the command. */
  8163. switch (cmdentry.cmdtype) {
  8164. default:
  8165. #if ENABLE_FEATURE_SH_NOFORK
  8166. /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
  8167. * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
  8168. {
  8169. /* find_command() encodes applet_no as (-2 - applet_no) */
  8170. int applet_no = (- cmdentry.u.index - 2);
  8171. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8172. listsetvar(varlist.list, VEXPORT|VSTACK);
  8173. /* run <applet>_main() */
  8174. exitstatus = run_nofork_applet(applet_no, argv);
  8175. break;
  8176. }
  8177. }
  8178. #endif
  8179. /* Fork off a child process if necessary. */
  8180. if (!(flags & EV_EXIT) || trap[0]) {
  8181. INT_OFF;
  8182. jp = makejob(/*cmd,*/ 1);
  8183. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8184. exitstatus = waitforjob(jp);
  8185. INT_ON;
  8186. TRACE(("forked child exited with %d\n", exitstatus));
  8187. break;
  8188. }
  8189. FORCE_INT_ON;
  8190. }
  8191. listsetvar(varlist.list, VEXPORT|VSTACK);
  8192. shellexec(argv, path, cmdentry.u.index);
  8193. /* NOTREACHED */
  8194. case CMDBUILTIN:
  8195. cmdenviron = varlist.list;
  8196. if (cmdenviron) {
  8197. struct strlist *list = cmdenviron;
  8198. int i = VNOSET;
  8199. if (spclbltin > 0 || argc == 0) {
  8200. i = 0;
  8201. if (cmd_is_exec && argc > 1)
  8202. i = VEXPORT;
  8203. }
  8204. listsetvar(list, i);
  8205. }
  8206. /* Tight loop with builtins only:
  8207. * "while kill -0 $child; do true; done"
  8208. * will never exit even if $child died, unless we do this
  8209. * to reap the zombie and make kill detect that it's gone: */
  8210. dowait(DOWAIT_NONBLOCK, NULL);
  8211. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8212. int exit_status;
  8213. int i = exception;
  8214. if (i == EXEXIT)
  8215. goto raise;
  8216. exit_status = 2;
  8217. if (i == EXINT)
  8218. exit_status = 128 + SIGINT;
  8219. if (i == EXSIG)
  8220. exit_status = 128 + pendingsig;
  8221. exitstatus = exit_status;
  8222. if (i == EXINT || spclbltin > 0) {
  8223. raise:
  8224. longjmp(exception_handler->loc, 1);
  8225. }
  8226. FORCE_INT_ON;
  8227. }
  8228. break;
  8229. case CMDFUNCTION:
  8230. listsetvar(varlist.list, 0);
  8231. /* See above for the rationale */
  8232. dowait(DOWAIT_NONBLOCK, NULL);
  8233. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8234. goto raise;
  8235. break;
  8236. }
  8237. out:
  8238. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8239. if (lastarg) {
  8240. /* dsl: I think this is intended to be used to support
  8241. * '_' in 'vi' command mode during line editing...
  8242. * However I implemented that within libedit itself.
  8243. */
  8244. setvar("_", lastarg, 0);
  8245. }
  8246. popstackmark(&smark);
  8247. }
  8248. static int
  8249. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8250. {
  8251. char *volatile savecmdname;
  8252. struct jmploc *volatile savehandler;
  8253. struct jmploc jmploc;
  8254. int i;
  8255. savecmdname = commandname;
  8256. i = setjmp(jmploc.loc);
  8257. if (i)
  8258. goto cmddone;
  8259. savehandler = exception_handler;
  8260. exception_handler = &jmploc;
  8261. commandname = argv[0];
  8262. argptr = argv + 1;
  8263. optptr = NULL; /* initialize nextopt */
  8264. exitstatus = (*cmd->builtin)(argc, argv);
  8265. flush_stdout_stderr();
  8266. cmddone:
  8267. exitstatus |= ferror(stdout);
  8268. clearerr(stdout);
  8269. commandname = savecmdname;
  8270. // exsig = 0;
  8271. exception_handler = savehandler;
  8272. return i;
  8273. }
  8274. static int
  8275. goodname(const char *p)
  8276. {
  8277. return !*endofname(p);
  8278. }
  8279. /*
  8280. * Search for a command. This is called before we fork so that the
  8281. * location of the command will be available in the parent as well as
  8282. * the child. The check for "goodname" is an overly conservative
  8283. * check that the name will not be subject to expansion.
  8284. */
  8285. static void
  8286. prehash(union node *n)
  8287. {
  8288. struct cmdentry entry;
  8289. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8290. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8291. }
  8292. /* ============ Builtin commands
  8293. *
  8294. * Builtin commands whose functions are closely tied to evaluation
  8295. * are implemented here.
  8296. */
  8297. /*
  8298. * Handle break and continue commands. Break, continue, and return are
  8299. * all handled by setting the evalskip flag. The evaluation routines
  8300. * above all check this flag, and if it is set they start skipping
  8301. * commands rather than executing them. The variable skipcount is
  8302. * the number of loops to break/continue, or the number of function
  8303. * levels to return. (The latter is always 1.) It should probably
  8304. * be an error to break out of more loops than exist, but it isn't
  8305. * in the standard shell so we don't make it one here.
  8306. */
  8307. static int
  8308. breakcmd(int argc UNUSED_PARAM, char **argv)
  8309. {
  8310. int n = argv[1] ? number(argv[1]) : 1;
  8311. if (n <= 0)
  8312. ash_msg_and_raise_error(illnum, argv[1]);
  8313. if (n > loopnest)
  8314. n = loopnest;
  8315. if (n > 0) {
  8316. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8317. skipcount = n;
  8318. }
  8319. return 0;
  8320. }
  8321. /* ============ input.c
  8322. *
  8323. * This implements the input routines used by the parser.
  8324. */
  8325. enum {
  8326. INPUT_PUSH_FILE = 1,
  8327. INPUT_NOFILE_OK = 2,
  8328. };
  8329. static int plinno = 1; /* input line number */
  8330. /* number of characters left in input buffer */
  8331. static int parsenleft; /* copy of parsefile->nleft */
  8332. static int parselleft; /* copy of parsefile->lleft */
  8333. /* next character in input buffer */
  8334. static char *parsenextc; /* copy of parsefile->nextc */
  8335. static smallint checkkwd;
  8336. /* values of checkkwd variable */
  8337. #define CHKALIAS 0x1
  8338. #define CHKKWD 0x2
  8339. #define CHKNL 0x4
  8340. static void
  8341. popstring(void)
  8342. {
  8343. struct strpush *sp = g_parsefile->strpush;
  8344. INT_OFF;
  8345. #if ENABLE_ASH_ALIAS
  8346. if (sp->ap) {
  8347. if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
  8348. checkkwd |= CHKALIAS;
  8349. }
  8350. if (sp->string != sp->ap->val) {
  8351. free(sp->string);
  8352. }
  8353. sp->ap->flag &= ~ALIASINUSE;
  8354. if (sp->ap->flag & ALIASDEAD) {
  8355. unalias(sp->ap->name);
  8356. }
  8357. }
  8358. #endif
  8359. parsenextc = sp->prevstring;
  8360. parsenleft = sp->prevnleft;
  8361. g_parsefile->strpush = sp->prev;
  8362. if (sp != &(g_parsefile->basestrpush))
  8363. free(sp);
  8364. INT_ON;
  8365. }
  8366. static int
  8367. preadfd(void)
  8368. {
  8369. int nr;
  8370. char *buf = g_parsefile->buf;
  8371. parsenextc = buf;
  8372. #if ENABLE_FEATURE_EDITING
  8373. retry:
  8374. if (!iflag || g_parsefile->fd != STDIN_FILENO)
  8375. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8376. else {
  8377. #if ENABLE_FEATURE_TAB_COMPLETION
  8378. line_input_state->path_lookup = pathval();
  8379. #endif
  8380. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  8381. if (nr == 0) {
  8382. /* Ctrl+C pressed */
  8383. if (trap[SIGINT]) {
  8384. buf[0] = '\n';
  8385. buf[1] = '\0';
  8386. raise(SIGINT);
  8387. return 1;
  8388. }
  8389. goto retry;
  8390. }
  8391. if (nr < 0 && errno == 0) {
  8392. /* Ctrl+D pressed */
  8393. nr = 0;
  8394. }
  8395. }
  8396. #else
  8397. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8398. #endif
  8399. #if 0
  8400. /* nonblock_safe_read() handles this problem */
  8401. if (nr < 0) {
  8402. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8403. int flags = fcntl(0, F_GETFL);
  8404. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8405. flags &= ~O_NONBLOCK;
  8406. if (fcntl(0, F_SETFL, flags) >= 0) {
  8407. out2str("sh: turning off NDELAY mode\n");
  8408. goto retry;
  8409. }
  8410. }
  8411. }
  8412. }
  8413. #endif
  8414. return nr;
  8415. }
  8416. /*
  8417. * Refill the input buffer and return the next input character:
  8418. *
  8419. * 1) If a string was pushed back on the input, pop it;
  8420. * 2) If an EOF was pushed back (parsenleft < -BIGNUM) or we are reading
  8421. * from a string so we can't refill the buffer, return EOF.
  8422. * 3) If the is more stuff in this buffer, use it else call read to fill it.
  8423. * 4) Process input up to the next newline, deleting nul characters.
  8424. */
  8425. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8426. #define pgetc_debug(...) ((void)0)
  8427. static int
  8428. preadbuffer(void)
  8429. {
  8430. char *q;
  8431. int more;
  8432. while (g_parsefile->strpush) {
  8433. #if ENABLE_ASH_ALIAS
  8434. if (parsenleft == -1 && g_parsefile->strpush->ap
  8435. && parsenextc[-1] != ' ' && parsenextc[-1] != '\t'
  8436. ) {
  8437. pgetc_debug("preadbuffer PEOA");
  8438. return PEOA;
  8439. }
  8440. #endif
  8441. popstring();
  8442. /* try "pgetc" now: */
  8443. pgetc_debug("internal pgetc at %d:%p'%s'", parsenleft, parsenextc, parsenextc);
  8444. if (--parsenleft >= 0)
  8445. return signed_char2int(*parsenextc++);
  8446. }
  8447. /* on both branches above parsenleft < 0.
  8448. * "pgetc" needs refilling.
  8449. */
  8450. /* -90 is -BIGNUM. Below we use -99 to mark "EOF on read",
  8451. * pungetc() may decrement it a few times. -90 is enough.
  8452. */
  8453. if (parsenleft < -90 || g_parsefile->buf == NULL) {
  8454. pgetc_debug("preadbuffer PEOF1");
  8455. /* even in failure keep them in lock step,
  8456. * for correct pungetc. */
  8457. parsenextc++;
  8458. return PEOF;
  8459. }
  8460. more = parselleft;
  8461. if (more <= 0) {
  8462. flush_stdout_stderr();
  8463. again:
  8464. more = preadfd();
  8465. if (more <= 0) {
  8466. parselleft = parsenleft = -99;
  8467. pgetc_debug("preadbuffer PEOF2");
  8468. parsenextc++;
  8469. return PEOF;
  8470. }
  8471. }
  8472. /* Find out where's the end of line.
  8473. * Set parsenleft/parselleft acordingly.
  8474. * NUL chars are deleted.
  8475. */
  8476. q = parsenextc;
  8477. for (;;) {
  8478. char c;
  8479. more--;
  8480. c = *q;
  8481. if (c == '\0') {
  8482. memmove(q, q + 1, more);
  8483. } else {
  8484. q++;
  8485. if (c == '\n') {
  8486. parsenleft = q - parsenextc - 1;
  8487. break;
  8488. }
  8489. }
  8490. if (more <= 0) {
  8491. parsenleft = q - parsenextc - 1;
  8492. if (parsenleft < 0)
  8493. goto again;
  8494. break;
  8495. }
  8496. }
  8497. parselleft = more;
  8498. if (vflag) {
  8499. char save = *q;
  8500. *q = '\0';
  8501. out2str(parsenextc);
  8502. *q = save;
  8503. }
  8504. pgetc_debug("preadbuffer at %d:%p'%s'", parsenleft, parsenextc, parsenextc);
  8505. return signed_char2int(*parsenextc++);
  8506. }
  8507. #define pgetc_as_macro() (--parsenleft >= 0 ? signed_char2int(*parsenextc++) : preadbuffer())
  8508. static int
  8509. pgetc(void)
  8510. {
  8511. pgetc_debug("pgetc at %d:%p'%s'", parsenleft, parsenextc, parsenextc);
  8512. return pgetc_as_macro();
  8513. }
  8514. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8515. #define pgetc_fast() pgetc()
  8516. #else
  8517. #define pgetc_fast() pgetc_as_macro()
  8518. #endif
  8519. /*
  8520. * Same as pgetc(), but ignores PEOA.
  8521. */
  8522. #if ENABLE_ASH_ALIAS
  8523. static int
  8524. pgetc2(void)
  8525. {
  8526. int c;
  8527. do {
  8528. c = pgetc_fast();
  8529. } while (c == PEOA);
  8530. return c;
  8531. }
  8532. #else
  8533. #define pgetc2() pgetc()
  8534. #endif
  8535. /*
  8536. * Read a line from the script.
  8537. */
  8538. static char *
  8539. pfgets(char *line, int len)
  8540. {
  8541. char *p = line;
  8542. int nleft = len;
  8543. int c;
  8544. while (--nleft > 0) {
  8545. c = pgetc2();
  8546. if (c == PEOF) {
  8547. if (p == line)
  8548. return NULL;
  8549. break;
  8550. }
  8551. *p++ = c;
  8552. if (c == '\n')
  8553. break;
  8554. }
  8555. *p = '\0';
  8556. return line;
  8557. }
  8558. /*
  8559. * Undo the last call to pgetc. Only one character may be pushed back.
  8560. * PEOF may be pushed back.
  8561. */
  8562. static void
  8563. pungetc(void)
  8564. {
  8565. parsenleft++;
  8566. parsenextc--;
  8567. pgetc_debug("pushed back to %d:%p'%s'", parsenleft, parsenextc, parsenextc);
  8568. }
  8569. /*
  8570. * Push a string back onto the input at this current parsefile level.
  8571. * We handle aliases this way.
  8572. */
  8573. #if !ENABLE_ASH_ALIAS
  8574. #define pushstring(s, ap) pushstring(s)
  8575. #endif
  8576. static void
  8577. pushstring(char *s, struct alias *ap)
  8578. {
  8579. struct strpush *sp;
  8580. int len;
  8581. len = strlen(s);
  8582. INT_OFF;
  8583. if (g_parsefile->strpush) {
  8584. sp = ckzalloc(sizeof(*sp));
  8585. sp->prev = g_parsefile->strpush;
  8586. } else {
  8587. sp = &(g_parsefile->basestrpush);
  8588. }
  8589. g_parsefile->strpush = sp;
  8590. sp->prevstring = parsenextc;
  8591. sp->prevnleft = parsenleft;
  8592. #if ENABLE_ASH_ALIAS
  8593. sp->ap = ap;
  8594. if (ap) {
  8595. ap->flag |= ALIASINUSE;
  8596. sp->string = s;
  8597. }
  8598. #endif
  8599. parsenextc = s;
  8600. parsenleft = len;
  8601. INT_ON;
  8602. }
  8603. /*
  8604. * To handle the "." command, a stack of input files is used. Pushfile
  8605. * adds a new entry to the stack and popfile restores the previous level.
  8606. */
  8607. static void
  8608. pushfile(void)
  8609. {
  8610. struct parsefile *pf;
  8611. g_parsefile->nleft = parsenleft;
  8612. g_parsefile->lleft = parselleft;
  8613. g_parsefile->nextc = parsenextc;
  8614. g_parsefile->linno = plinno;
  8615. pf = ckzalloc(sizeof(*pf));
  8616. pf->prev = g_parsefile;
  8617. pf->fd = -1;
  8618. /*pf->strpush = NULL; - ckzalloc did it */
  8619. /*pf->basestrpush.prev = NULL;*/
  8620. g_parsefile = pf;
  8621. }
  8622. static void
  8623. popfile(void)
  8624. {
  8625. struct parsefile *pf = g_parsefile;
  8626. INT_OFF;
  8627. if (pf->fd >= 0)
  8628. close(pf->fd);
  8629. free(pf->buf);
  8630. while (pf->strpush)
  8631. popstring();
  8632. g_parsefile = pf->prev;
  8633. free(pf);
  8634. parsenleft = g_parsefile->nleft;
  8635. parselleft = g_parsefile->lleft;
  8636. parsenextc = g_parsefile->nextc;
  8637. plinno = g_parsefile->linno;
  8638. INT_ON;
  8639. }
  8640. /*
  8641. * Return to top level.
  8642. */
  8643. static void
  8644. popallfiles(void)
  8645. {
  8646. while (g_parsefile != &basepf)
  8647. popfile();
  8648. }
  8649. /*
  8650. * Close the file(s) that the shell is reading commands from. Called
  8651. * after a fork is done.
  8652. */
  8653. static void
  8654. closescript(void)
  8655. {
  8656. popallfiles();
  8657. if (g_parsefile->fd > 0) {
  8658. close(g_parsefile->fd);
  8659. g_parsefile->fd = 0;
  8660. }
  8661. }
  8662. /*
  8663. * Like setinputfile, but takes an open file descriptor. Call this with
  8664. * interrupts off.
  8665. */
  8666. static void
  8667. setinputfd(int fd, int push)
  8668. {
  8669. close_on_exec_on(fd);
  8670. if (push) {
  8671. pushfile();
  8672. g_parsefile->buf = NULL;
  8673. }
  8674. g_parsefile->fd = fd;
  8675. if (g_parsefile->buf == NULL)
  8676. g_parsefile->buf = ckmalloc(IBUFSIZ);
  8677. parselleft = parsenleft = 0;
  8678. plinno = 1;
  8679. }
  8680. /*
  8681. * Set the input to take input from a file. If push is set, push the
  8682. * old input onto the stack first.
  8683. */
  8684. static int
  8685. setinputfile(const char *fname, int flags)
  8686. {
  8687. int fd;
  8688. int fd2;
  8689. INT_OFF;
  8690. fd = open(fname, O_RDONLY);
  8691. if (fd < 0) {
  8692. if (flags & INPUT_NOFILE_OK)
  8693. goto out;
  8694. ash_msg_and_raise_error("can't open %s", fname);
  8695. }
  8696. if (fd < 10) {
  8697. fd2 = copyfd(fd, 10);
  8698. close(fd);
  8699. if (fd2 < 0)
  8700. ash_msg_and_raise_error("out of file descriptors");
  8701. fd = fd2;
  8702. }
  8703. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8704. out:
  8705. INT_ON;
  8706. return fd;
  8707. }
  8708. /*
  8709. * Like setinputfile, but takes input from a string.
  8710. */
  8711. static void
  8712. setinputstring(char *string)
  8713. {
  8714. INT_OFF;
  8715. pushfile();
  8716. parsenextc = string;
  8717. parsenleft = strlen(string);
  8718. g_parsefile->buf = NULL;
  8719. plinno = 1;
  8720. INT_ON;
  8721. }
  8722. /* ============ mail.c
  8723. *
  8724. * Routines to check for mail.
  8725. */
  8726. #if ENABLE_ASH_MAIL
  8727. #define MAXMBOXES 10
  8728. /* times of mailboxes */
  8729. static time_t mailtime[MAXMBOXES];
  8730. /* Set if MAIL or MAILPATH is changed. */
  8731. static smallint mail_var_path_changed;
  8732. /*
  8733. * Print appropriate message(s) if mail has arrived.
  8734. * If mail_var_path_changed is set,
  8735. * then the value of MAIL has mail_var_path_changed,
  8736. * so we just update the values.
  8737. */
  8738. static void
  8739. chkmail(void)
  8740. {
  8741. const char *mpath;
  8742. char *p;
  8743. char *q;
  8744. time_t *mtp;
  8745. struct stackmark smark;
  8746. struct stat statb;
  8747. setstackmark(&smark);
  8748. mpath = mpathset() ? mpathval() : mailval();
  8749. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8750. p = padvance(&mpath, nullstr);
  8751. if (p == NULL)
  8752. break;
  8753. if (*p == '\0')
  8754. continue;
  8755. for (q = p; *q; q++)
  8756. continue;
  8757. #if DEBUG
  8758. if (q[-1] != '/')
  8759. abort();
  8760. #endif
  8761. q[-1] = '\0'; /* delete trailing '/' */
  8762. if (stat(p, &statb) < 0) {
  8763. *mtp = 0;
  8764. continue;
  8765. }
  8766. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8767. fprintf(
  8768. stderr, snlfmt,
  8769. pathopt ? pathopt : "you have mail"
  8770. );
  8771. }
  8772. *mtp = statb.st_mtime;
  8773. }
  8774. mail_var_path_changed = 0;
  8775. popstackmark(&smark);
  8776. }
  8777. static void
  8778. changemail(const char *val UNUSED_PARAM)
  8779. {
  8780. mail_var_path_changed = 1;
  8781. }
  8782. #endif /* ASH_MAIL */
  8783. /* ============ ??? */
  8784. /*
  8785. * Set the shell parameters.
  8786. */
  8787. static void
  8788. setparam(char **argv)
  8789. {
  8790. char **newparam;
  8791. char **ap;
  8792. int nparam;
  8793. for (nparam = 0; argv[nparam]; nparam++)
  8794. continue;
  8795. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  8796. while (*argv) {
  8797. *ap++ = ckstrdup(*argv++);
  8798. }
  8799. *ap = NULL;
  8800. freeparam(&shellparam);
  8801. shellparam.malloced = 1;
  8802. shellparam.nparam = nparam;
  8803. shellparam.p = newparam;
  8804. #if ENABLE_ASH_GETOPTS
  8805. shellparam.optind = 1;
  8806. shellparam.optoff = -1;
  8807. #endif
  8808. }
  8809. /*
  8810. * Process shell options. The global variable argptr contains a pointer
  8811. * to the argument list; we advance it past the options.
  8812. *
  8813. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  8814. * For a non-interactive shell, an error condition encountered
  8815. * by a special built-in ... shall cause the shell to write a diagnostic message
  8816. * to standard error and exit as shown in the following table:
  8817. * Error Special Built-In
  8818. * ...
  8819. * Utility syntax error (option or operand error) Shall exit
  8820. * ...
  8821. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  8822. * we see that bash does not do that (set "finishes" with error code 1 instead,
  8823. * and shell continues), and people rely on this behavior!
  8824. * Testcase:
  8825. * set -o barfoo 2>/dev/null
  8826. * echo $?
  8827. *
  8828. * Oh well. Let's mimic that.
  8829. */
  8830. static int
  8831. plus_minus_o(char *name, int val)
  8832. {
  8833. int i;
  8834. if (name) {
  8835. for (i = 0; i < NOPTS; i++) {
  8836. if (strcmp(name, optnames(i)) == 0) {
  8837. optlist[i] = val;
  8838. return 0;
  8839. }
  8840. }
  8841. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  8842. return 1;
  8843. }
  8844. for (i = 0; i < NOPTS; i++) {
  8845. if (val) {
  8846. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  8847. } else {
  8848. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  8849. }
  8850. }
  8851. return 0;
  8852. }
  8853. static void
  8854. setoption(int flag, int val)
  8855. {
  8856. int i;
  8857. for (i = 0; i < NOPTS; i++) {
  8858. if (optletters(i) == flag) {
  8859. optlist[i] = val;
  8860. return;
  8861. }
  8862. }
  8863. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  8864. /* NOTREACHED */
  8865. }
  8866. static int
  8867. options(int cmdline)
  8868. {
  8869. char *p;
  8870. int val;
  8871. int c;
  8872. if (cmdline)
  8873. minusc = NULL;
  8874. while ((p = *argptr) != NULL) {
  8875. c = *p++;
  8876. if (c != '-' && c != '+')
  8877. break;
  8878. argptr++;
  8879. val = 0; /* val = 0 if c == '+' */
  8880. if (c == '-') {
  8881. val = 1;
  8882. if (p[0] == '\0' || LONE_DASH(p)) {
  8883. if (!cmdline) {
  8884. /* "-" means turn off -x and -v */
  8885. if (p[0] == '\0')
  8886. xflag = vflag = 0;
  8887. /* "--" means reset params */
  8888. else if (*argptr == NULL)
  8889. setparam(argptr);
  8890. }
  8891. break; /* "-" or "--" terminates options */
  8892. }
  8893. }
  8894. /* first char was + or - */
  8895. while ((c = *p++) != '\0') {
  8896. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  8897. if (c == 'c' && cmdline) {
  8898. minusc = p; /* command is after shell args */
  8899. } else if (c == 'o') {
  8900. if (plus_minus_o(*argptr, val)) {
  8901. /* it already printed err message */
  8902. return 1; /* error */
  8903. }
  8904. if (*argptr)
  8905. argptr++;
  8906. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  8907. isloginsh = 1;
  8908. /* bash does not accept +-login, we also won't */
  8909. } else if (cmdline && val && (c == '-')) { /* long options */
  8910. if (strcmp(p, "login") == 0)
  8911. isloginsh = 1;
  8912. break;
  8913. } else {
  8914. setoption(c, val);
  8915. }
  8916. }
  8917. }
  8918. return 0;
  8919. }
  8920. /*
  8921. * The shift builtin command.
  8922. */
  8923. static int
  8924. shiftcmd(int argc UNUSED_PARAM, char **argv)
  8925. {
  8926. int n;
  8927. char **ap1, **ap2;
  8928. n = 1;
  8929. if (argv[1])
  8930. n = number(argv[1]);
  8931. if (n > shellparam.nparam)
  8932. n = 0; /* bash compat, was = shellparam.nparam; */
  8933. INT_OFF;
  8934. shellparam.nparam -= n;
  8935. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  8936. if (shellparam.malloced)
  8937. free(*ap1);
  8938. }
  8939. ap2 = shellparam.p;
  8940. while ((*ap2++ = *ap1++) != NULL)
  8941. continue;
  8942. #if ENABLE_ASH_GETOPTS
  8943. shellparam.optind = 1;
  8944. shellparam.optoff = -1;
  8945. #endif
  8946. INT_ON;
  8947. return 0;
  8948. }
  8949. /*
  8950. * POSIX requires that 'set' (but not export or readonly) output the
  8951. * variables in lexicographic order - by the locale's collating order (sigh).
  8952. * Maybe we could keep them in an ordered balanced binary tree
  8953. * instead of hashed lists.
  8954. * For now just roll 'em through qsort for printing...
  8955. */
  8956. static int
  8957. showvars(const char *sep_prefix, int on, int off)
  8958. {
  8959. const char *sep;
  8960. char **ep, **epend;
  8961. ep = listvars(on, off, &epend);
  8962. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  8963. sep = *sep_prefix ? " " : sep_prefix;
  8964. for (; ep < epend; ep++) {
  8965. const char *p;
  8966. const char *q;
  8967. p = strchrnul(*ep, '=');
  8968. q = nullstr;
  8969. if (*p)
  8970. q = single_quote(++p);
  8971. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  8972. }
  8973. return 0;
  8974. }
  8975. /*
  8976. * The set command builtin.
  8977. */
  8978. static int
  8979. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8980. {
  8981. int retval;
  8982. if (!argv[1])
  8983. return showvars(nullstr, 0, VUNSET);
  8984. INT_OFF;
  8985. retval = 1;
  8986. if (!options(0)) { /* if no parse error... */
  8987. retval = 0;
  8988. optschanged();
  8989. if (*argptr != NULL) {
  8990. setparam(argptr);
  8991. }
  8992. }
  8993. INT_ON;
  8994. return retval;
  8995. }
  8996. #if ENABLE_ASH_RANDOM_SUPPORT
  8997. static void
  8998. change_random(const char *value)
  8999. {
  9000. /* Galois LFSR parameter */
  9001. /* Taps at 32 31 29 1: */
  9002. enum { MASK = 0x8000000b };
  9003. /* Another example - taps at 32 31 30 10: */
  9004. /* MASK = 0x00400007 */
  9005. if (value == NULL) {
  9006. /* "get", generate */
  9007. uint32_t t;
  9008. /* LCG has period of 2^32 and alternating lowest bit */
  9009. random_LCG = 1664525 * random_LCG + 1013904223;
  9010. /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
  9011. t = (random_galois_LFSR << 1);
  9012. if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
  9013. t ^= MASK;
  9014. random_galois_LFSR = t;
  9015. /* Both are weak, combining them gives better randomness
  9016. * and ~2^64 period. & 0x7fff is probably bash compat
  9017. * for $RANDOM range. Combining with subtraction is
  9018. * just for fun. + and ^ would work equally well. */
  9019. t = (t - random_LCG) & 0x7fff;
  9020. /* set without recursion */
  9021. setvar(vrandom.text, utoa(t), VNOFUNC);
  9022. vrandom.flags &= ~VNOFUNC;
  9023. } else {
  9024. /* set/reset */
  9025. random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
  9026. }
  9027. }
  9028. #endif
  9029. #if ENABLE_ASH_GETOPTS
  9030. static int
  9031. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9032. {
  9033. char *p, *q;
  9034. char c = '?';
  9035. int done = 0;
  9036. int err = 0;
  9037. char s[12];
  9038. char **optnext;
  9039. if (*param_optind < 1)
  9040. return 1;
  9041. optnext = optfirst + *param_optind - 1;
  9042. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9043. p = NULL;
  9044. else
  9045. p = optnext[-1] + *optoff;
  9046. if (p == NULL || *p == '\0') {
  9047. /* Current word is done, advance */
  9048. p = *optnext;
  9049. if (p == NULL || *p != '-' || *++p == '\0') {
  9050. atend:
  9051. p = NULL;
  9052. done = 1;
  9053. goto out;
  9054. }
  9055. optnext++;
  9056. if (LONE_DASH(p)) /* check for "--" */
  9057. goto atend;
  9058. }
  9059. c = *p++;
  9060. for (q = optstr; *q != c;) {
  9061. if (*q == '\0') {
  9062. if (optstr[0] == ':') {
  9063. s[0] = c;
  9064. s[1] = '\0';
  9065. err |= setvarsafe("OPTARG", s, 0);
  9066. } else {
  9067. fprintf(stderr, "Illegal option -%c\n", c);
  9068. unsetvar("OPTARG");
  9069. }
  9070. c = '?';
  9071. goto out;
  9072. }
  9073. if (*++q == ':')
  9074. q++;
  9075. }
  9076. if (*++q == ':') {
  9077. if (*p == '\0' && (p = *optnext) == NULL) {
  9078. if (optstr[0] == ':') {
  9079. s[0] = c;
  9080. s[1] = '\0';
  9081. err |= setvarsafe("OPTARG", s, 0);
  9082. c = ':';
  9083. } else {
  9084. fprintf(stderr, "No arg for -%c option\n", c);
  9085. unsetvar("OPTARG");
  9086. c = '?';
  9087. }
  9088. goto out;
  9089. }
  9090. if (p == *optnext)
  9091. optnext++;
  9092. err |= setvarsafe("OPTARG", p, 0);
  9093. p = NULL;
  9094. } else
  9095. err |= setvarsafe("OPTARG", nullstr, 0);
  9096. out:
  9097. *optoff = p ? p - *(optnext - 1) : -1;
  9098. *param_optind = optnext - optfirst + 1;
  9099. fmtstr(s, sizeof(s), "%d", *param_optind);
  9100. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9101. s[0] = c;
  9102. s[1] = '\0';
  9103. err |= setvarsafe(optvar, s, 0);
  9104. if (err) {
  9105. *param_optind = 1;
  9106. *optoff = -1;
  9107. flush_stdout_stderr();
  9108. raise_exception(EXERROR);
  9109. }
  9110. return done;
  9111. }
  9112. /*
  9113. * The getopts builtin. Shellparam.optnext points to the next argument
  9114. * to be processed. Shellparam.optptr points to the next character to
  9115. * be processed in the current argument. If shellparam.optnext is NULL,
  9116. * then it's the first time getopts has been called.
  9117. */
  9118. static int
  9119. getoptscmd(int argc, char **argv)
  9120. {
  9121. char **optbase;
  9122. if (argc < 3)
  9123. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9124. if (argc == 3) {
  9125. optbase = shellparam.p;
  9126. if (shellparam.optind > shellparam.nparam + 1) {
  9127. shellparam.optind = 1;
  9128. shellparam.optoff = -1;
  9129. }
  9130. } else {
  9131. optbase = &argv[3];
  9132. if (shellparam.optind > argc - 2) {
  9133. shellparam.optind = 1;
  9134. shellparam.optoff = -1;
  9135. }
  9136. }
  9137. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9138. &shellparam.optoff);
  9139. }
  9140. #endif /* ASH_GETOPTS */
  9141. /* ============ Shell parser */
  9142. struct heredoc {
  9143. struct heredoc *next; /* next here document in list */
  9144. union node *here; /* redirection node */
  9145. char *eofmark; /* string indicating end of input */
  9146. smallint striptabs; /* if set, strip leading tabs */
  9147. };
  9148. static smallint tokpushback; /* last token pushed back */
  9149. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9150. static smallint quoteflag; /* set if (part of) last token was quoted */
  9151. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9152. static struct heredoc *heredoclist; /* list of here documents to read */
  9153. static char *wordtext; /* text of last word returned by readtoken */
  9154. static struct nodelist *backquotelist;
  9155. static union node *redirnode;
  9156. static struct heredoc *heredoc;
  9157. /*
  9158. * NEOF is returned by parsecmd when it encounters an end of file. It
  9159. * must be distinct from NULL, so we use the address of a variable that
  9160. * happens to be handy.
  9161. */
  9162. #define NEOF ((union node *)&tokpushback)
  9163. static void raise_error_syntax(const char *) NORETURN;
  9164. static void
  9165. raise_error_syntax(const char *msg)
  9166. {
  9167. ash_msg_and_raise_error("syntax error: %s", msg);
  9168. /* NOTREACHED */
  9169. }
  9170. /*
  9171. * Called when an unexpected token is read during the parse. The argument
  9172. * is the token that is expected, or -1 if more than one type of token can
  9173. * occur at this point.
  9174. */
  9175. static void raise_error_unexpected_syntax(int) NORETURN;
  9176. static void
  9177. raise_error_unexpected_syntax(int token)
  9178. {
  9179. char msg[64];
  9180. int l;
  9181. l = sprintf(msg, "%s unexpected", tokname(lasttoken));
  9182. if (token >= 0)
  9183. sprintf(msg + l, " (expecting %s)", tokname(token));
  9184. raise_error_syntax(msg);
  9185. /* NOTREACHED */
  9186. }
  9187. #define EOFMARKLEN 79
  9188. /* parsing is heavily cross-recursive, need these forward decls */
  9189. static union node *andor(void);
  9190. static union node *pipeline(void);
  9191. static union node *parse_command(void);
  9192. static void parseheredoc(void);
  9193. static char peektoken(void);
  9194. static int readtoken(void);
  9195. static union node *
  9196. list(int nlflag)
  9197. {
  9198. union node *n1, *n2, *n3;
  9199. int tok;
  9200. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9201. if (nlflag == 2 && peektoken())
  9202. return NULL;
  9203. n1 = NULL;
  9204. for (;;) {
  9205. n2 = andor();
  9206. tok = readtoken();
  9207. if (tok == TBACKGND) {
  9208. if (n2->type == NPIPE) {
  9209. n2->npipe.pipe_backgnd = 1;
  9210. } else {
  9211. if (n2->type != NREDIR) {
  9212. n3 = stzalloc(sizeof(struct nredir));
  9213. n3->nredir.n = n2;
  9214. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9215. n2 = n3;
  9216. }
  9217. n2->type = NBACKGND;
  9218. }
  9219. }
  9220. if (n1 == NULL) {
  9221. n1 = n2;
  9222. } else {
  9223. n3 = stzalloc(sizeof(struct nbinary));
  9224. n3->type = NSEMI;
  9225. n3->nbinary.ch1 = n1;
  9226. n3->nbinary.ch2 = n2;
  9227. n1 = n3;
  9228. }
  9229. switch (tok) {
  9230. case TBACKGND:
  9231. case TSEMI:
  9232. tok = readtoken();
  9233. /* fall through */
  9234. case TNL:
  9235. if (tok == TNL) {
  9236. parseheredoc();
  9237. if (nlflag == 1)
  9238. return n1;
  9239. } else {
  9240. tokpushback = 1;
  9241. }
  9242. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9243. if (peektoken())
  9244. return n1;
  9245. break;
  9246. case TEOF:
  9247. if (heredoclist)
  9248. parseheredoc();
  9249. else
  9250. pungetc(); /* push back EOF on input */
  9251. return n1;
  9252. default:
  9253. if (nlflag == 1)
  9254. raise_error_unexpected_syntax(-1);
  9255. tokpushback = 1;
  9256. return n1;
  9257. }
  9258. }
  9259. }
  9260. static union node *
  9261. andor(void)
  9262. {
  9263. union node *n1, *n2, *n3;
  9264. int t;
  9265. n1 = pipeline();
  9266. for (;;) {
  9267. t = readtoken();
  9268. if (t == TAND) {
  9269. t = NAND;
  9270. } else if (t == TOR) {
  9271. t = NOR;
  9272. } else {
  9273. tokpushback = 1;
  9274. return n1;
  9275. }
  9276. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9277. n2 = pipeline();
  9278. n3 = stzalloc(sizeof(struct nbinary));
  9279. n3->type = t;
  9280. n3->nbinary.ch1 = n1;
  9281. n3->nbinary.ch2 = n2;
  9282. n1 = n3;
  9283. }
  9284. }
  9285. static union node *
  9286. pipeline(void)
  9287. {
  9288. union node *n1, *n2, *pipenode;
  9289. struct nodelist *lp, *prev;
  9290. int negate;
  9291. negate = 0;
  9292. TRACE(("pipeline: entered\n"));
  9293. if (readtoken() == TNOT) {
  9294. negate = !negate;
  9295. checkkwd = CHKKWD | CHKALIAS;
  9296. } else
  9297. tokpushback = 1;
  9298. n1 = parse_command();
  9299. if (readtoken() == TPIPE) {
  9300. pipenode = stzalloc(sizeof(struct npipe));
  9301. pipenode->type = NPIPE;
  9302. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9303. lp = stzalloc(sizeof(struct nodelist));
  9304. pipenode->npipe.cmdlist = lp;
  9305. lp->n = n1;
  9306. do {
  9307. prev = lp;
  9308. lp = stzalloc(sizeof(struct nodelist));
  9309. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9310. lp->n = parse_command();
  9311. prev->next = lp;
  9312. } while (readtoken() == TPIPE);
  9313. lp->next = NULL;
  9314. n1 = pipenode;
  9315. }
  9316. tokpushback = 1;
  9317. if (negate) {
  9318. n2 = stzalloc(sizeof(struct nnot));
  9319. n2->type = NNOT;
  9320. n2->nnot.com = n1;
  9321. return n2;
  9322. }
  9323. return n1;
  9324. }
  9325. static union node *
  9326. makename(void)
  9327. {
  9328. union node *n;
  9329. n = stzalloc(sizeof(struct narg));
  9330. n->type = NARG;
  9331. /*n->narg.next = NULL; - stzalloc did it */
  9332. n->narg.text = wordtext;
  9333. n->narg.backquote = backquotelist;
  9334. return n;
  9335. }
  9336. static void
  9337. fixredir(union node *n, const char *text, int err)
  9338. {
  9339. int fd;
  9340. TRACE(("Fix redir %s %d\n", text, err));
  9341. if (!err)
  9342. n->ndup.vname = NULL;
  9343. fd = bb_strtou(text, NULL, 10);
  9344. if (!errno && fd >= 0)
  9345. n->ndup.dupfd = fd;
  9346. else if (LONE_DASH(text))
  9347. n->ndup.dupfd = -1;
  9348. else {
  9349. if (err)
  9350. raise_error_syntax("bad fd number");
  9351. n->ndup.vname = makename();
  9352. }
  9353. }
  9354. /*
  9355. * Returns true if the text contains nothing to expand (no dollar signs
  9356. * or backquotes).
  9357. */
  9358. static int
  9359. noexpand(char *text)
  9360. {
  9361. char *p;
  9362. char c;
  9363. p = text;
  9364. while ((c = *p++) != '\0') {
  9365. if (c == CTLQUOTEMARK)
  9366. continue;
  9367. if (c == CTLESC)
  9368. p++;
  9369. else if (SIT(c, BASESYNTAX) == CCTL)
  9370. return 0;
  9371. }
  9372. return 1;
  9373. }
  9374. static void
  9375. parsefname(void)
  9376. {
  9377. union node *n = redirnode;
  9378. if (readtoken() != TWORD)
  9379. raise_error_unexpected_syntax(-1);
  9380. if (n->type == NHERE) {
  9381. struct heredoc *here = heredoc;
  9382. struct heredoc *p;
  9383. int i;
  9384. if (quoteflag == 0)
  9385. n->type = NXHERE;
  9386. TRACE(("Here document %d\n", n->type));
  9387. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9388. raise_error_syntax("illegal eof marker for << redirection");
  9389. rmescapes(wordtext);
  9390. here->eofmark = wordtext;
  9391. here->next = NULL;
  9392. if (heredoclist == NULL)
  9393. heredoclist = here;
  9394. else {
  9395. for (p = heredoclist; p->next; p = p->next)
  9396. continue;
  9397. p->next = here;
  9398. }
  9399. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9400. fixredir(n, wordtext, 0);
  9401. } else {
  9402. n->nfile.fname = makename();
  9403. }
  9404. }
  9405. static union node *
  9406. simplecmd(void)
  9407. {
  9408. union node *args, **app;
  9409. union node *n = NULL;
  9410. union node *vars, **vpp;
  9411. union node **rpp, *redir;
  9412. int savecheckkwd;
  9413. #if ENABLE_ASH_BASH_COMPAT
  9414. smallint double_brackets_flag = 0;
  9415. #endif
  9416. args = NULL;
  9417. app = &args;
  9418. vars = NULL;
  9419. vpp = &vars;
  9420. redir = NULL;
  9421. rpp = &redir;
  9422. savecheckkwd = CHKALIAS;
  9423. for (;;) {
  9424. int t;
  9425. checkkwd = savecheckkwd;
  9426. t = readtoken();
  9427. switch (t) {
  9428. #if ENABLE_ASH_BASH_COMPAT
  9429. case TAND: /* "&&" */
  9430. case TOR: /* "||" */
  9431. if (!double_brackets_flag) {
  9432. tokpushback = 1;
  9433. goto out;
  9434. }
  9435. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9436. #endif
  9437. case TWORD:
  9438. n = stzalloc(sizeof(struct narg));
  9439. n->type = NARG;
  9440. /*n->narg.next = NULL; - stzalloc did it */
  9441. n->narg.text = wordtext;
  9442. #if ENABLE_ASH_BASH_COMPAT
  9443. if (strcmp("[[", wordtext) == 0)
  9444. double_brackets_flag = 1;
  9445. else if (strcmp("]]", wordtext) == 0)
  9446. double_brackets_flag = 0;
  9447. #endif
  9448. n->narg.backquote = backquotelist;
  9449. if (savecheckkwd && isassignment(wordtext)) {
  9450. *vpp = n;
  9451. vpp = &n->narg.next;
  9452. } else {
  9453. *app = n;
  9454. app = &n->narg.next;
  9455. savecheckkwd = 0;
  9456. }
  9457. break;
  9458. case TREDIR:
  9459. *rpp = n = redirnode;
  9460. rpp = &n->nfile.next;
  9461. parsefname(); /* read name of redirection file */
  9462. break;
  9463. case TLP:
  9464. if (args && app == &args->narg.next
  9465. && !vars && !redir
  9466. ) {
  9467. struct builtincmd *bcmd;
  9468. const char *name;
  9469. /* We have a function */
  9470. if (readtoken() != TRP)
  9471. raise_error_unexpected_syntax(TRP);
  9472. name = n->narg.text;
  9473. if (!goodname(name)
  9474. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9475. ) {
  9476. raise_error_syntax("bad function name");
  9477. }
  9478. n->type = NDEFUN;
  9479. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9480. n->narg.next = parse_command();
  9481. return n;
  9482. }
  9483. /* fall through */
  9484. default:
  9485. tokpushback = 1;
  9486. goto out;
  9487. }
  9488. }
  9489. out:
  9490. *app = NULL;
  9491. *vpp = NULL;
  9492. *rpp = NULL;
  9493. n = stzalloc(sizeof(struct ncmd));
  9494. n->type = NCMD;
  9495. n->ncmd.args = args;
  9496. n->ncmd.assign = vars;
  9497. n->ncmd.redirect = redir;
  9498. return n;
  9499. }
  9500. static union node *
  9501. parse_command(void)
  9502. {
  9503. union node *n1, *n2;
  9504. union node *ap, **app;
  9505. union node *cp, **cpp;
  9506. union node *redir, **rpp;
  9507. union node **rpp2;
  9508. int t;
  9509. redir = NULL;
  9510. rpp2 = &redir;
  9511. switch (readtoken()) {
  9512. default:
  9513. raise_error_unexpected_syntax(-1);
  9514. /* NOTREACHED */
  9515. case TIF:
  9516. n1 = stzalloc(sizeof(struct nif));
  9517. n1->type = NIF;
  9518. n1->nif.test = list(0);
  9519. if (readtoken() != TTHEN)
  9520. raise_error_unexpected_syntax(TTHEN);
  9521. n1->nif.ifpart = list(0);
  9522. n2 = n1;
  9523. while (readtoken() == TELIF) {
  9524. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9525. n2 = n2->nif.elsepart;
  9526. n2->type = NIF;
  9527. n2->nif.test = list(0);
  9528. if (readtoken() != TTHEN)
  9529. raise_error_unexpected_syntax(TTHEN);
  9530. n2->nif.ifpart = list(0);
  9531. }
  9532. if (lasttoken == TELSE)
  9533. n2->nif.elsepart = list(0);
  9534. else {
  9535. n2->nif.elsepart = NULL;
  9536. tokpushback = 1;
  9537. }
  9538. t = TFI;
  9539. break;
  9540. case TWHILE:
  9541. case TUNTIL: {
  9542. int got;
  9543. n1 = stzalloc(sizeof(struct nbinary));
  9544. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9545. n1->nbinary.ch1 = list(0);
  9546. got = readtoken();
  9547. if (got != TDO) {
  9548. TRACE(("expecting DO got %s %s\n", tokname(got),
  9549. got == TWORD ? wordtext : ""));
  9550. raise_error_unexpected_syntax(TDO);
  9551. }
  9552. n1->nbinary.ch2 = list(0);
  9553. t = TDONE;
  9554. break;
  9555. }
  9556. case TFOR:
  9557. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9558. raise_error_syntax("bad for loop variable");
  9559. n1 = stzalloc(sizeof(struct nfor));
  9560. n1->type = NFOR;
  9561. n1->nfor.var = wordtext;
  9562. checkkwd = CHKKWD | CHKALIAS;
  9563. if (readtoken() == TIN) {
  9564. app = &ap;
  9565. while (readtoken() == TWORD) {
  9566. n2 = stzalloc(sizeof(struct narg));
  9567. n2->type = NARG;
  9568. /*n2->narg.next = NULL; - stzalloc did it */
  9569. n2->narg.text = wordtext;
  9570. n2->narg.backquote = backquotelist;
  9571. *app = n2;
  9572. app = &n2->narg.next;
  9573. }
  9574. *app = NULL;
  9575. n1->nfor.args = ap;
  9576. if (lasttoken != TNL && lasttoken != TSEMI)
  9577. raise_error_unexpected_syntax(-1);
  9578. } else {
  9579. n2 = stzalloc(sizeof(struct narg));
  9580. n2->type = NARG;
  9581. /*n2->narg.next = NULL; - stzalloc did it */
  9582. n2->narg.text = (char *)dolatstr;
  9583. /*n2->narg.backquote = NULL;*/
  9584. n1->nfor.args = n2;
  9585. /*
  9586. * Newline or semicolon here is optional (but note
  9587. * that the original Bourne shell only allowed NL).
  9588. */
  9589. if (lasttoken != TNL && lasttoken != TSEMI)
  9590. tokpushback = 1;
  9591. }
  9592. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9593. if (readtoken() != TDO)
  9594. raise_error_unexpected_syntax(TDO);
  9595. n1->nfor.body = list(0);
  9596. t = TDONE;
  9597. break;
  9598. case TCASE:
  9599. n1 = stzalloc(sizeof(struct ncase));
  9600. n1->type = NCASE;
  9601. if (readtoken() != TWORD)
  9602. raise_error_unexpected_syntax(TWORD);
  9603. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  9604. n2->type = NARG;
  9605. /*n2->narg.next = NULL; - stzalloc did it */
  9606. n2->narg.text = wordtext;
  9607. n2->narg.backquote = backquotelist;
  9608. do {
  9609. checkkwd = CHKKWD | CHKALIAS;
  9610. } while (readtoken() == TNL);
  9611. if (lasttoken != TIN)
  9612. raise_error_unexpected_syntax(TIN);
  9613. cpp = &n1->ncase.cases;
  9614. next_case:
  9615. checkkwd = CHKNL | CHKKWD;
  9616. t = readtoken();
  9617. while (t != TESAC) {
  9618. if (lasttoken == TLP)
  9619. readtoken();
  9620. *cpp = cp = stzalloc(sizeof(struct nclist));
  9621. cp->type = NCLIST;
  9622. app = &cp->nclist.pattern;
  9623. for (;;) {
  9624. *app = ap = stzalloc(sizeof(struct narg));
  9625. ap->type = NARG;
  9626. /*ap->narg.next = NULL; - stzalloc did it */
  9627. ap->narg.text = wordtext;
  9628. ap->narg.backquote = backquotelist;
  9629. if (readtoken() != TPIPE)
  9630. break;
  9631. app = &ap->narg.next;
  9632. readtoken();
  9633. }
  9634. //ap->narg.next = NULL;
  9635. if (lasttoken != TRP)
  9636. raise_error_unexpected_syntax(TRP);
  9637. cp->nclist.body = list(2);
  9638. cpp = &cp->nclist.next;
  9639. checkkwd = CHKNL | CHKKWD;
  9640. t = readtoken();
  9641. if (t != TESAC) {
  9642. if (t != TENDCASE)
  9643. raise_error_unexpected_syntax(TENDCASE);
  9644. goto next_case;
  9645. }
  9646. }
  9647. *cpp = NULL;
  9648. goto redir;
  9649. case TLP:
  9650. n1 = stzalloc(sizeof(struct nredir));
  9651. n1->type = NSUBSHELL;
  9652. n1->nredir.n = list(0);
  9653. /*n1->nredir.redirect = NULL; - stzalloc did it */
  9654. t = TRP;
  9655. break;
  9656. case TBEGIN:
  9657. n1 = list(0);
  9658. t = TEND;
  9659. break;
  9660. case TWORD:
  9661. case TREDIR:
  9662. tokpushback = 1;
  9663. return simplecmd();
  9664. }
  9665. if (readtoken() != t)
  9666. raise_error_unexpected_syntax(t);
  9667. redir:
  9668. /* Now check for redirection which may follow command */
  9669. checkkwd = CHKKWD | CHKALIAS;
  9670. rpp = rpp2;
  9671. while (readtoken() == TREDIR) {
  9672. *rpp = n2 = redirnode;
  9673. rpp = &n2->nfile.next;
  9674. parsefname();
  9675. }
  9676. tokpushback = 1;
  9677. *rpp = NULL;
  9678. if (redir) {
  9679. if (n1->type != NSUBSHELL) {
  9680. n2 = stzalloc(sizeof(struct nredir));
  9681. n2->type = NREDIR;
  9682. n2->nredir.n = n1;
  9683. n1 = n2;
  9684. }
  9685. n1->nredir.redirect = redir;
  9686. }
  9687. return n1;
  9688. }
  9689. #if ENABLE_ASH_BASH_COMPAT
  9690. static int decode_dollar_squote(void)
  9691. {
  9692. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  9693. int c, cnt;
  9694. char *p;
  9695. char buf[4];
  9696. c = pgetc();
  9697. p = strchr(C_escapes, c);
  9698. if (p) {
  9699. buf[0] = c;
  9700. p = buf;
  9701. cnt = 3;
  9702. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  9703. do {
  9704. c = pgetc();
  9705. *++p = c;
  9706. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  9707. pungetc();
  9708. } else if (c == 'x') { /* \xHH */
  9709. do {
  9710. c = pgetc();
  9711. *++p = c;
  9712. } while (isxdigit(c) && --cnt);
  9713. pungetc();
  9714. if (cnt == 3) { /* \x but next char is "bad" */
  9715. c = 'x';
  9716. goto unrecognized;
  9717. }
  9718. } else { /* simple seq like \\ or \t */
  9719. p++;
  9720. }
  9721. *p = '\0';
  9722. p = buf;
  9723. c = bb_process_escape_sequence((void*)&p);
  9724. } else { /* unrecognized "\z": print both chars unless ' or " */
  9725. if (c != '\'' && c != '"') {
  9726. unrecognized:
  9727. c |= 0x100; /* "please encode \, then me" */
  9728. }
  9729. }
  9730. return c;
  9731. }
  9732. #endif
  9733. /*
  9734. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  9735. * is not NULL, read a here document. In the latter case, eofmark is the
  9736. * word which marks the end of the document and striptabs is true if
  9737. * leading tabs should be stripped from the document. The argument firstc
  9738. * is the first character of the input token or document.
  9739. *
  9740. * Because C does not have internal subroutines, I have simulated them
  9741. * using goto's to implement the subroutine linkage. The following macros
  9742. * will run code that appears at the end of readtoken1.
  9743. */
  9744. #define CHECKEND() {goto checkend; checkend_return:;}
  9745. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  9746. #define PARSESUB() {goto parsesub; parsesub_return:;}
  9747. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  9748. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  9749. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  9750. static int
  9751. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  9752. {
  9753. /* NB: syntax parameter fits into smallint */
  9754. int c = firstc;
  9755. char *out;
  9756. int len;
  9757. char line[EOFMARKLEN + 1];
  9758. struct nodelist *bqlist;
  9759. smallint quotef;
  9760. smallint dblquote;
  9761. smallint oldstyle;
  9762. smallint prevsyntax; /* syntax before arithmetic */
  9763. #if ENABLE_ASH_EXPAND_PRMT
  9764. smallint pssyntax; /* we are expanding a prompt string */
  9765. #endif
  9766. int varnest; /* levels of variables expansion */
  9767. int arinest; /* levels of arithmetic expansion */
  9768. int parenlevel; /* levels of parens in arithmetic */
  9769. int dqvarnest; /* levels of variables expansion within double quotes */
  9770. USE_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  9771. #if __GNUC__
  9772. /* Avoid longjmp clobbering */
  9773. (void) &out;
  9774. (void) &quotef;
  9775. (void) &dblquote;
  9776. (void) &varnest;
  9777. (void) &arinest;
  9778. (void) &parenlevel;
  9779. (void) &dqvarnest;
  9780. (void) &oldstyle;
  9781. (void) &prevsyntax;
  9782. (void) &syntax;
  9783. #endif
  9784. startlinno = plinno;
  9785. bqlist = NULL;
  9786. quotef = 0;
  9787. oldstyle = 0;
  9788. prevsyntax = 0;
  9789. #if ENABLE_ASH_EXPAND_PRMT
  9790. pssyntax = (syntax == PSSYNTAX);
  9791. if (pssyntax)
  9792. syntax = DQSYNTAX;
  9793. #endif
  9794. dblquote = (syntax == DQSYNTAX);
  9795. varnest = 0;
  9796. arinest = 0;
  9797. parenlevel = 0;
  9798. dqvarnest = 0;
  9799. STARTSTACKSTR(out);
  9800. loop:
  9801. /* For each line, until end of word */
  9802. {
  9803. CHECKEND(); /* set c to PEOF if at end of here document */
  9804. for (;;) { /* until end of line or end of word */
  9805. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  9806. switch (SIT(c, syntax)) {
  9807. case CNL: /* '\n' */
  9808. if (syntax == BASESYNTAX)
  9809. goto endword; /* exit outer loop */
  9810. USTPUTC(c, out);
  9811. plinno++;
  9812. if (doprompt)
  9813. setprompt(2);
  9814. c = pgetc();
  9815. goto loop; /* continue outer loop */
  9816. case CWORD:
  9817. USTPUTC(c, out);
  9818. break;
  9819. case CCTL:
  9820. if (eofmark == NULL || dblquote)
  9821. USTPUTC(CTLESC, out);
  9822. #if ENABLE_ASH_BASH_COMPAT
  9823. if (c == '\\' && bash_dollar_squote) {
  9824. c = decode_dollar_squote();
  9825. if (c & 0x100) {
  9826. USTPUTC('\\', out);
  9827. c = (unsigned char)c;
  9828. }
  9829. }
  9830. #endif
  9831. USTPUTC(c, out);
  9832. break;
  9833. case CBACK: /* backslash */
  9834. c = pgetc2();
  9835. if (c == PEOF) {
  9836. USTPUTC(CTLESC, out);
  9837. USTPUTC('\\', out);
  9838. pungetc();
  9839. } else if (c == '\n') {
  9840. if (doprompt)
  9841. setprompt(2);
  9842. } else {
  9843. #if ENABLE_ASH_EXPAND_PRMT
  9844. if (c == '$' && pssyntax) {
  9845. USTPUTC(CTLESC, out);
  9846. USTPUTC('\\', out);
  9847. }
  9848. #endif
  9849. if (dblquote && c != '\\'
  9850. && c != '`' && c != '$'
  9851. && (c != '"' || eofmark != NULL)
  9852. ) {
  9853. USTPUTC(CTLESC, out);
  9854. USTPUTC('\\', out);
  9855. }
  9856. if (SIT(c, SQSYNTAX) == CCTL)
  9857. USTPUTC(CTLESC, out);
  9858. USTPUTC(c, out);
  9859. quotef = 1;
  9860. }
  9861. break;
  9862. case CSQUOTE:
  9863. syntax = SQSYNTAX;
  9864. quotemark:
  9865. if (eofmark == NULL) {
  9866. USTPUTC(CTLQUOTEMARK, out);
  9867. }
  9868. break;
  9869. case CDQUOTE:
  9870. syntax = DQSYNTAX;
  9871. dblquote = 1;
  9872. goto quotemark;
  9873. case CENDQUOTE:
  9874. USE_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  9875. if (eofmark != NULL && arinest == 0
  9876. && varnest == 0
  9877. ) {
  9878. USTPUTC(c, out);
  9879. } else {
  9880. if (dqvarnest == 0) {
  9881. syntax = BASESYNTAX;
  9882. dblquote = 0;
  9883. }
  9884. quotef = 1;
  9885. goto quotemark;
  9886. }
  9887. break;
  9888. case CVAR: /* '$' */
  9889. PARSESUB(); /* parse substitution */
  9890. break;
  9891. case CENDVAR: /* '}' */
  9892. if (varnest > 0) {
  9893. varnest--;
  9894. if (dqvarnest > 0) {
  9895. dqvarnest--;
  9896. }
  9897. USTPUTC(CTLENDVAR, out);
  9898. } else {
  9899. USTPUTC(c, out);
  9900. }
  9901. break;
  9902. #if ENABLE_ASH_MATH_SUPPORT
  9903. case CLP: /* '(' in arithmetic */
  9904. parenlevel++;
  9905. USTPUTC(c, out);
  9906. break;
  9907. case CRP: /* ')' in arithmetic */
  9908. if (parenlevel > 0) {
  9909. USTPUTC(c, out);
  9910. --parenlevel;
  9911. } else {
  9912. if (pgetc() == ')') {
  9913. if (--arinest == 0) {
  9914. USTPUTC(CTLENDARI, out);
  9915. syntax = prevsyntax;
  9916. dblquote = (syntax == DQSYNTAX);
  9917. } else
  9918. USTPUTC(')', out);
  9919. } else {
  9920. /*
  9921. * unbalanced parens
  9922. * (don't 2nd guess - no error)
  9923. */
  9924. pungetc();
  9925. USTPUTC(')', out);
  9926. }
  9927. }
  9928. break;
  9929. #endif
  9930. case CBQUOTE: /* '`' */
  9931. PARSEBACKQOLD();
  9932. break;
  9933. case CENDFILE:
  9934. goto endword; /* exit outer loop */
  9935. case CIGN:
  9936. break;
  9937. default:
  9938. if (varnest == 0) {
  9939. #if ENABLE_ASH_BASH_COMPAT
  9940. if (c == '&') {
  9941. if (pgetc() == '>')
  9942. c = 0x100 + '>'; /* flag &> */
  9943. pungetc();
  9944. }
  9945. #endif
  9946. goto endword; /* exit outer loop */
  9947. }
  9948. #if ENABLE_ASH_ALIAS
  9949. if (c != PEOA)
  9950. #endif
  9951. USTPUTC(c, out);
  9952. }
  9953. c = pgetc_fast();
  9954. } /* for (;;) */
  9955. }
  9956. endword:
  9957. #if ENABLE_ASH_MATH_SUPPORT
  9958. if (syntax == ARISYNTAX)
  9959. raise_error_syntax("missing '))'");
  9960. #endif
  9961. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  9962. raise_error_syntax("unterminated quoted string");
  9963. if (varnest != 0) {
  9964. startlinno = plinno;
  9965. /* { */
  9966. raise_error_syntax("missing '}'");
  9967. }
  9968. USTPUTC('\0', out);
  9969. len = out - (char *)stackblock();
  9970. out = stackblock();
  9971. if (eofmark == NULL) {
  9972. if ((c == '>' || c == '<' USE_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  9973. && quotef == 0
  9974. ) {
  9975. if (isdigit_str9(out)) {
  9976. PARSEREDIR(); /* passed as params: out, c */
  9977. lasttoken = TREDIR;
  9978. return lasttoken;
  9979. }
  9980. /* else: non-number X seen, interpret it
  9981. * as "NNNX>file" = "NNNX >file" */
  9982. }
  9983. pungetc();
  9984. }
  9985. quoteflag = quotef;
  9986. backquotelist = bqlist;
  9987. grabstackblock(len);
  9988. wordtext = out;
  9989. lasttoken = TWORD;
  9990. return lasttoken;
  9991. /* end of readtoken routine */
  9992. /*
  9993. * Check to see whether we are at the end of the here document. When this
  9994. * is called, c is set to the first character of the next input line. If
  9995. * we are at the end of the here document, this routine sets the c to PEOF.
  9996. */
  9997. checkend: {
  9998. if (eofmark) {
  9999. #if ENABLE_ASH_ALIAS
  10000. if (c == PEOA) {
  10001. c = pgetc2();
  10002. }
  10003. #endif
  10004. if (striptabs) {
  10005. while (c == '\t') {
  10006. c = pgetc2();
  10007. }
  10008. }
  10009. if (c == *eofmark) {
  10010. if (pfgets(line, sizeof(line)) != NULL) {
  10011. char *p, *q;
  10012. p = line;
  10013. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10014. continue;
  10015. if (*p == '\n' && *q == '\0') {
  10016. c = PEOF;
  10017. plinno++;
  10018. needprompt = doprompt;
  10019. } else {
  10020. pushstring(line, NULL);
  10021. }
  10022. }
  10023. }
  10024. }
  10025. goto checkend_return;
  10026. }
  10027. /*
  10028. * Parse a redirection operator. The variable "out" points to a string
  10029. * specifying the fd to be redirected. The variable "c" contains the
  10030. * first character of the redirection operator.
  10031. */
  10032. parseredir: {
  10033. /* out is already checked to be a valid number or "" */
  10034. int fd = (*out == '\0' ? -1 : atoi(out));
  10035. union node *np;
  10036. np = stzalloc(sizeof(struct nfile));
  10037. if (c == '>') {
  10038. np->nfile.fd = 1;
  10039. c = pgetc();
  10040. if (c == '>')
  10041. np->type = NAPPEND;
  10042. else if (c == '|')
  10043. np->type = NCLOBBER;
  10044. else if (c == '&')
  10045. np->type = NTOFD;
  10046. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10047. else {
  10048. np->type = NTO;
  10049. pungetc();
  10050. }
  10051. }
  10052. #if ENABLE_ASH_BASH_COMPAT
  10053. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10054. np->nfile.fd = 1;
  10055. pgetc(); /* this is '>', no need to check */
  10056. np->type = NTO2;
  10057. }
  10058. #endif
  10059. else { /* c == '<' */
  10060. /*np->nfile.fd = 0; - stzalloc did it */
  10061. c = pgetc();
  10062. switch (c) {
  10063. case '<':
  10064. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10065. np = stzalloc(sizeof(struct nhere));
  10066. /*np->nfile.fd = 0; - stzalloc did it */
  10067. }
  10068. np->type = NHERE;
  10069. heredoc = stzalloc(sizeof(struct heredoc));
  10070. heredoc->here = np;
  10071. c = pgetc();
  10072. if (c == '-') {
  10073. heredoc->striptabs = 1;
  10074. } else {
  10075. /*heredoc->striptabs = 0; - stzalloc did it */
  10076. pungetc();
  10077. }
  10078. break;
  10079. case '&':
  10080. np->type = NFROMFD;
  10081. break;
  10082. case '>':
  10083. np->type = NFROMTO;
  10084. break;
  10085. default:
  10086. np->type = NFROM;
  10087. pungetc();
  10088. break;
  10089. }
  10090. }
  10091. if (fd >= 0)
  10092. np->nfile.fd = fd;
  10093. redirnode = np;
  10094. goto parseredir_return;
  10095. }
  10096. /*
  10097. * Parse a substitution. At this point, we have read the dollar sign
  10098. * and nothing else.
  10099. */
  10100. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10101. * (assuming ascii char codes, as the original implementation did) */
  10102. #define is_special(c) \
  10103. (((unsigned)(c) - 33 < 32) \
  10104. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10105. parsesub: {
  10106. int subtype;
  10107. int typeloc;
  10108. int flags;
  10109. char *p;
  10110. static const char types[] ALIGN1 = "}-+?=";
  10111. c = pgetc();
  10112. if (c <= PEOA_OR_PEOF
  10113. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10114. ) {
  10115. #if ENABLE_ASH_BASH_COMPAT
  10116. if (c == '\'')
  10117. bash_dollar_squote = 1;
  10118. else
  10119. #endif
  10120. USTPUTC('$', out);
  10121. pungetc();
  10122. } else if (c == '(') { /* $(command) or $((arith)) */
  10123. if (pgetc() == '(') {
  10124. #if ENABLE_ASH_MATH_SUPPORT
  10125. PARSEARITH();
  10126. #else
  10127. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10128. #endif
  10129. } else {
  10130. pungetc();
  10131. PARSEBACKQNEW();
  10132. }
  10133. } else {
  10134. USTPUTC(CTLVAR, out);
  10135. typeloc = out - (char *)stackblock();
  10136. USTPUTC(VSNORMAL, out);
  10137. subtype = VSNORMAL;
  10138. if (c == '{') {
  10139. c = pgetc();
  10140. if (c == '#') {
  10141. c = pgetc();
  10142. if (c == '}')
  10143. c = '#';
  10144. else
  10145. subtype = VSLENGTH;
  10146. } else
  10147. subtype = 0;
  10148. }
  10149. if (c > PEOA_OR_PEOF && is_name(c)) {
  10150. do {
  10151. STPUTC(c, out);
  10152. c = pgetc();
  10153. } while (c > PEOA_OR_PEOF && is_in_name(c));
  10154. } else if (isdigit(c)) {
  10155. do {
  10156. STPUTC(c, out);
  10157. c = pgetc();
  10158. } while (isdigit(c));
  10159. } else if (is_special(c)) {
  10160. USTPUTC(c, out);
  10161. c = pgetc();
  10162. } else {
  10163. badsub:
  10164. raise_error_syntax("bad substitution");
  10165. }
  10166. STPUTC('=', out);
  10167. flags = 0;
  10168. if (subtype == 0) {
  10169. switch (c) {
  10170. case ':':
  10171. c = pgetc();
  10172. #if ENABLE_ASH_BASH_COMPAT
  10173. if (c == ':' || c == '$' || isdigit(c)) {
  10174. pungetc();
  10175. subtype = VSSUBSTR;
  10176. break;
  10177. }
  10178. #endif
  10179. flags = VSNUL;
  10180. /*FALLTHROUGH*/
  10181. default:
  10182. p = strchr(types, c);
  10183. if (p == NULL)
  10184. goto badsub;
  10185. subtype = p - types + VSNORMAL;
  10186. break;
  10187. case '%':
  10188. case '#': {
  10189. int cc = c;
  10190. subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
  10191. c = pgetc();
  10192. if (c == cc)
  10193. subtype++;
  10194. else
  10195. pungetc();
  10196. break;
  10197. }
  10198. #if ENABLE_ASH_BASH_COMPAT
  10199. case '/':
  10200. subtype = VSREPLACE;
  10201. c = pgetc();
  10202. if (c == '/')
  10203. subtype++; /* VSREPLACEALL */
  10204. else
  10205. pungetc();
  10206. break;
  10207. #endif
  10208. }
  10209. } else {
  10210. pungetc();
  10211. }
  10212. if (dblquote || arinest)
  10213. flags |= VSQUOTE;
  10214. *((char *)stackblock() + typeloc) = subtype | flags;
  10215. if (subtype != VSNORMAL) {
  10216. varnest++;
  10217. if (dblquote || arinest) {
  10218. dqvarnest++;
  10219. }
  10220. }
  10221. }
  10222. goto parsesub_return;
  10223. }
  10224. /*
  10225. * Called to parse command substitutions. Newstyle is set if the command
  10226. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10227. * list of commands (passed by reference), and savelen is the number of
  10228. * characters on the top of the stack which must be preserved.
  10229. */
  10230. parsebackq: {
  10231. struct nodelist **nlpp;
  10232. smallint savepbq;
  10233. union node *n;
  10234. char *volatile str;
  10235. struct jmploc jmploc;
  10236. struct jmploc *volatile savehandler;
  10237. size_t savelen;
  10238. smallint saveprompt = 0;
  10239. #ifdef __GNUC__
  10240. (void) &saveprompt;
  10241. #endif
  10242. savepbq = parsebackquote;
  10243. if (setjmp(jmploc.loc)) {
  10244. free(str);
  10245. parsebackquote = 0;
  10246. exception_handler = savehandler;
  10247. longjmp(exception_handler->loc, 1);
  10248. }
  10249. INT_OFF;
  10250. str = NULL;
  10251. savelen = out - (char *)stackblock();
  10252. if (savelen > 0) {
  10253. str = ckmalloc(savelen);
  10254. memcpy(str, stackblock(), savelen);
  10255. }
  10256. savehandler = exception_handler;
  10257. exception_handler = &jmploc;
  10258. INT_ON;
  10259. if (oldstyle) {
  10260. /* We must read until the closing backquote, giving special
  10261. treatment to some slashes, and then push the string and
  10262. reread it as input, interpreting it normally. */
  10263. char *pout;
  10264. int pc;
  10265. size_t psavelen;
  10266. char *pstr;
  10267. STARTSTACKSTR(pout);
  10268. for (;;) {
  10269. if (needprompt) {
  10270. setprompt(2);
  10271. }
  10272. pc = pgetc();
  10273. switch (pc) {
  10274. case '`':
  10275. goto done;
  10276. case '\\':
  10277. pc = pgetc();
  10278. if (pc == '\n') {
  10279. plinno++;
  10280. if (doprompt)
  10281. setprompt(2);
  10282. /*
  10283. * If eating a newline, avoid putting
  10284. * the newline into the new character
  10285. * stream (via the STPUTC after the
  10286. * switch).
  10287. */
  10288. continue;
  10289. }
  10290. if (pc != '\\' && pc != '`' && pc != '$'
  10291. && (!dblquote || pc != '"'))
  10292. STPUTC('\\', pout);
  10293. if (pc > PEOA_OR_PEOF) {
  10294. break;
  10295. }
  10296. /* fall through */
  10297. case PEOF:
  10298. #if ENABLE_ASH_ALIAS
  10299. case PEOA:
  10300. #endif
  10301. startlinno = plinno;
  10302. raise_error_syntax("EOF in backquote substitution");
  10303. case '\n':
  10304. plinno++;
  10305. needprompt = doprompt;
  10306. break;
  10307. default:
  10308. break;
  10309. }
  10310. STPUTC(pc, pout);
  10311. }
  10312. done:
  10313. STPUTC('\0', pout);
  10314. psavelen = pout - (char *)stackblock();
  10315. if (psavelen > 0) {
  10316. pstr = grabstackstr(pout);
  10317. setinputstring(pstr);
  10318. }
  10319. }
  10320. nlpp = &bqlist;
  10321. while (*nlpp)
  10322. nlpp = &(*nlpp)->next;
  10323. *nlpp = stzalloc(sizeof(**nlpp));
  10324. /* (*nlpp)->next = NULL; - stzalloc did it */
  10325. parsebackquote = oldstyle;
  10326. if (oldstyle) {
  10327. saveprompt = doprompt;
  10328. doprompt = 0;
  10329. }
  10330. n = list(2);
  10331. if (oldstyle)
  10332. doprompt = saveprompt;
  10333. else if (readtoken() != TRP)
  10334. raise_error_unexpected_syntax(TRP);
  10335. (*nlpp)->n = n;
  10336. if (oldstyle) {
  10337. /*
  10338. * Start reading from old file again, ignoring any pushed back
  10339. * tokens left from the backquote parsing
  10340. */
  10341. popfile();
  10342. tokpushback = 0;
  10343. }
  10344. while (stackblocksize() <= savelen)
  10345. growstackblock();
  10346. STARTSTACKSTR(out);
  10347. if (str) {
  10348. memcpy(out, str, savelen);
  10349. STADJUST(savelen, out);
  10350. INT_OFF;
  10351. free(str);
  10352. str = NULL;
  10353. INT_ON;
  10354. }
  10355. parsebackquote = savepbq;
  10356. exception_handler = savehandler;
  10357. if (arinest || dblquote)
  10358. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10359. else
  10360. USTPUTC(CTLBACKQ, out);
  10361. if (oldstyle)
  10362. goto parsebackq_oldreturn;
  10363. goto parsebackq_newreturn;
  10364. }
  10365. #if ENABLE_ASH_MATH_SUPPORT
  10366. /*
  10367. * Parse an arithmetic expansion (indicate start of one and set state)
  10368. */
  10369. parsearith: {
  10370. if (++arinest == 1) {
  10371. prevsyntax = syntax;
  10372. syntax = ARISYNTAX;
  10373. USTPUTC(CTLARI, out);
  10374. if (dblquote)
  10375. USTPUTC('"', out);
  10376. else
  10377. USTPUTC(' ', out);
  10378. } else {
  10379. /*
  10380. * we collapse embedded arithmetic expansion to
  10381. * parenthesis, which should be equivalent
  10382. */
  10383. USTPUTC('(', out);
  10384. }
  10385. goto parsearith_return;
  10386. }
  10387. #endif
  10388. } /* end of readtoken */
  10389. /*
  10390. * Read the next input token.
  10391. * If the token is a word, we set backquotelist to the list of cmds in
  10392. * backquotes. We set quoteflag to true if any part of the word was
  10393. * quoted.
  10394. * If the token is TREDIR, then we set redirnode to a structure containing
  10395. * the redirection.
  10396. * In all cases, the variable startlinno is set to the number of the line
  10397. * on which the token starts.
  10398. *
  10399. * [Change comment: here documents and internal procedures]
  10400. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10401. * word parsing code into a separate routine. In this case, readtoken
  10402. * doesn't need to have any internal procedures, but parseword does.
  10403. * We could also make parseoperator in essence the main routine, and
  10404. * have parseword (readtoken1?) handle both words and redirection.]
  10405. */
  10406. #define NEW_xxreadtoken
  10407. #ifdef NEW_xxreadtoken
  10408. /* singles must be first! */
  10409. static const char xxreadtoken_chars[7] ALIGN1 = {
  10410. '\n', '(', ')', /* singles */
  10411. '&', '|', ';', /* doubles */
  10412. 0
  10413. };
  10414. #define xxreadtoken_singles 3
  10415. #define xxreadtoken_doubles 3
  10416. static const char xxreadtoken_tokens[] ALIGN1 = {
  10417. TNL, TLP, TRP, /* only single occurrence allowed */
  10418. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10419. TEOF, /* corresponds to trailing nul */
  10420. TAND, TOR, TENDCASE /* if double occurrence */
  10421. };
  10422. static int
  10423. xxreadtoken(void)
  10424. {
  10425. int c;
  10426. if (tokpushback) {
  10427. tokpushback = 0;
  10428. return lasttoken;
  10429. }
  10430. if (needprompt) {
  10431. setprompt(2);
  10432. }
  10433. startlinno = plinno;
  10434. for (;;) { /* until token or start of word found */
  10435. c = pgetc_fast();
  10436. if (c == ' ' || c == '\t' USE_ASH_ALIAS( || c == PEOA))
  10437. continue;
  10438. if (c == '#') {
  10439. while ((c = pgetc()) != '\n' && c != PEOF)
  10440. continue;
  10441. pungetc();
  10442. } else if (c == '\\') {
  10443. if (pgetc() != '\n') {
  10444. pungetc();
  10445. break; /* return readtoken1(...) */
  10446. }
  10447. startlinno = ++plinno;
  10448. if (doprompt)
  10449. setprompt(2);
  10450. } else {
  10451. const char *p;
  10452. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10453. if (c != PEOF) {
  10454. if (c == '\n') {
  10455. plinno++;
  10456. needprompt = doprompt;
  10457. }
  10458. p = strchr(xxreadtoken_chars, c);
  10459. if (p == NULL)
  10460. break; /* return readtoken1(...) */
  10461. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10462. int cc = pgetc();
  10463. if (cc == c) { /* double occurrence? */
  10464. p += xxreadtoken_doubles + 1;
  10465. } else {
  10466. pungetc();
  10467. #if ENABLE_ASH_BASH_COMPAT
  10468. if (c == '&' && cc == '>') /* &> */
  10469. break; /* return readtoken1(...) */
  10470. #endif
  10471. }
  10472. }
  10473. }
  10474. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10475. return lasttoken;
  10476. }
  10477. } /* for (;;) */
  10478. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10479. }
  10480. #else /* old xxreadtoken */
  10481. #define RETURN(token) return lasttoken = token
  10482. static int
  10483. xxreadtoken(void)
  10484. {
  10485. int c;
  10486. if (tokpushback) {
  10487. tokpushback = 0;
  10488. return lasttoken;
  10489. }
  10490. if (needprompt) {
  10491. setprompt(2);
  10492. }
  10493. startlinno = plinno;
  10494. for (;;) { /* until token or start of word found */
  10495. c = pgetc_fast();
  10496. switch (c) {
  10497. case ' ': case '\t':
  10498. #if ENABLE_ASH_ALIAS
  10499. case PEOA:
  10500. #endif
  10501. continue;
  10502. case '#':
  10503. while ((c = pgetc()) != '\n' && c != PEOF)
  10504. continue;
  10505. pungetc();
  10506. continue;
  10507. case '\\':
  10508. if (pgetc() == '\n') {
  10509. startlinno = ++plinno;
  10510. if (doprompt)
  10511. setprompt(2);
  10512. continue;
  10513. }
  10514. pungetc();
  10515. goto breakloop;
  10516. case '\n':
  10517. plinno++;
  10518. needprompt = doprompt;
  10519. RETURN(TNL);
  10520. case PEOF:
  10521. RETURN(TEOF);
  10522. case '&':
  10523. if (pgetc() == '&')
  10524. RETURN(TAND);
  10525. pungetc();
  10526. RETURN(TBACKGND);
  10527. case '|':
  10528. if (pgetc() == '|')
  10529. RETURN(TOR);
  10530. pungetc();
  10531. RETURN(TPIPE);
  10532. case ';':
  10533. if (pgetc() == ';')
  10534. RETURN(TENDCASE);
  10535. pungetc();
  10536. RETURN(TSEMI);
  10537. case '(':
  10538. RETURN(TLP);
  10539. case ')':
  10540. RETURN(TRP);
  10541. default:
  10542. goto breakloop;
  10543. }
  10544. }
  10545. breakloop:
  10546. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10547. #undef RETURN
  10548. }
  10549. #endif /* old xxreadtoken */
  10550. static int
  10551. readtoken(void)
  10552. {
  10553. int t;
  10554. #if DEBUG
  10555. smallint alreadyseen = tokpushback;
  10556. #endif
  10557. #if ENABLE_ASH_ALIAS
  10558. top:
  10559. #endif
  10560. t = xxreadtoken();
  10561. /*
  10562. * eat newlines
  10563. */
  10564. if (checkkwd & CHKNL) {
  10565. while (t == TNL) {
  10566. parseheredoc();
  10567. t = xxreadtoken();
  10568. }
  10569. }
  10570. if (t != TWORD || quoteflag) {
  10571. goto out;
  10572. }
  10573. /*
  10574. * check for keywords
  10575. */
  10576. if (checkkwd & CHKKWD) {
  10577. const char *const *pp;
  10578. pp = findkwd(wordtext);
  10579. if (pp) {
  10580. lasttoken = t = pp - tokname_array;
  10581. TRACE(("keyword %s recognized\n", tokname(t)));
  10582. goto out;
  10583. }
  10584. }
  10585. if (checkkwd & CHKALIAS) {
  10586. #if ENABLE_ASH_ALIAS
  10587. struct alias *ap;
  10588. ap = lookupalias(wordtext, 1);
  10589. if (ap != NULL) {
  10590. if (*ap->val) {
  10591. pushstring(ap->val, ap);
  10592. }
  10593. goto top;
  10594. }
  10595. #endif
  10596. }
  10597. out:
  10598. checkkwd = 0;
  10599. #if DEBUG
  10600. if (!alreadyseen)
  10601. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10602. else
  10603. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10604. #endif
  10605. return t;
  10606. }
  10607. static char
  10608. peektoken(void)
  10609. {
  10610. int t;
  10611. t = readtoken();
  10612. tokpushback = 1;
  10613. return tokname_array[t][0];
  10614. }
  10615. /*
  10616. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  10617. * valid parse tree indicating a blank line.)
  10618. */
  10619. static union node *
  10620. parsecmd(int interact)
  10621. {
  10622. int t;
  10623. tokpushback = 0;
  10624. doprompt = interact;
  10625. if (doprompt)
  10626. setprompt(doprompt);
  10627. needprompt = 0;
  10628. t = readtoken();
  10629. if (t == TEOF)
  10630. return NEOF;
  10631. if (t == TNL)
  10632. return NULL;
  10633. tokpushback = 1;
  10634. return list(1);
  10635. }
  10636. /*
  10637. * Input any here documents.
  10638. */
  10639. static void
  10640. parseheredoc(void)
  10641. {
  10642. struct heredoc *here;
  10643. union node *n;
  10644. here = heredoclist;
  10645. heredoclist = NULL;
  10646. while (here) {
  10647. if (needprompt) {
  10648. setprompt(2);
  10649. }
  10650. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  10651. here->eofmark, here->striptabs);
  10652. n = stzalloc(sizeof(struct narg));
  10653. n->narg.type = NARG;
  10654. /*n->narg.next = NULL; - stzalloc did it */
  10655. n->narg.text = wordtext;
  10656. n->narg.backquote = backquotelist;
  10657. here->here->nhere.doc = n;
  10658. here = here->next;
  10659. }
  10660. }
  10661. /*
  10662. * called by editline -- any expansions to the prompt should be added here.
  10663. */
  10664. #if ENABLE_ASH_EXPAND_PRMT
  10665. static const char *
  10666. expandstr(const char *ps)
  10667. {
  10668. union node n;
  10669. /* XXX Fix (char *) cast. */
  10670. setinputstring((char *)ps);
  10671. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  10672. popfile();
  10673. n.narg.type = NARG;
  10674. n.narg.next = NULL;
  10675. n.narg.text = wordtext;
  10676. n.narg.backquote = backquotelist;
  10677. expandarg(&n, NULL, 0);
  10678. return stackblock();
  10679. }
  10680. #endif
  10681. /*
  10682. * Execute a command or commands contained in a string.
  10683. */
  10684. static int
  10685. evalstring(char *s, int mask)
  10686. {
  10687. union node *n;
  10688. struct stackmark smark;
  10689. int skip;
  10690. setinputstring(s);
  10691. setstackmark(&smark);
  10692. skip = 0;
  10693. while ((n = parsecmd(0)) != NEOF) {
  10694. evaltree(n, 0);
  10695. popstackmark(&smark);
  10696. skip = evalskip;
  10697. if (skip)
  10698. break;
  10699. }
  10700. popfile();
  10701. skip &= mask;
  10702. evalskip = skip;
  10703. return skip;
  10704. }
  10705. /*
  10706. * The eval command.
  10707. */
  10708. static int
  10709. evalcmd(int argc UNUSED_PARAM, char **argv)
  10710. {
  10711. char *p;
  10712. char *concat;
  10713. if (argv[1]) {
  10714. p = argv[1];
  10715. argv += 2;
  10716. if (argv[0]) {
  10717. STARTSTACKSTR(concat);
  10718. for (;;) {
  10719. concat = stack_putstr(p, concat);
  10720. p = *argv++;
  10721. if (p == NULL)
  10722. break;
  10723. STPUTC(' ', concat);
  10724. }
  10725. STPUTC('\0', concat);
  10726. p = grabstackstr(concat);
  10727. }
  10728. evalstring(p, ~SKIPEVAL);
  10729. }
  10730. return exitstatus;
  10731. }
  10732. /*
  10733. * Read and execute commands. "Top" is nonzero for the top level command
  10734. * loop; it turns on prompting if the shell is interactive.
  10735. */
  10736. static int
  10737. cmdloop(int top)
  10738. {
  10739. union node *n;
  10740. struct stackmark smark;
  10741. int inter;
  10742. int numeof = 0;
  10743. TRACE(("cmdloop(%d) called\n", top));
  10744. for (;;) {
  10745. int skip;
  10746. setstackmark(&smark);
  10747. #if JOBS
  10748. if (doing_jobctl)
  10749. showjobs(stderr, SHOW_CHANGED);
  10750. #endif
  10751. inter = 0;
  10752. if (iflag && top) {
  10753. inter++;
  10754. #if ENABLE_ASH_MAIL
  10755. chkmail();
  10756. #endif
  10757. }
  10758. n = parsecmd(inter);
  10759. /* showtree(n); DEBUG */
  10760. if (n == NEOF) {
  10761. if (!top || numeof >= 50)
  10762. break;
  10763. if (!stoppedjobs()) {
  10764. if (!Iflag)
  10765. break;
  10766. out2str("\nUse \"exit\" to leave shell.\n");
  10767. }
  10768. numeof++;
  10769. } else if (nflag == 0) {
  10770. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  10771. job_warning >>= 1;
  10772. numeof = 0;
  10773. evaltree(n, 0);
  10774. }
  10775. popstackmark(&smark);
  10776. skip = evalskip;
  10777. if (skip) {
  10778. evalskip = 0;
  10779. return skip & SKIPEVAL;
  10780. }
  10781. }
  10782. return 0;
  10783. }
  10784. /*
  10785. * Take commands from a file. To be compatible we should do a path
  10786. * search for the file, which is necessary to find sub-commands.
  10787. */
  10788. static char *
  10789. find_dot_file(char *name)
  10790. {
  10791. char *fullname;
  10792. const char *path = pathval();
  10793. struct stat statb;
  10794. /* don't try this for absolute or relative paths */
  10795. if (strchr(name, '/'))
  10796. return name;
  10797. while ((fullname = padvance(&path, name)) != NULL) {
  10798. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  10799. /*
  10800. * Don't bother freeing here, since it will
  10801. * be freed by the caller.
  10802. */
  10803. return fullname;
  10804. }
  10805. stunalloc(fullname);
  10806. }
  10807. /* not found in the PATH */
  10808. ash_msg_and_raise_error("%s: not found", name);
  10809. /* NOTREACHED */
  10810. }
  10811. static int
  10812. dotcmd(int argc, char **argv)
  10813. {
  10814. struct strlist *sp;
  10815. volatile struct shparam saveparam;
  10816. int status = 0;
  10817. for (sp = cmdenviron; sp; sp = sp->next)
  10818. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  10819. if (argv[1]) { /* That's what SVR2 does */
  10820. char *fullname = find_dot_file(argv[1]);
  10821. argv += 2;
  10822. argc -= 2;
  10823. if (argc) { /* argc > 0, argv[0] != NULL */
  10824. saveparam = shellparam;
  10825. shellparam.malloced = 0;
  10826. shellparam.nparam = argc;
  10827. shellparam.p = argv;
  10828. };
  10829. setinputfile(fullname, INPUT_PUSH_FILE);
  10830. commandname = fullname;
  10831. cmdloop(0);
  10832. popfile();
  10833. if (argc) {
  10834. freeparam(&shellparam);
  10835. shellparam = saveparam;
  10836. };
  10837. status = exitstatus;
  10838. }
  10839. return status;
  10840. }
  10841. static int
  10842. exitcmd(int argc UNUSED_PARAM, char **argv)
  10843. {
  10844. if (stoppedjobs())
  10845. return 0;
  10846. if (argv[1])
  10847. exitstatus = number(argv[1]);
  10848. raise_exception(EXEXIT);
  10849. /* NOTREACHED */
  10850. }
  10851. /*
  10852. * Read a file containing shell functions.
  10853. */
  10854. static void
  10855. readcmdfile(char *name)
  10856. {
  10857. setinputfile(name, INPUT_PUSH_FILE);
  10858. cmdloop(0);
  10859. popfile();
  10860. }
  10861. /* ============ find_command inplementation */
  10862. /*
  10863. * Resolve a command name. If you change this routine, you may have to
  10864. * change the shellexec routine as well.
  10865. */
  10866. static void
  10867. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  10868. {
  10869. struct tblentry *cmdp;
  10870. int idx;
  10871. int prev;
  10872. char *fullname;
  10873. struct stat statb;
  10874. int e;
  10875. int updatetbl;
  10876. struct builtincmd *bcmd;
  10877. /* If name contains a slash, don't use PATH or hash table */
  10878. if (strchr(name, '/') != NULL) {
  10879. entry->u.index = -1;
  10880. if (act & DO_ABS) {
  10881. while (stat(name, &statb) < 0) {
  10882. #ifdef SYSV
  10883. if (errno == EINTR)
  10884. continue;
  10885. #endif
  10886. entry->cmdtype = CMDUNKNOWN;
  10887. return;
  10888. }
  10889. }
  10890. entry->cmdtype = CMDNORMAL;
  10891. return;
  10892. }
  10893. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  10894. updatetbl = (path == pathval());
  10895. if (!updatetbl) {
  10896. act |= DO_ALTPATH;
  10897. if (strstr(path, "%builtin") != NULL)
  10898. act |= DO_ALTBLTIN;
  10899. }
  10900. /* If name is in the table, check answer will be ok */
  10901. cmdp = cmdlookup(name, 0);
  10902. if (cmdp != NULL) {
  10903. int bit;
  10904. switch (cmdp->cmdtype) {
  10905. default:
  10906. #if DEBUG
  10907. abort();
  10908. #endif
  10909. case CMDNORMAL:
  10910. bit = DO_ALTPATH;
  10911. break;
  10912. case CMDFUNCTION:
  10913. bit = DO_NOFUNC;
  10914. break;
  10915. case CMDBUILTIN:
  10916. bit = DO_ALTBLTIN;
  10917. break;
  10918. }
  10919. if (act & bit) {
  10920. updatetbl = 0;
  10921. cmdp = NULL;
  10922. } else if (cmdp->rehash == 0)
  10923. /* if not invalidated by cd, we're done */
  10924. goto success;
  10925. }
  10926. /* If %builtin not in path, check for builtin next */
  10927. bcmd = find_builtin(name);
  10928. if (bcmd) {
  10929. if (IS_BUILTIN_REGULAR(bcmd))
  10930. goto builtin_success;
  10931. if (act & DO_ALTPATH) {
  10932. if (!(act & DO_ALTBLTIN))
  10933. goto builtin_success;
  10934. } else if (builtinloc <= 0) {
  10935. goto builtin_success;
  10936. }
  10937. }
  10938. #if ENABLE_FEATURE_SH_STANDALONE
  10939. {
  10940. int applet_no = find_applet_by_name(name);
  10941. if (applet_no >= 0) {
  10942. entry->cmdtype = CMDNORMAL;
  10943. entry->u.index = -2 - applet_no;
  10944. return;
  10945. }
  10946. }
  10947. #endif
  10948. /* We have to search path. */
  10949. prev = -1; /* where to start */
  10950. if (cmdp && cmdp->rehash) { /* doing a rehash */
  10951. if (cmdp->cmdtype == CMDBUILTIN)
  10952. prev = builtinloc;
  10953. else
  10954. prev = cmdp->param.index;
  10955. }
  10956. e = ENOENT;
  10957. idx = -1;
  10958. loop:
  10959. while ((fullname = padvance(&path, name)) != NULL) {
  10960. stunalloc(fullname);
  10961. /* NB: code below will still use fullname
  10962. * despite it being "unallocated" */
  10963. idx++;
  10964. if (pathopt) {
  10965. if (prefix(pathopt, "builtin")) {
  10966. if (bcmd)
  10967. goto builtin_success;
  10968. continue;
  10969. }
  10970. if ((act & DO_NOFUNC)
  10971. || !prefix(pathopt, "func")
  10972. ) { /* ignore unimplemented options */
  10973. continue;
  10974. }
  10975. }
  10976. /* if rehash, don't redo absolute path names */
  10977. if (fullname[0] == '/' && idx <= prev) {
  10978. if (idx < prev)
  10979. continue;
  10980. TRACE(("searchexec \"%s\": no change\n", name));
  10981. goto success;
  10982. }
  10983. while (stat(fullname, &statb) < 0) {
  10984. #ifdef SYSV
  10985. if (errno == EINTR)
  10986. continue;
  10987. #endif
  10988. if (errno != ENOENT && errno != ENOTDIR)
  10989. e = errno;
  10990. goto loop;
  10991. }
  10992. e = EACCES; /* if we fail, this will be the error */
  10993. if (!S_ISREG(statb.st_mode))
  10994. continue;
  10995. if (pathopt) { /* this is a %func directory */
  10996. stalloc(strlen(fullname) + 1);
  10997. /* NB: stalloc will return space pointed by fullname
  10998. * (because we don't have any intervening allocations
  10999. * between stunalloc above and this stalloc) */
  11000. readcmdfile(fullname);
  11001. cmdp = cmdlookup(name, 0);
  11002. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11003. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11004. stunalloc(fullname);
  11005. goto success;
  11006. }
  11007. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11008. if (!updatetbl) {
  11009. entry->cmdtype = CMDNORMAL;
  11010. entry->u.index = idx;
  11011. return;
  11012. }
  11013. INT_OFF;
  11014. cmdp = cmdlookup(name, 1);
  11015. cmdp->cmdtype = CMDNORMAL;
  11016. cmdp->param.index = idx;
  11017. INT_ON;
  11018. goto success;
  11019. }
  11020. /* We failed. If there was an entry for this command, delete it */
  11021. if (cmdp && updatetbl)
  11022. delete_cmd_entry();
  11023. if (act & DO_ERR)
  11024. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11025. entry->cmdtype = CMDUNKNOWN;
  11026. return;
  11027. builtin_success:
  11028. if (!updatetbl) {
  11029. entry->cmdtype = CMDBUILTIN;
  11030. entry->u.cmd = bcmd;
  11031. return;
  11032. }
  11033. INT_OFF;
  11034. cmdp = cmdlookup(name, 1);
  11035. cmdp->cmdtype = CMDBUILTIN;
  11036. cmdp->param.cmd = bcmd;
  11037. INT_ON;
  11038. success:
  11039. cmdp->rehash = 0;
  11040. entry->cmdtype = cmdp->cmdtype;
  11041. entry->u = cmdp->param;
  11042. }
  11043. /* ============ trap.c */
  11044. /*
  11045. * The trap builtin.
  11046. */
  11047. static int
  11048. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11049. {
  11050. char *action;
  11051. char **ap;
  11052. int signo;
  11053. nextopt(nullstr);
  11054. ap = argptr;
  11055. if (!*ap) {
  11056. for (signo = 0; signo < NSIG; signo++) {
  11057. if (trap[signo] != NULL) {
  11058. out1fmt("trap -- %s %s\n",
  11059. single_quote(trap[signo]),
  11060. get_signame(signo));
  11061. }
  11062. }
  11063. return 0;
  11064. }
  11065. action = NULL;
  11066. if (ap[1])
  11067. action = *ap++;
  11068. while (*ap) {
  11069. signo = get_signum(*ap);
  11070. if (signo < 0)
  11071. ash_msg_and_raise_error("%s: bad trap", *ap);
  11072. INT_OFF;
  11073. if (action) {
  11074. if (LONE_DASH(action))
  11075. action = NULL;
  11076. else
  11077. action = ckstrdup(action);
  11078. }
  11079. free(trap[signo]);
  11080. trap[signo] = action;
  11081. if (signo != 0)
  11082. setsignal(signo);
  11083. INT_ON;
  11084. ap++;
  11085. }
  11086. return 0;
  11087. }
  11088. /* ============ Builtins */
  11089. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11090. /*
  11091. * Lists available builtins
  11092. */
  11093. static int
  11094. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11095. {
  11096. unsigned col;
  11097. unsigned i;
  11098. out1fmt("\nBuilt-in commands:\n-------------------\n");
  11099. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11100. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11101. builtintab[i].name + 1);
  11102. if (col > 60) {
  11103. out1fmt("\n");
  11104. col = 0;
  11105. }
  11106. }
  11107. #if ENABLE_FEATURE_SH_STANDALONE
  11108. {
  11109. const char *a = applet_names;
  11110. while (*a) {
  11111. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11112. if (col > 60) {
  11113. out1fmt("\n");
  11114. col = 0;
  11115. }
  11116. a += strlen(a) + 1;
  11117. }
  11118. }
  11119. #endif
  11120. out1fmt("\n\n");
  11121. return EXIT_SUCCESS;
  11122. }
  11123. #endif /* FEATURE_SH_EXTRA_QUIET */
  11124. /*
  11125. * The export and readonly commands.
  11126. */
  11127. static int
  11128. exportcmd(int argc UNUSED_PARAM, char **argv)
  11129. {
  11130. struct var *vp;
  11131. char *name;
  11132. const char *p;
  11133. char **aptr;
  11134. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  11135. if (nextopt("p") != 'p') {
  11136. aptr = argptr;
  11137. name = *aptr;
  11138. if (name) {
  11139. do {
  11140. p = strchr(name, '=');
  11141. if (p != NULL) {
  11142. p++;
  11143. } else {
  11144. vp = *findvar(hashvar(name), name);
  11145. if (vp) {
  11146. vp->flags |= flag;
  11147. continue;
  11148. }
  11149. }
  11150. setvar(name, p, flag);
  11151. } while ((name = *++aptr) != NULL);
  11152. return 0;
  11153. }
  11154. }
  11155. showvars(argv[0], flag, 0);
  11156. return 0;
  11157. }
  11158. /*
  11159. * Delete a function if it exists.
  11160. */
  11161. static void
  11162. unsetfunc(const char *name)
  11163. {
  11164. struct tblentry *cmdp;
  11165. cmdp = cmdlookup(name, 0);
  11166. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  11167. delete_cmd_entry();
  11168. }
  11169. /*
  11170. * The unset builtin command. We unset the function before we unset the
  11171. * variable to allow a function to be unset when there is a readonly variable
  11172. * with the same name.
  11173. */
  11174. static int
  11175. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11176. {
  11177. char **ap;
  11178. int i;
  11179. int flag = 0;
  11180. int ret = 0;
  11181. while ((i = nextopt("vf")) != '\0') {
  11182. flag = i;
  11183. }
  11184. for (ap = argptr; *ap; ap++) {
  11185. if (flag != 'f') {
  11186. i = unsetvar(*ap);
  11187. ret |= i;
  11188. if (!(i & 2))
  11189. continue;
  11190. }
  11191. if (flag != 'v')
  11192. unsetfunc(*ap);
  11193. }
  11194. return ret & 1;
  11195. }
  11196. /* setmode.c */
  11197. #include <sys/times.h>
  11198. static const unsigned char timescmd_str[] ALIGN1 = {
  11199. ' ', offsetof(struct tms, tms_utime),
  11200. '\n', offsetof(struct tms, tms_stime),
  11201. ' ', offsetof(struct tms, tms_cutime),
  11202. '\n', offsetof(struct tms, tms_cstime),
  11203. 0
  11204. };
  11205. static int
  11206. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11207. {
  11208. long clk_tck, s, t;
  11209. const unsigned char *p;
  11210. struct tms buf;
  11211. clk_tck = sysconf(_SC_CLK_TCK);
  11212. times(&buf);
  11213. p = timescmd_str;
  11214. do {
  11215. t = *(clock_t *)(((char *) &buf) + p[1]);
  11216. s = t / clk_tck;
  11217. out1fmt("%ldm%ld.%.3lds%c",
  11218. s/60, s%60,
  11219. ((t - s * clk_tck) * 1000) / clk_tck,
  11220. p[0]);
  11221. } while (*(p += 2));
  11222. return 0;
  11223. }
  11224. #if ENABLE_ASH_MATH_SUPPORT
  11225. static arith_t
  11226. dash_arith(const char *s)
  11227. {
  11228. arith_t result;
  11229. int errcode = 0;
  11230. INT_OFF;
  11231. result = arith(s, &errcode);
  11232. if (errcode < 0) {
  11233. if (errcode == -3)
  11234. ash_msg_and_raise_error("exponent less than 0");
  11235. if (errcode == -2)
  11236. ash_msg_and_raise_error("divide by zero");
  11237. if (errcode == -5)
  11238. ash_msg_and_raise_error("expression recursion loop detected");
  11239. raise_error_syntax(s);
  11240. }
  11241. INT_ON;
  11242. return result;
  11243. }
  11244. /*
  11245. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  11246. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11247. *
  11248. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11249. */
  11250. static int
  11251. letcmd(int argc UNUSED_PARAM, char **argv)
  11252. {
  11253. arith_t i;
  11254. argv++;
  11255. if (!*argv)
  11256. ash_msg_and_raise_error("expression expected");
  11257. do {
  11258. i = dash_arith(*argv);
  11259. } while (*++argv);
  11260. return !i;
  11261. }
  11262. #endif /* ASH_MATH_SUPPORT */
  11263. /* ============ miscbltin.c
  11264. *
  11265. * Miscellaneous builtins.
  11266. */
  11267. #undef rflag
  11268. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11269. typedef enum __rlimit_resource rlim_t;
  11270. #endif
  11271. /*
  11272. * The read builtin. Options:
  11273. * -r Do not interpret '\' specially
  11274. * -s Turn off echo (tty only)
  11275. * -n NCHARS Read NCHARS max
  11276. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11277. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11278. * -u FD Read from given FD instead of fd 0
  11279. * This uses unbuffered input, which may be avoidable in some cases.
  11280. * TODO: bash also has:
  11281. * -a ARRAY Read into array[0],[1],etc
  11282. * -d DELIM End on DELIM char, not newline
  11283. * -e Use line editing (tty only)
  11284. */
  11285. static int
  11286. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11287. {
  11288. static const char *const arg_REPLY[] = { "REPLY", NULL };
  11289. char **ap;
  11290. int backslash;
  11291. char c;
  11292. int rflag;
  11293. char *prompt;
  11294. const char *ifs;
  11295. char *p;
  11296. int startword;
  11297. int status;
  11298. int i;
  11299. int fd = 0;
  11300. #if ENABLE_ASH_READ_NCHARS
  11301. int nchars = 0; /* if != 0, -n is in effect */
  11302. int silent = 0;
  11303. struct termios tty, old_tty;
  11304. #endif
  11305. #if ENABLE_ASH_READ_TIMEOUT
  11306. unsigned end_ms = 0;
  11307. unsigned timeout = 0;
  11308. #endif
  11309. rflag = 0;
  11310. prompt = NULL;
  11311. while ((i = nextopt("p:u:r"
  11312. USE_ASH_READ_TIMEOUT("t:")
  11313. USE_ASH_READ_NCHARS("n:s")
  11314. )) != '\0') {
  11315. switch (i) {
  11316. case 'p':
  11317. prompt = optionarg;
  11318. break;
  11319. #if ENABLE_ASH_READ_NCHARS
  11320. case 'n':
  11321. nchars = bb_strtou(optionarg, NULL, 10);
  11322. if (nchars < 0 || errno)
  11323. ash_msg_and_raise_error("invalid count");
  11324. /* nchars == 0: off (bash 3.2 does this too) */
  11325. break;
  11326. case 's':
  11327. silent = 1;
  11328. break;
  11329. #endif
  11330. #if ENABLE_ASH_READ_TIMEOUT
  11331. case 't':
  11332. timeout = bb_strtou(optionarg, NULL, 10);
  11333. if (errno || timeout > UINT_MAX / 2048)
  11334. ash_msg_and_raise_error("invalid timeout");
  11335. timeout *= 1000;
  11336. #if 0 /* even bash have no -t N.NNN support */
  11337. ts.tv_sec = bb_strtou(optionarg, &p, 10);
  11338. ts.tv_usec = 0;
  11339. /* EINVAL means number is ok, but not terminated by NUL */
  11340. if (*p == '.' && errno == EINVAL) {
  11341. char *p2;
  11342. if (*++p) {
  11343. int scale;
  11344. ts.tv_usec = bb_strtou(p, &p2, 10);
  11345. if (errno)
  11346. ash_msg_and_raise_error("invalid timeout");
  11347. scale = p2 - p;
  11348. /* normalize to usec */
  11349. if (scale > 6)
  11350. ash_msg_and_raise_error("invalid timeout");
  11351. while (scale++ < 6)
  11352. ts.tv_usec *= 10;
  11353. }
  11354. } else if (ts.tv_sec < 0 || errno) {
  11355. ash_msg_and_raise_error("invalid timeout");
  11356. }
  11357. if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
  11358. ash_msg_and_raise_error("invalid timeout");
  11359. }
  11360. #endif /* if 0 */
  11361. break;
  11362. #endif
  11363. case 'r':
  11364. rflag = 1;
  11365. break;
  11366. case 'u':
  11367. fd = bb_strtou(optionarg, NULL, 10);
  11368. if (fd < 0 || errno)
  11369. ash_msg_and_raise_error("invalid file descriptor");
  11370. break;
  11371. default:
  11372. break;
  11373. }
  11374. }
  11375. if (prompt && isatty(fd)) {
  11376. out2str(prompt);
  11377. }
  11378. ap = argptr;
  11379. if (*ap == NULL)
  11380. ap = (char**)arg_REPLY;
  11381. ifs = bltinlookup("IFS");
  11382. if (ifs == NULL)
  11383. ifs = defifs;
  11384. #if ENABLE_ASH_READ_NCHARS
  11385. tcgetattr(fd, &tty);
  11386. old_tty = tty;
  11387. if (nchars || silent) {
  11388. if (nchars) {
  11389. tty.c_lflag &= ~ICANON;
  11390. tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
  11391. }
  11392. if (silent) {
  11393. tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
  11394. }
  11395. /* if tcgetattr failed, tcsetattr will fail too.
  11396. * Ignoring, it's harmless. */
  11397. tcsetattr(fd, TCSANOW, &tty);
  11398. }
  11399. #endif
  11400. status = 0;
  11401. startword = 2;
  11402. backslash = 0;
  11403. #if ENABLE_ASH_READ_TIMEOUT
  11404. if (timeout) /* NB: ensuring end_ms is nonzero */
  11405. end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
  11406. #endif
  11407. STARTSTACKSTR(p);
  11408. do {
  11409. const char *is_ifs;
  11410. #if ENABLE_ASH_READ_TIMEOUT
  11411. if (end_ms) {
  11412. struct pollfd pfd[1];
  11413. pfd[0].fd = fd;
  11414. pfd[0].events = POLLIN;
  11415. timeout = end_ms - (unsigned)(monotonic_us() / 1000);
  11416. if ((int)timeout <= 0 /* already late? */
  11417. || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
  11418. ) { /* timed out! */
  11419. #if ENABLE_ASH_READ_NCHARS
  11420. tcsetattr(fd, TCSANOW, &old_tty);
  11421. #endif
  11422. return 1;
  11423. }
  11424. }
  11425. #endif
  11426. if (nonblock_safe_read(fd, &c, 1) != 1) {
  11427. status = 1;
  11428. break;
  11429. }
  11430. if (c == '\0')
  11431. continue;
  11432. if (backslash) {
  11433. backslash = 0;
  11434. if (c != '\n')
  11435. goto put;
  11436. continue;
  11437. }
  11438. if (!rflag && c == '\\') {
  11439. backslash = 1;
  11440. continue;
  11441. }
  11442. if (c == '\n')
  11443. break;
  11444. is_ifs = strchr(ifs, c);
  11445. if (startword && is_ifs) {
  11446. if (isspace(c))
  11447. continue;
  11448. /* non-space ifs char */
  11449. startword--;
  11450. if (startword == 1) /* first one? */
  11451. continue;
  11452. }
  11453. startword = 0;
  11454. if (ap[1] != NULL && is_ifs) {
  11455. const char *beg;
  11456. STACKSTRNUL(p);
  11457. beg = stackblock();
  11458. setvar(*ap, beg, 0);
  11459. ap++;
  11460. /* can we skip one non-space ifs? (2: yes) */
  11461. startword = isspace(c) ? 2 : 1;
  11462. STARTSTACKSTR(p);
  11463. continue;
  11464. }
  11465. put:
  11466. STPUTC(c, p);
  11467. }
  11468. /* end of do {} while: */
  11469. #if ENABLE_ASH_READ_NCHARS
  11470. while (--nchars);
  11471. #else
  11472. while (1);
  11473. #endif
  11474. #if ENABLE_ASH_READ_NCHARS
  11475. tcsetattr(fd, TCSANOW, &old_tty);
  11476. #endif
  11477. STACKSTRNUL(p);
  11478. /* Remove trailing space ifs chars */
  11479. while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
  11480. *p = '\0';
  11481. setvar(*ap, stackblock(), 0);
  11482. while (*++ap != NULL)
  11483. setvar(*ap, nullstr, 0);
  11484. return status;
  11485. }
  11486. static int
  11487. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11488. {
  11489. static const char permuser[3] ALIGN1 = "ugo";
  11490. static const char permmode[3] ALIGN1 = "rwx";
  11491. static const short permmask[] ALIGN2 = {
  11492. S_IRUSR, S_IWUSR, S_IXUSR,
  11493. S_IRGRP, S_IWGRP, S_IXGRP,
  11494. S_IROTH, S_IWOTH, S_IXOTH
  11495. };
  11496. char *ap;
  11497. mode_t mask;
  11498. int i;
  11499. int symbolic_mode = 0;
  11500. while (nextopt("S") != '\0') {
  11501. symbolic_mode = 1;
  11502. }
  11503. INT_OFF;
  11504. mask = umask(0);
  11505. umask(mask);
  11506. INT_ON;
  11507. ap = *argptr;
  11508. if (ap == NULL) {
  11509. if (symbolic_mode) {
  11510. char buf[18];
  11511. char *p = buf;
  11512. for (i = 0; i < 3; i++) {
  11513. int j;
  11514. *p++ = permuser[i];
  11515. *p++ = '=';
  11516. for (j = 0; j < 3; j++) {
  11517. if ((mask & permmask[3 * i + j]) == 0) {
  11518. *p++ = permmode[j];
  11519. }
  11520. }
  11521. *p++ = ',';
  11522. }
  11523. *--p = 0;
  11524. puts(buf);
  11525. } else {
  11526. out1fmt("%.4o\n", mask);
  11527. }
  11528. } else {
  11529. if (isdigit((unsigned char) *ap)) {
  11530. mask = 0;
  11531. do {
  11532. if (*ap >= '8' || *ap < '0')
  11533. ash_msg_and_raise_error(illnum, argv[1]);
  11534. mask = (mask << 3) + (*ap - '0');
  11535. } while (*++ap != '\0');
  11536. umask(mask);
  11537. } else {
  11538. mask = ~mask & 0777;
  11539. if (!bb_parse_mode(ap, &mask)) {
  11540. ash_msg_and_raise_error("illegal mode: %s", ap);
  11541. }
  11542. umask(~mask & 0777);
  11543. }
  11544. }
  11545. return 0;
  11546. }
  11547. /*
  11548. * ulimit builtin
  11549. *
  11550. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11551. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11552. * ash by J.T. Conklin.
  11553. *
  11554. * Public domain.
  11555. */
  11556. struct limits {
  11557. uint8_t cmd; /* RLIMIT_xxx fit into it */
  11558. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  11559. char option;
  11560. };
  11561. static const struct limits limits_tbl[] = {
  11562. #ifdef RLIMIT_CPU
  11563. { RLIMIT_CPU, 0, 't' },
  11564. #endif
  11565. #ifdef RLIMIT_FSIZE
  11566. { RLIMIT_FSIZE, 9, 'f' },
  11567. #endif
  11568. #ifdef RLIMIT_DATA
  11569. { RLIMIT_DATA, 10, 'd' },
  11570. #endif
  11571. #ifdef RLIMIT_STACK
  11572. { RLIMIT_STACK, 10, 's' },
  11573. #endif
  11574. #ifdef RLIMIT_CORE
  11575. { RLIMIT_CORE, 9, 'c' },
  11576. #endif
  11577. #ifdef RLIMIT_RSS
  11578. { RLIMIT_RSS, 10, 'm' },
  11579. #endif
  11580. #ifdef RLIMIT_MEMLOCK
  11581. { RLIMIT_MEMLOCK, 10, 'l' },
  11582. #endif
  11583. #ifdef RLIMIT_NPROC
  11584. { RLIMIT_NPROC, 0, 'p' },
  11585. #endif
  11586. #ifdef RLIMIT_NOFILE
  11587. { RLIMIT_NOFILE, 0, 'n' },
  11588. #endif
  11589. #ifdef RLIMIT_AS
  11590. { RLIMIT_AS, 10, 'v' },
  11591. #endif
  11592. #ifdef RLIMIT_LOCKS
  11593. { RLIMIT_LOCKS, 0, 'w' },
  11594. #endif
  11595. };
  11596. static const char limits_name[] =
  11597. #ifdef RLIMIT_CPU
  11598. "time(seconds)" "\0"
  11599. #endif
  11600. #ifdef RLIMIT_FSIZE
  11601. "file(blocks)" "\0"
  11602. #endif
  11603. #ifdef RLIMIT_DATA
  11604. "data(kb)" "\0"
  11605. #endif
  11606. #ifdef RLIMIT_STACK
  11607. "stack(kb)" "\0"
  11608. #endif
  11609. #ifdef RLIMIT_CORE
  11610. "coredump(blocks)" "\0"
  11611. #endif
  11612. #ifdef RLIMIT_RSS
  11613. "memory(kb)" "\0"
  11614. #endif
  11615. #ifdef RLIMIT_MEMLOCK
  11616. "locked memory(kb)" "\0"
  11617. #endif
  11618. #ifdef RLIMIT_NPROC
  11619. "process" "\0"
  11620. #endif
  11621. #ifdef RLIMIT_NOFILE
  11622. "nofiles" "\0"
  11623. #endif
  11624. #ifdef RLIMIT_AS
  11625. "vmemory(kb)" "\0"
  11626. #endif
  11627. #ifdef RLIMIT_LOCKS
  11628. "locks" "\0"
  11629. #endif
  11630. ;
  11631. enum limtype { SOFT = 0x1, HARD = 0x2 };
  11632. static void
  11633. printlim(enum limtype how, const struct rlimit *limit,
  11634. const struct limits *l)
  11635. {
  11636. rlim_t val;
  11637. val = limit->rlim_max;
  11638. if (how & SOFT)
  11639. val = limit->rlim_cur;
  11640. if (val == RLIM_INFINITY)
  11641. out1fmt("unlimited\n");
  11642. else {
  11643. val >>= l->factor_shift;
  11644. out1fmt("%lld\n", (long long) val);
  11645. }
  11646. }
  11647. static int
  11648. ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11649. {
  11650. int c;
  11651. rlim_t val = 0;
  11652. enum limtype how = SOFT | HARD;
  11653. const struct limits *l;
  11654. int set, all = 0;
  11655. int optc, what;
  11656. struct rlimit limit;
  11657. what = 'f';
  11658. while ((optc = nextopt("HSa"
  11659. #ifdef RLIMIT_CPU
  11660. "t"
  11661. #endif
  11662. #ifdef RLIMIT_FSIZE
  11663. "f"
  11664. #endif
  11665. #ifdef RLIMIT_DATA
  11666. "d"
  11667. #endif
  11668. #ifdef RLIMIT_STACK
  11669. "s"
  11670. #endif
  11671. #ifdef RLIMIT_CORE
  11672. "c"
  11673. #endif
  11674. #ifdef RLIMIT_RSS
  11675. "m"
  11676. #endif
  11677. #ifdef RLIMIT_MEMLOCK
  11678. "l"
  11679. #endif
  11680. #ifdef RLIMIT_NPROC
  11681. "p"
  11682. #endif
  11683. #ifdef RLIMIT_NOFILE
  11684. "n"
  11685. #endif
  11686. #ifdef RLIMIT_AS
  11687. "v"
  11688. #endif
  11689. #ifdef RLIMIT_LOCKS
  11690. "w"
  11691. #endif
  11692. )) != '\0')
  11693. switch (optc) {
  11694. case 'H':
  11695. how = HARD;
  11696. break;
  11697. case 'S':
  11698. how = SOFT;
  11699. break;
  11700. case 'a':
  11701. all = 1;
  11702. break;
  11703. default:
  11704. what = optc;
  11705. }
  11706. for (l = limits_tbl; l->option != what; l++)
  11707. continue;
  11708. set = *argptr ? 1 : 0;
  11709. if (set) {
  11710. char *p = *argptr;
  11711. if (all || argptr[1])
  11712. ash_msg_and_raise_error("too many arguments");
  11713. if (strncmp(p, "unlimited\n", 9) == 0)
  11714. val = RLIM_INFINITY;
  11715. else {
  11716. val = (rlim_t) 0;
  11717. while ((c = *p++) >= '0' && c <= '9') {
  11718. val = (val * 10) + (long)(c - '0');
  11719. // val is actually 'unsigned long int' and can't get < 0
  11720. if (val < (rlim_t) 0)
  11721. break;
  11722. }
  11723. if (c)
  11724. ash_msg_and_raise_error("bad number");
  11725. val <<= l->factor_shift;
  11726. }
  11727. }
  11728. if (all) {
  11729. const char *lname = limits_name;
  11730. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  11731. getrlimit(l->cmd, &limit);
  11732. out1fmt("%-20s ", lname);
  11733. lname += strlen(lname) + 1;
  11734. printlim(how, &limit, l);
  11735. }
  11736. return 0;
  11737. }
  11738. getrlimit(l->cmd, &limit);
  11739. if (set) {
  11740. if (how & HARD)
  11741. limit.rlim_max = val;
  11742. if (how & SOFT)
  11743. limit.rlim_cur = val;
  11744. if (setrlimit(l->cmd, &limit) < 0)
  11745. ash_msg_and_raise_error("error setting limit (%m)");
  11746. } else {
  11747. printlim(how, &limit, l);
  11748. }
  11749. return 0;
  11750. }
  11751. /* ============ Math support */
  11752. #if ENABLE_ASH_MATH_SUPPORT
  11753. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  11754. Permission is hereby granted, free of charge, to any person obtaining
  11755. a copy of this software and associated documentation files (the
  11756. "Software"), to deal in the Software without restriction, including
  11757. without limitation the rights to use, copy, modify, merge, publish,
  11758. distribute, sublicense, and/or sell copies of the Software, and to
  11759. permit persons to whom the Software is furnished to do so, subject to
  11760. the following conditions:
  11761. The above copyright notice and this permission notice shall be
  11762. included in all copies or substantial portions of the Software.
  11763. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  11764. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11765. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  11766. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  11767. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  11768. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  11769. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11770. */
  11771. /* This is my infix parser/evaluator. It is optimized for size, intended
  11772. * as a replacement for yacc-based parsers. However, it may well be faster
  11773. * than a comparable parser written in yacc. The supported operators are
  11774. * listed in #defines below. Parens, order of operations, and error handling
  11775. * are supported. This code is thread safe. The exact expression format should
  11776. * be that which POSIX specifies for shells. */
  11777. /* The code uses a simple two-stack algorithm. See
  11778. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  11779. * for a detailed explanation of the infix-to-postfix algorithm on which
  11780. * this is based (this code differs in that it applies operators immediately
  11781. * to the stack instead of adding them to a queue to end up with an
  11782. * expression). */
  11783. /* To use the routine, call it with an expression string and error return
  11784. * pointer */
  11785. /*
  11786. * Aug 24, 2001 Manuel Novoa III
  11787. *
  11788. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  11789. *
  11790. * 1) In arith_apply():
  11791. * a) Cached values of *numptr and &(numptr[-1]).
  11792. * b) Removed redundant test for zero denominator.
  11793. *
  11794. * 2) In arith():
  11795. * a) Eliminated redundant code for processing operator tokens by moving
  11796. * to a table-based implementation. Also folded handling of parens
  11797. * into the table.
  11798. * b) Combined all 3 loops which called arith_apply to reduce generated
  11799. * code size at the cost of speed.
  11800. *
  11801. * 3) The following expressions were treated as valid by the original code:
  11802. * 1() , 0! , 1 ( *3 ) .
  11803. * These bugs have been fixed by internally enclosing the expression in
  11804. * parens and then checking that all binary ops and right parens are
  11805. * preceded by a valid expression (NUM_TOKEN).
  11806. *
  11807. * Note: It may be desirable to replace Aaron's test for whitespace with
  11808. * ctype's isspace() if it is used by another busybox applet or if additional
  11809. * whitespace chars should be considered. Look below the "#include"s for a
  11810. * precompiler test.
  11811. */
  11812. /*
  11813. * Aug 26, 2001 Manuel Novoa III
  11814. *
  11815. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  11816. *
  11817. * Merge in Aaron's comments previously posted to the busybox list,
  11818. * modified slightly to take account of my changes to the code.
  11819. *
  11820. */
  11821. /*
  11822. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11823. *
  11824. * - allow access to variable,
  11825. * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
  11826. * - realize assign syntax (VAR=expr, +=, *= etc)
  11827. * - realize exponentiation (** operator)
  11828. * - realize comma separated - expr, expr
  11829. * - realise ++expr --expr expr++ expr--
  11830. * - realise expr ? expr : expr (but, second expr calculate always)
  11831. * - allow hexadecimal and octal numbers
  11832. * - was restored loses XOR operator
  11833. * - remove one goto label, added three ;-)
  11834. * - protect $((num num)) as true zero expr (Manuel`s error)
  11835. * - always use special isspace(), see comment from bash ;-)
  11836. */
  11837. #define arith_isspace(arithval) \
  11838. (arithval == ' ' || arithval == '\n' || arithval == '\t')
  11839. typedef unsigned char operator;
  11840. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  11841. * precedence, and 3 high bits are an ID unique across operators of that
  11842. * precedence. The ID portion is so that multiple operators can have the
  11843. * same precedence, ensuring that the leftmost one is evaluated first.
  11844. * Consider * and /. */
  11845. #define tok_decl(prec,id) (((id)<<5)|(prec))
  11846. #define PREC(op) ((op) & 0x1F)
  11847. #define TOK_LPAREN tok_decl(0,0)
  11848. #define TOK_COMMA tok_decl(1,0)
  11849. #define TOK_ASSIGN tok_decl(2,0)
  11850. #define TOK_AND_ASSIGN tok_decl(2,1)
  11851. #define TOK_OR_ASSIGN tok_decl(2,2)
  11852. #define TOK_XOR_ASSIGN tok_decl(2,3)
  11853. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  11854. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  11855. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  11856. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  11857. #define TOK_MUL_ASSIGN tok_decl(3,0)
  11858. #define TOK_DIV_ASSIGN tok_decl(3,1)
  11859. #define TOK_REM_ASSIGN tok_decl(3,2)
  11860. /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
  11861. #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
  11862. /* conditional is right associativity too */
  11863. #define TOK_CONDITIONAL tok_decl(4,0)
  11864. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  11865. #define TOK_OR tok_decl(5,0)
  11866. #define TOK_AND tok_decl(6,0)
  11867. #define TOK_BOR tok_decl(7,0)
  11868. #define TOK_BXOR tok_decl(8,0)
  11869. #define TOK_BAND tok_decl(9,0)
  11870. #define TOK_EQ tok_decl(10,0)
  11871. #define TOK_NE tok_decl(10,1)
  11872. #define TOK_LT tok_decl(11,0)
  11873. #define TOK_GT tok_decl(11,1)
  11874. #define TOK_GE tok_decl(11,2)
  11875. #define TOK_LE tok_decl(11,3)
  11876. #define TOK_LSHIFT tok_decl(12,0)
  11877. #define TOK_RSHIFT tok_decl(12,1)
  11878. #define TOK_ADD tok_decl(13,0)
  11879. #define TOK_SUB tok_decl(13,1)
  11880. #define TOK_MUL tok_decl(14,0)
  11881. #define TOK_DIV tok_decl(14,1)
  11882. #define TOK_REM tok_decl(14,2)
  11883. /* exponent is right associativity */
  11884. #define TOK_EXPONENT tok_decl(15,1)
  11885. /* For now unary operators. */
  11886. #define UNARYPREC 16
  11887. #define TOK_BNOT tok_decl(UNARYPREC,0)
  11888. #define TOK_NOT tok_decl(UNARYPREC,1)
  11889. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  11890. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  11891. #define PREC_PRE (UNARYPREC+2)
  11892. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  11893. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  11894. #define PREC_POST (UNARYPREC+3)
  11895. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  11896. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  11897. #define SPEC_PREC (UNARYPREC+4)
  11898. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  11899. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  11900. #define NUMPTR (*numstackptr)
  11901. static int
  11902. tok_have_assign(operator op)
  11903. {
  11904. operator prec = PREC(op);
  11905. convert_prec_is_assing(prec);
  11906. return (prec == PREC(TOK_ASSIGN) ||
  11907. prec == PREC_PRE || prec == PREC_POST);
  11908. }
  11909. static int
  11910. is_right_associativity(operator prec)
  11911. {
  11912. return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
  11913. || prec == PREC(TOK_CONDITIONAL));
  11914. }
  11915. typedef struct {
  11916. arith_t val;
  11917. arith_t contidional_second_val;
  11918. char contidional_second_val_initialized;
  11919. char *var; /* if NULL then is regular number,
  11920. else is variable name */
  11921. } v_n_t;
  11922. typedef struct chk_var_recursive_looped_t {
  11923. const char *var;
  11924. struct chk_var_recursive_looped_t *next;
  11925. } chk_var_recursive_looped_t;
  11926. static chk_var_recursive_looped_t *prev_chk_var_recursive;
  11927. static int
  11928. arith_lookup_val(v_n_t *t)
  11929. {
  11930. if (t->var) {
  11931. const char * p = lookupvar(t->var);
  11932. if (p) {
  11933. int errcode;
  11934. /* recursive try as expression */
  11935. chk_var_recursive_looped_t *cur;
  11936. chk_var_recursive_looped_t cur_save;
  11937. for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
  11938. if (strcmp(cur->var, t->var) == 0) {
  11939. /* expression recursion loop detected */
  11940. return -5;
  11941. }
  11942. }
  11943. /* save current lookuped var name */
  11944. cur = prev_chk_var_recursive;
  11945. cur_save.var = t->var;
  11946. cur_save.next = cur;
  11947. prev_chk_var_recursive = &cur_save;
  11948. t->val = arith (p, &errcode);
  11949. /* restore previous ptr after recursiving */
  11950. prev_chk_var_recursive = cur;
  11951. return errcode;
  11952. }
  11953. /* allow undefined var as 0 */
  11954. t->val = 0;
  11955. }
  11956. return 0;
  11957. }
  11958. /* "applying" a token means performing it on the top elements on the integer
  11959. * stack. For a unary operator it will only change the top element, but a
  11960. * binary operator will pop two arguments and push a result */
  11961. static int
  11962. arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
  11963. {
  11964. v_n_t *numptr_m1;
  11965. arith_t numptr_val, rez;
  11966. int ret_arith_lookup_val;
  11967. /* There is no operator that can work without arguments */
  11968. if (NUMPTR == numstack) goto err;
  11969. numptr_m1 = NUMPTR - 1;
  11970. /* check operand is var with noninteger value */
  11971. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11972. if (ret_arith_lookup_val)
  11973. return ret_arith_lookup_val;
  11974. rez = numptr_m1->val;
  11975. if (op == TOK_UMINUS)
  11976. rez *= -1;
  11977. else if (op == TOK_NOT)
  11978. rez = !rez;
  11979. else if (op == TOK_BNOT)
  11980. rez = ~rez;
  11981. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  11982. rez++;
  11983. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  11984. rez--;
  11985. else if (op != TOK_UPLUS) {
  11986. /* Binary operators */
  11987. /* check and binary operators need two arguments */
  11988. if (numptr_m1 == numstack) goto err;
  11989. /* ... and they pop one */
  11990. --NUMPTR;
  11991. numptr_val = rez;
  11992. if (op == TOK_CONDITIONAL) {
  11993. if (!numptr_m1->contidional_second_val_initialized) {
  11994. /* protect $((expr1 ? expr2)) without ": expr" */
  11995. goto err;
  11996. }
  11997. rez = numptr_m1->contidional_second_val;
  11998. } else if (numptr_m1->contidional_second_val_initialized) {
  11999. /* protect $((expr1 : expr2)) without "expr ? " */
  12000. goto err;
  12001. }
  12002. numptr_m1 = NUMPTR - 1;
  12003. if (op != TOK_ASSIGN) {
  12004. /* check operand is var with noninteger value for not '=' */
  12005. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  12006. if (ret_arith_lookup_val)
  12007. return ret_arith_lookup_val;
  12008. }
  12009. if (op == TOK_CONDITIONAL) {
  12010. numptr_m1->contidional_second_val = rez;
  12011. }
  12012. rez = numptr_m1->val;
  12013. if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  12014. rez |= numptr_val;
  12015. else if (op == TOK_OR)
  12016. rez = numptr_val || rez;
  12017. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  12018. rez &= numptr_val;
  12019. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  12020. rez ^= numptr_val;
  12021. else if (op == TOK_AND)
  12022. rez = rez && numptr_val;
  12023. else if (op == TOK_EQ)
  12024. rez = (rez == numptr_val);
  12025. else if (op == TOK_NE)
  12026. rez = (rez != numptr_val);
  12027. else if (op == TOK_GE)
  12028. rez = (rez >= numptr_val);
  12029. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  12030. rez >>= numptr_val;
  12031. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  12032. rez <<= numptr_val;
  12033. else if (op == TOK_GT)
  12034. rez = (rez > numptr_val);
  12035. else if (op == TOK_LT)
  12036. rez = (rez < numptr_val);
  12037. else if (op == TOK_LE)
  12038. rez = (rez <= numptr_val);
  12039. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  12040. rez *= numptr_val;
  12041. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  12042. rez += numptr_val;
  12043. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  12044. rez -= numptr_val;
  12045. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  12046. rez = numptr_val;
  12047. else if (op == TOK_CONDITIONAL_SEP) {
  12048. if (numptr_m1 == numstack) {
  12049. /* protect $((expr : expr)) without "expr ? " */
  12050. goto err;
  12051. }
  12052. numptr_m1->contidional_second_val_initialized = op;
  12053. numptr_m1->contidional_second_val = numptr_val;
  12054. } else if (op == TOK_CONDITIONAL) {
  12055. rez = rez ?
  12056. numptr_val : numptr_m1->contidional_second_val;
  12057. } else if (op == TOK_EXPONENT) {
  12058. if (numptr_val < 0)
  12059. return -3; /* exponent less than 0 */
  12060. else {
  12061. arith_t c = 1;
  12062. if (numptr_val)
  12063. while (numptr_val--)
  12064. c *= rez;
  12065. rez = c;
  12066. }
  12067. } else if (numptr_val==0) /* zero divisor check */
  12068. return -2;
  12069. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  12070. rez /= numptr_val;
  12071. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  12072. rez %= numptr_val;
  12073. }
  12074. if (tok_have_assign(op)) {
  12075. char buf[sizeof(arith_t_type)*3 + 2];
  12076. if (numptr_m1->var == NULL) {
  12077. /* Hmm, 1=2 ? */
  12078. goto err;
  12079. }
  12080. /* save to shell variable */
  12081. #if ENABLE_ASH_MATH_SUPPORT_64
  12082. snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
  12083. #else
  12084. snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
  12085. #endif
  12086. setvar(numptr_m1->var, buf, 0);
  12087. /* after saving, make previous value for v++ or v-- */
  12088. if (op == TOK_POST_INC)
  12089. rez--;
  12090. else if (op == TOK_POST_DEC)
  12091. rez++;
  12092. }
  12093. numptr_m1->val = rez;
  12094. /* protect geting var value, is number now */
  12095. numptr_m1->var = NULL;
  12096. return 0;
  12097. err:
  12098. return -1;
  12099. }
  12100. /* longest must be first */
  12101. static const char op_tokens[] ALIGN1 = {
  12102. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  12103. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  12104. '<','<', 0, TOK_LSHIFT,
  12105. '>','>', 0, TOK_RSHIFT,
  12106. '|','|', 0, TOK_OR,
  12107. '&','&', 0, TOK_AND,
  12108. '!','=', 0, TOK_NE,
  12109. '<','=', 0, TOK_LE,
  12110. '>','=', 0, TOK_GE,
  12111. '=','=', 0, TOK_EQ,
  12112. '|','=', 0, TOK_OR_ASSIGN,
  12113. '&','=', 0, TOK_AND_ASSIGN,
  12114. '*','=', 0, TOK_MUL_ASSIGN,
  12115. '/','=', 0, TOK_DIV_ASSIGN,
  12116. '%','=', 0, TOK_REM_ASSIGN,
  12117. '+','=', 0, TOK_PLUS_ASSIGN,
  12118. '-','=', 0, TOK_MINUS_ASSIGN,
  12119. '-','-', 0, TOK_POST_DEC,
  12120. '^','=', 0, TOK_XOR_ASSIGN,
  12121. '+','+', 0, TOK_POST_INC,
  12122. '*','*', 0, TOK_EXPONENT,
  12123. '!', 0, TOK_NOT,
  12124. '<', 0, TOK_LT,
  12125. '>', 0, TOK_GT,
  12126. '=', 0, TOK_ASSIGN,
  12127. '|', 0, TOK_BOR,
  12128. '&', 0, TOK_BAND,
  12129. '*', 0, TOK_MUL,
  12130. '/', 0, TOK_DIV,
  12131. '%', 0, TOK_REM,
  12132. '+', 0, TOK_ADD,
  12133. '-', 0, TOK_SUB,
  12134. '^', 0, TOK_BXOR,
  12135. /* uniq */
  12136. '~', 0, TOK_BNOT,
  12137. ',', 0, TOK_COMMA,
  12138. '?', 0, TOK_CONDITIONAL,
  12139. ':', 0, TOK_CONDITIONAL_SEP,
  12140. ')', 0, TOK_RPAREN,
  12141. '(', 0, TOK_LPAREN,
  12142. 0
  12143. };
  12144. /* ptr to ")" */
  12145. #define endexpression (&op_tokens[sizeof(op_tokens)-7])
  12146. static arith_t
  12147. arith(const char *expr, int *perrcode)
  12148. {
  12149. char arithval; /* Current character under analysis */
  12150. operator lasttok, op;
  12151. operator prec;
  12152. operator *stack, *stackptr;
  12153. const char *p = endexpression;
  12154. int errcode;
  12155. v_n_t *numstack, *numstackptr;
  12156. unsigned datasizes = strlen(expr) + 2;
  12157. /* Stack of integers */
  12158. /* The proof that there can be no more than strlen(startbuf)/2+1 integers
  12159. * in any given correct or incorrect expression is left as an exercise to
  12160. * the reader. */
  12161. numstackptr = numstack = alloca((datasizes / 2) * sizeof(numstack[0]));
  12162. /* Stack of operator tokens */
  12163. stackptr = stack = alloca(datasizes * sizeof(stack[0]));
  12164. *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
  12165. *perrcode = errcode = 0;
  12166. while (1) {
  12167. arithval = *expr;
  12168. if (arithval == 0) {
  12169. if (p == endexpression) {
  12170. /* Null expression. */
  12171. return 0;
  12172. }
  12173. /* This is only reached after all tokens have been extracted from the
  12174. * input stream. If there are still tokens on the operator stack, they
  12175. * are to be applied in order. At the end, there should be a final
  12176. * result on the integer stack */
  12177. if (expr != endexpression + 1) {
  12178. /* If we haven't done so already, */
  12179. /* append a closing right paren */
  12180. expr = endexpression;
  12181. /* and let the loop process it. */
  12182. continue;
  12183. }
  12184. /* At this point, we're done with the expression. */
  12185. if (numstackptr != numstack+1) {
  12186. /* ... but if there isn't, it's bad */
  12187. err:
  12188. *perrcode = -1;
  12189. return *perrcode;
  12190. }
  12191. if (numstack->var) {
  12192. /* expression is $((var)) only, lookup now */
  12193. errcode = arith_lookup_val(numstack);
  12194. }
  12195. ret:
  12196. *perrcode = errcode;
  12197. return numstack->val;
  12198. }
  12199. /* Continue processing the expression. */
  12200. if (arith_isspace(arithval)) {
  12201. /* Skip whitespace */
  12202. goto prologue;
  12203. }
  12204. p = endofname(expr);
  12205. if (p != expr) {
  12206. size_t var_name_size = (p-expr) + 1; /* trailing zero */
  12207. numstackptr->var = alloca(var_name_size);
  12208. safe_strncpy(numstackptr->var, expr, var_name_size);
  12209. expr = p;
  12210. num:
  12211. numstackptr->contidional_second_val_initialized = 0;
  12212. numstackptr++;
  12213. lasttok = TOK_NUM;
  12214. continue;
  12215. }
  12216. if (isdigit(arithval)) {
  12217. numstackptr->var = NULL;
  12218. #if ENABLE_ASH_MATH_SUPPORT_64
  12219. numstackptr->val = strtoll(expr, (char **) &expr, 0);
  12220. #else
  12221. numstackptr->val = strtol(expr, (char **) &expr, 0);
  12222. #endif
  12223. goto num;
  12224. }
  12225. for (p = op_tokens; ; p++) {
  12226. const char *o;
  12227. if (*p == 0) {
  12228. /* strange operator not found */
  12229. goto err;
  12230. }
  12231. for (o = expr; *p && *o == *p; p++)
  12232. o++;
  12233. if (!*p) {
  12234. /* found */
  12235. expr = o - 1;
  12236. break;
  12237. }
  12238. /* skip tail uncompared token */
  12239. while (*p)
  12240. p++;
  12241. /* skip zero delim */
  12242. p++;
  12243. }
  12244. op = p[1];
  12245. /* post grammar: a++ reduce to num */
  12246. if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  12247. lasttok = TOK_NUM;
  12248. /* Plus and minus are binary (not unary) _only_ if the last
  12249. * token was as number, or a right paren (which pretends to be
  12250. * a number, since it evaluates to one). Think about it.
  12251. * It makes sense. */
  12252. if (lasttok != TOK_NUM) {
  12253. switch (op) {
  12254. case TOK_ADD:
  12255. op = TOK_UPLUS;
  12256. break;
  12257. case TOK_SUB:
  12258. op = TOK_UMINUS;
  12259. break;
  12260. case TOK_POST_INC:
  12261. op = TOK_PRE_INC;
  12262. break;
  12263. case TOK_POST_DEC:
  12264. op = TOK_PRE_DEC;
  12265. break;
  12266. }
  12267. }
  12268. /* We don't want a unary operator to cause recursive descent on the
  12269. * stack, because there can be many in a row and it could cause an
  12270. * operator to be evaluated before its argument is pushed onto the
  12271. * integer stack. */
  12272. /* But for binary operators, "apply" everything on the operator
  12273. * stack until we find an operator with a lesser priority than the
  12274. * one we have just extracted. */
  12275. /* Left paren is given the lowest priority so it will never be
  12276. * "applied" in this way.
  12277. * if associativity is right and priority eq, applied also skip
  12278. */
  12279. prec = PREC(op);
  12280. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  12281. /* not left paren or unary */
  12282. if (lasttok != TOK_NUM) {
  12283. /* binary op must be preceded by a num */
  12284. goto err;
  12285. }
  12286. while (stackptr != stack) {
  12287. if (op == TOK_RPAREN) {
  12288. /* The algorithm employed here is simple: while we don't
  12289. * hit an open paren nor the bottom of the stack, pop
  12290. * tokens and apply them */
  12291. if (stackptr[-1] == TOK_LPAREN) {
  12292. --stackptr;
  12293. /* Any operator directly after a */
  12294. lasttok = TOK_NUM;
  12295. /* close paren should consider itself binary */
  12296. goto prologue;
  12297. }
  12298. } else {
  12299. operator prev_prec = PREC(stackptr[-1]);
  12300. convert_prec_is_assing(prec);
  12301. convert_prec_is_assing(prev_prec);
  12302. if (prev_prec < prec)
  12303. break;
  12304. /* check right assoc */
  12305. if (prev_prec == prec && is_right_associativity(prec))
  12306. break;
  12307. }
  12308. errcode = arith_apply(*--stackptr, numstack, &numstackptr);
  12309. if (errcode) goto ret;
  12310. }
  12311. if (op == TOK_RPAREN) {
  12312. goto err;
  12313. }
  12314. }
  12315. /* Push this operator to the stack and remember it. */
  12316. *stackptr++ = lasttok = op;
  12317. prologue:
  12318. ++expr;
  12319. } /* while */
  12320. }
  12321. #endif /* ASH_MATH_SUPPORT */
  12322. /* ============ main() and helpers */
  12323. /*
  12324. * Called to exit the shell.
  12325. */
  12326. static void exitshell(void) NORETURN;
  12327. static void
  12328. exitshell(void)
  12329. {
  12330. struct jmploc loc;
  12331. char *p;
  12332. int status;
  12333. status = exitstatus;
  12334. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12335. if (setjmp(loc.loc)) {
  12336. if (exception == EXEXIT)
  12337. /* dash bug: it just does _exit(exitstatus) here
  12338. * but we have to do setjobctl(0) first!
  12339. * (bug is still not fixed in dash-0.5.3 - if you run dash
  12340. * under Midnight Commander, on exit from dash MC is backgrounded) */
  12341. status = exitstatus;
  12342. goto out;
  12343. }
  12344. exception_handler = &loc;
  12345. p = trap[0];
  12346. if (p) {
  12347. trap[0] = NULL;
  12348. evalstring(p, 0);
  12349. }
  12350. flush_stdout_stderr();
  12351. out:
  12352. setjobctl(0);
  12353. _exit(status);
  12354. /* NOTREACHED */
  12355. }
  12356. static void
  12357. init(void)
  12358. {
  12359. /* from input.c: */
  12360. basepf.nextc = basepf.buf = basebuf;
  12361. /* from trap.c: */
  12362. signal(SIGCHLD, SIG_DFL);
  12363. /* from var.c: */
  12364. {
  12365. char **envp;
  12366. char ppid[sizeof(int)*3 + 1];
  12367. const char *p;
  12368. struct stat st1, st2;
  12369. initvar();
  12370. for (envp = environ; envp && *envp; envp++) {
  12371. if (strchr(*envp, '=')) {
  12372. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12373. }
  12374. }
  12375. snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
  12376. setvar("PPID", ppid, 0);
  12377. p = lookupvar("PWD");
  12378. if (p)
  12379. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  12380. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  12381. p = '\0';
  12382. setpwd(p, 0);
  12383. }
  12384. }
  12385. /*
  12386. * Process the shell command line arguments.
  12387. */
  12388. static void
  12389. procargs(char **argv)
  12390. {
  12391. int i;
  12392. const char *xminusc;
  12393. char **xargv;
  12394. xargv = argv;
  12395. arg0 = xargv[0];
  12396. /* if (xargv[0]) - mmm, this is always true! */
  12397. xargv++;
  12398. for (i = 0; i < NOPTS; i++)
  12399. optlist[i] = 2;
  12400. argptr = xargv;
  12401. if (options(1)) {
  12402. /* it already printed err message */
  12403. raise_exception(EXERROR);
  12404. }
  12405. xargv = argptr;
  12406. xminusc = minusc;
  12407. if (*xargv == NULL) {
  12408. if (xminusc)
  12409. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12410. sflag = 1;
  12411. }
  12412. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12413. iflag = 1;
  12414. if (mflag == 2)
  12415. mflag = iflag;
  12416. for (i = 0; i < NOPTS; i++)
  12417. if (optlist[i] == 2)
  12418. optlist[i] = 0;
  12419. #if DEBUG == 2
  12420. debug = 1;
  12421. #endif
  12422. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  12423. if (xminusc) {
  12424. minusc = *xargv++;
  12425. if (*xargv)
  12426. goto setarg0;
  12427. } else if (!sflag) {
  12428. setinputfile(*xargv, 0);
  12429. setarg0:
  12430. arg0 = *xargv++;
  12431. commandname = arg0;
  12432. }
  12433. shellparam.p = xargv;
  12434. #if ENABLE_ASH_GETOPTS
  12435. shellparam.optind = 1;
  12436. shellparam.optoff = -1;
  12437. #endif
  12438. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12439. while (*xargv) {
  12440. shellparam.nparam++;
  12441. xargv++;
  12442. }
  12443. optschanged();
  12444. }
  12445. /*
  12446. * Read /etc/profile or .profile.
  12447. */
  12448. static void
  12449. read_profile(const char *name)
  12450. {
  12451. int skip;
  12452. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12453. return;
  12454. skip = cmdloop(0);
  12455. popfile();
  12456. if (skip)
  12457. exitshell();
  12458. }
  12459. /*
  12460. * This routine is called when an error or an interrupt occurs in an
  12461. * interactive shell and control is returned to the main command loop.
  12462. */
  12463. static void
  12464. reset(void)
  12465. {
  12466. /* from eval.c: */
  12467. evalskip = 0;
  12468. loopnest = 0;
  12469. /* from input.c: */
  12470. parselleft = parsenleft = 0; /* clear input buffer */
  12471. popallfiles();
  12472. /* from parser.c: */
  12473. tokpushback = 0;
  12474. checkkwd = 0;
  12475. /* from redir.c: */
  12476. clearredir(/*drop:*/ 0);
  12477. }
  12478. #if PROFILE
  12479. static short profile_buf[16384];
  12480. extern int etext();
  12481. #endif
  12482. /*
  12483. * Main routine. We initialize things, parse the arguments, execute
  12484. * profiles if we're a login shell, and then call cmdloop to execute
  12485. * commands. The setjmp call sets up the location to jump to when an
  12486. * exception occurs. When an exception occurs the variable "state"
  12487. * is used to figure out how far we had gotten.
  12488. */
  12489. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12490. int ash_main(int argc UNUSED_PARAM, char **argv)
  12491. {
  12492. char *shinit;
  12493. volatile int state;
  12494. struct jmploc jmploc;
  12495. struct stackmark smark;
  12496. /* Initialize global data */
  12497. INIT_G_misc();
  12498. INIT_G_memstack();
  12499. INIT_G_var();
  12500. #if ENABLE_ASH_ALIAS
  12501. INIT_G_alias();
  12502. #endif
  12503. INIT_G_cmdtable();
  12504. #if PROFILE
  12505. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12506. #endif
  12507. #if ENABLE_FEATURE_EDITING
  12508. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12509. #endif
  12510. state = 0;
  12511. if (setjmp(jmploc.loc)) {
  12512. int e;
  12513. int s;
  12514. reset();
  12515. e = exception;
  12516. if (e == EXERROR)
  12517. exitstatus = 2;
  12518. s = state;
  12519. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  12520. exitshell();
  12521. if (e == EXINT) {
  12522. outcslow('\n', stderr);
  12523. }
  12524. popstackmark(&smark);
  12525. FORCE_INT_ON; /* enable interrupts */
  12526. if (s == 1)
  12527. goto state1;
  12528. if (s == 2)
  12529. goto state2;
  12530. if (s == 3)
  12531. goto state3;
  12532. goto state4;
  12533. }
  12534. exception_handler = &jmploc;
  12535. #if DEBUG
  12536. opentrace();
  12537. TRACE(("Shell args: "));
  12538. trace_puts_args(argv);
  12539. #endif
  12540. rootpid = getpid();
  12541. #if ENABLE_ASH_RANDOM_SUPPORT
  12542. /* Can use monotonic_ns() for better randomness but for now it is
  12543. * not used anywhere else in busybox... so avoid bloat */
  12544. random_galois_LFSR = random_LCG = rootpid + monotonic_us();
  12545. #endif
  12546. init();
  12547. setstackmark(&smark);
  12548. procargs(argv);
  12549. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12550. if (iflag) {
  12551. const char *hp = lookupvar("HISTFILE");
  12552. if (hp == NULL) {
  12553. hp = lookupvar("HOME");
  12554. if (hp != NULL) {
  12555. char *defhp = concat_path_file(hp, ".ash_history");
  12556. setvar("HISTFILE", defhp, 0);
  12557. free(defhp);
  12558. }
  12559. }
  12560. }
  12561. #endif
  12562. if (argv[0] && argv[0][0] == '-')
  12563. isloginsh = 1;
  12564. if (isloginsh) {
  12565. state = 1;
  12566. read_profile("/etc/profile");
  12567. state1:
  12568. state = 2;
  12569. read_profile(".profile");
  12570. }
  12571. state2:
  12572. state = 3;
  12573. if (
  12574. #ifndef linux
  12575. getuid() == geteuid() && getgid() == getegid() &&
  12576. #endif
  12577. iflag
  12578. ) {
  12579. shinit = lookupvar("ENV");
  12580. if (shinit != NULL && *shinit != '\0') {
  12581. read_profile(shinit);
  12582. }
  12583. }
  12584. state3:
  12585. state = 4;
  12586. if (minusc) {
  12587. /* evalstring pushes parsefile stack.
  12588. * Ensure we don't falsely claim that 0 (stdin)
  12589. * is one of stacked source fds */
  12590. if (!sflag)
  12591. g_parsefile->fd = -1;
  12592. evalstring(minusc, 0);
  12593. }
  12594. if (sflag || minusc == NULL) {
  12595. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12596. if (iflag) {
  12597. const char *hp = lookupvar("HISTFILE");
  12598. if (hp != NULL)
  12599. line_input_state->hist_file = hp;
  12600. }
  12601. #endif
  12602. state4: /* XXX ??? - why isn't this before the "if" statement */
  12603. cmdloop(1);
  12604. }
  12605. #if PROFILE
  12606. monitor(0);
  12607. #endif
  12608. #ifdef GPROF
  12609. {
  12610. extern void _mcleanup(void);
  12611. _mcleanup();
  12612. }
  12613. #endif
  12614. exitshell();
  12615. /* NOTREACHED */
  12616. }
  12617. /*-
  12618. * Copyright (c) 1989, 1991, 1993, 1994
  12619. * The Regents of the University of California. All rights reserved.
  12620. *
  12621. * This code is derived from software contributed to Berkeley by
  12622. * Kenneth Almquist.
  12623. *
  12624. * Redistribution and use in source and binary forms, with or without
  12625. * modification, are permitted provided that the following conditions
  12626. * are met:
  12627. * 1. Redistributions of source code must retain the above copyright
  12628. * notice, this list of conditions and the following disclaimer.
  12629. * 2. Redistributions in binary form must reproduce the above copyright
  12630. * notice, this list of conditions and the following disclaimer in the
  12631. * documentation and/or other materials provided with the distribution.
  12632. * 3. Neither the name of the University nor the names of its contributors
  12633. * may be used to endorse or promote products derived from this software
  12634. * without specific prior written permission.
  12635. *
  12636. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12637. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12638. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12639. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12640. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12641. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12642. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12643. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12644. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12645. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12646. * SUCH DAMAGE.
  12647. */