ash.c 281 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * Copyright (c) 1989, 1991, 1993, 1994
  6. * The Regents of the University of California. All rights reserved.
  7. *
  8. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  9. * was re-ported from NetBSD and debianized.
  10. *
  11. *
  12. * This code is derived from software contributed to Berkeley by
  13. * Kenneth Almquist.
  14. *
  15. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  16. *
  17. * Original BSD copyright notice is retained at the end of this file.
  18. */
  19. /*
  20. * rewrite arith.y to micro stack based cryptic algorithm by
  21. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  22. *
  23. * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
  24. * dynamic variables.
  25. *
  26. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
  27. * used in busybox and size optimizations,
  28. * rewrote arith (see notes to this), added locale support,
  29. * rewrote dynamic variables.
  30. *
  31. */
  32. /*
  33. * The follow should be set to reflect the type of system you have:
  34. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  35. * define SYSV if you are running under System V.
  36. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  37. * define DEBUG=2 to compile in and turn on debugging.
  38. *
  39. * When debugging is on, debugging info will be written to ./trace and
  40. * a quit signal will generate a core dump.
  41. */
  42. #define DEBUG 0
  43. #define IFS_BROKEN
  44. #define PROFILE 0
  45. #include "busybox.h"
  46. #if DEBUG
  47. #define _GNU_SOURCE
  48. #endif
  49. #include <sys/types.h>
  50. #include <sys/ioctl.h>
  51. #include <sys/param.h>
  52. #include <sys/resource.h>
  53. #include <sys/stat.h>
  54. #include <sys/wait.h>
  55. #include <stdio.h>
  56. #include <stdlib.h>
  57. #include <string.h>
  58. #include <unistd.h>
  59. #include <stdarg.h>
  60. #include <stddef.h>
  61. #include <assert.h>
  62. #include <ctype.h>
  63. #include <dirent.h>
  64. #include <errno.h>
  65. #include <fcntl.h>
  66. #include <limits.h>
  67. #include <paths.h>
  68. #include <setjmp.h>
  69. #include <signal.h>
  70. /*#include <stdint.h>*/
  71. #include <time.h>
  72. #include <fnmatch.h>
  73. #ifdef CONFIG_ASH_JOB_CONTROL
  74. #define JOBS 1
  75. #else
  76. #define JOBS 0
  77. #endif
  78. #if JOBS || defined(CONFIG_ASH_READ_NCHARS)
  79. #include <termios.h>
  80. #endif
  81. #include "cmdedit.h"
  82. #ifdef __GLIBC__
  83. /* glibc sucks */
  84. static int *dash_errno;
  85. #undef errno
  86. #define errno (*dash_errno)
  87. #endif
  88. #if defined(__uClinux__)
  89. #error "Do not even bother, ash will not run on uClinux"
  90. #endif
  91. #if DEBUG
  92. #define _DIAGASSERT(assert_expr) assert(assert_expr)
  93. #else
  94. #define _DIAGASSERT(assert_expr)
  95. #endif
  96. #ifdef CONFIG_ASH_ALIAS
  97. /* alias.h */
  98. #define ALIASINUSE 1
  99. #define ALIASDEAD 2
  100. struct alias {
  101. struct alias *next;
  102. char *name;
  103. char *val;
  104. int flag;
  105. };
  106. static struct alias *lookupalias(const char *, int);
  107. static int aliascmd(int, char **);
  108. static int unaliascmd(int, char **);
  109. static void rmaliases(void);
  110. static int unalias(const char *);
  111. static void printalias(const struct alias *);
  112. #endif
  113. /* cd.h */
  114. static void setpwd(const char *, int);
  115. /* error.h */
  116. /*
  117. * Types of operations (passed to the errmsg routine).
  118. */
  119. static const char not_found_msg[] = "%s: not found";
  120. #define E_OPEN "No such file" /* opening a file */
  121. #define E_CREAT "Directory nonexistent" /* creating a file */
  122. #define E_EXEC not_found_msg+4 /* executing a program */
  123. /*
  124. * We enclose jmp_buf in a structure so that we can declare pointers to
  125. * jump locations. The global variable handler contains the location to
  126. * jump to when an exception occurs, and the global variable exception
  127. * contains a code identifying the exception. To implement nested
  128. * exception handlers, the user should save the value of handler on entry
  129. * to an inner scope, set handler to point to a jmploc structure for the
  130. * inner scope, and restore handler on exit from the scope.
  131. */
  132. struct jmploc {
  133. jmp_buf loc;
  134. };
  135. static struct jmploc *handler;
  136. static int exception;
  137. static volatile int suppressint;
  138. static volatile sig_atomic_t intpending;
  139. /* exceptions */
  140. #define EXINT 0 /* SIGINT received */
  141. #define EXERROR 1 /* a generic error */
  142. #define EXSHELLPROC 2 /* execute a shell procedure */
  143. #define EXEXEC 3 /* command execution failed */
  144. #define EXEXIT 4 /* exit the shell */
  145. #define EXSIG 5 /* trapped signal in wait(1) */
  146. /* do we generate EXSIG events */
  147. static int exsig;
  148. /* last pending signal */
  149. static volatile sig_atomic_t pendingsigs;
  150. /*
  151. * These macros allow the user to suspend the handling of interrupt signals
  152. * over a period of time. This is similar to SIGHOLD to or sigblock, but
  153. * much more efficient and portable. (But hacking the kernel is so much
  154. * more fun than worrying about efficiency and portability. :-))
  155. */
  156. #define xbarrier() ({ __asm__ __volatile__ ("": : :"memory"); })
  157. #define INTOFF \
  158. ({ \
  159. suppressint++; \
  160. xbarrier(); \
  161. 0; \
  162. })
  163. #define SAVEINT(v) ((v) = suppressint)
  164. #define RESTOREINT(v) \
  165. ({ \
  166. xbarrier(); \
  167. if ((suppressint = (v)) == 0 && intpending) onint(); \
  168. 0; \
  169. })
  170. #define EXSIGON() \
  171. ({ \
  172. exsig++; \
  173. xbarrier(); \
  174. if (pendingsigs) \
  175. exraise(EXSIG); \
  176. 0; \
  177. })
  178. /* EXSIG is turned off by evalbltin(). */
  179. static void exraise(int) ATTRIBUTE_NORETURN;
  180. static void onint(void) ATTRIBUTE_NORETURN;
  181. static void sh_error(const char *, ...) ATTRIBUTE_NORETURN;
  182. static void exerror(int, const char *, ...) ATTRIBUTE_NORETURN;
  183. static void sh_warnx(const char *, ...);
  184. #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
  185. static void
  186. inton(void) {
  187. if (--suppressint == 0 && intpending) {
  188. onint();
  189. }
  190. }
  191. #define INTON inton()
  192. static void forceinton(void)
  193. {
  194. suppressint = 0;
  195. if (intpending)
  196. onint();
  197. }
  198. #define FORCEINTON forceinton()
  199. #else
  200. #define INTON \
  201. ({ \
  202. xbarrier(); \
  203. if (--suppressint == 0 && intpending) onint(); \
  204. 0; \
  205. })
  206. #define FORCEINTON \
  207. ({ \
  208. xbarrier(); \
  209. suppressint = 0; \
  210. if (intpending) onint(); \
  211. 0; \
  212. })
  213. #endif /* CONFIG_ASH_OPTIMIZE_FOR_SIZE */
  214. /* expand.h */
  215. struct strlist {
  216. struct strlist *next;
  217. char *text;
  218. };
  219. struct arglist {
  220. struct strlist *list;
  221. struct strlist **lastp;
  222. };
  223. /*
  224. * expandarg() flags
  225. */
  226. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  227. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  228. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  229. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  230. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  231. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  232. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  233. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  234. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  235. union node;
  236. static void expandarg(union node *, struct arglist *, int);
  237. #define rmescapes(p) _rmescapes((p), 0)
  238. static char *_rmescapes(char *, int);
  239. static int casematch(union node *, char *);
  240. #ifdef CONFIG_ASH_MATH_SUPPORT
  241. static void expari(int);
  242. #endif
  243. /* eval.h */
  244. static char *commandname; /* currently executing command */
  245. static struct strlist *cmdenviron; /* environment for builtin command */
  246. static int exitstatus; /* exit status of last command */
  247. static int back_exitstatus; /* exit status of backquoted command */
  248. struct backcmd { /* result of evalbackcmd */
  249. int fd; /* file descriptor to read from */
  250. char *buf; /* buffer */
  251. int nleft; /* number of chars in buffer */
  252. struct job *jp; /* job structure for command */
  253. };
  254. /*
  255. * This file was generated by the mknodes program.
  256. */
  257. #define NCMD 0
  258. #define NPIPE 1
  259. #define NREDIR 2
  260. #define NBACKGND 3
  261. #define NSUBSHELL 4
  262. #define NAND 5
  263. #define NOR 6
  264. #define NSEMI 7
  265. #define NIF 8
  266. #define NWHILE 9
  267. #define NUNTIL 10
  268. #define NFOR 11
  269. #define NCASE 12
  270. #define NCLIST 13
  271. #define NDEFUN 14
  272. #define NARG 15
  273. #define NTO 16
  274. #define NCLOBBER 17
  275. #define NFROM 18
  276. #define NFROMTO 19
  277. #define NAPPEND 20
  278. #define NTOFD 21
  279. #define NFROMFD 22
  280. #define NHERE 23
  281. #define NXHERE 24
  282. #define NNOT 25
  283. struct ncmd {
  284. int type;
  285. union node *assign;
  286. union node *args;
  287. union node *redirect;
  288. };
  289. struct npipe {
  290. int type;
  291. int backgnd;
  292. struct nodelist *cmdlist;
  293. };
  294. struct nredir {
  295. int type;
  296. union node *n;
  297. union node *redirect;
  298. };
  299. struct nbinary {
  300. int type;
  301. union node *ch1;
  302. union node *ch2;
  303. };
  304. struct nif {
  305. int type;
  306. union node *test;
  307. union node *ifpart;
  308. union node *elsepart;
  309. };
  310. struct nfor {
  311. int type;
  312. union node *args;
  313. union node *body;
  314. char *var;
  315. };
  316. struct ncase {
  317. int type;
  318. union node *expr;
  319. union node *cases;
  320. };
  321. struct nclist {
  322. int type;
  323. union node *next;
  324. union node *pattern;
  325. union node *body;
  326. };
  327. struct narg {
  328. int type;
  329. union node *next;
  330. char *text;
  331. struct nodelist *backquote;
  332. };
  333. struct nfile {
  334. int type;
  335. union node *next;
  336. int fd;
  337. union node *fname;
  338. char *expfname;
  339. };
  340. struct ndup {
  341. int type;
  342. union node *next;
  343. int fd;
  344. int dupfd;
  345. union node *vname;
  346. };
  347. struct nhere {
  348. int type;
  349. union node *next;
  350. int fd;
  351. union node *doc;
  352. };
  353. struct nnot {
  354. int type;
  355. union node *com;
  356. };
  357. union node {
  358. int type;
  359. struct ncmd ncmd;
  360. struct npipe npipe;
  361. struct nredir nredir;
  362. struct nbinary nbinary;
  363. struct nif nif;
  364. struct nfor nfor;
  365. struct ncase ncase;
  366. struct nclist nclist;
  367. struct narg narg;
  368. struct nfile nfile;
  369. struct ndup ndup;
  370. struct nhere nhere;
  371. struct nnot nnot;
  372. };
  373. struct nodelist {
  374. struct nodelist *next;
  375. union node *n;
  376. };
  377. struct funcnode {
  378. int count;
  379. union node n;
  380. };
  381. static void freefunc(struct funcnode *);
  382. /* parser.h */
  383. /* control characters in argument strings */
  384. #define CTL_FIRST '\201' /* first 'special' character */
  385. #define CTLESC '\201' /* escape next character */
  386. #define CTLVAR '\202' /* variable defn */
  387. #define CTLENDVAR '\203'
  388. #define CTLBACKQ '\204'
  389. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  390. /* CTLBACKQ | CTLQUOTE == '\205' */
  391. #define CTLARI '\206' /* arithmetic expression */
  392. #define CTLENDARI '\207'
  393. #define CTLQUOTEMARK '\210'
  394. #define CTL_LAST '\210' /* last 'special' character */
  395. /* variable substitution byte (follows CTLVAR) */
  396. #define VSTYPE 0x0f /* type of variable substitution */
  397. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  398. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  399. /* values of VSTYPE field */
  400. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  401. #define VSMINUS 0x2 /* ${var-text} */
  402. #define VSPLUS 0x3 /* ${var+text} */
  403. #define VSQUESTION 0x4 /* ${var?message} */
  404. #define VSASSIGN 0x5 /* ${var=text} */
  405. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  406. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  407. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  408. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  409. #define VSLENGTH 0xa /* ${#var} */
  410. /* values of checkkwd variable */
  411. #define CHKALIAS 0x1
  412. #define CHKKWD 0x2
  413. #define CHKNL 0x4
  414. #define IBUFSIZ (BUFSIZ + 1)
  415. /*
  416. * NEOF is returned by parsecmd when it encounters an end of file. It
  417. * must be distinct from NULL, so we use the address of a variable that
  418. * happens to be handy.
  419. */
  420. static int plinno = 1; /* input line number */
  421. /* number of characters left in input buffer */
  422. static int parsenleft; /* copy of parsefile->nleft */
  423. static int parselleft; /* copy of parsefile->lleft */
  424. /* next character in input buffer */
  425. static char *parsenextc; /* copy of parsefile->nextc */
  426. struct strpush {
  427. struct strpush *prev; /* preceding string on stack */
  428. char *prevstring;
  429. int prevnleft;
  430. #ifdef CONFIG_ASH_ALIAS
  431. struct alias *ap; /* if push was associated with an alias */
  432. #endif
  433. char *string; /* remember the string since it may change */
  434. };
  435. struct parsefile {
  436. struct parsefile *prev; /* preceding file on stack */
  437. int linno; /* current line */
  438. int fd; /* file descriptor (or -1 if string) */
  439. int nleft; /* number of chars left in this line */
  440. int lleft; /* number of chars left in this buffer */
  441. char *nextc; /* next char in buffer */
  442. char *buf; /* input buffer */
  443. struct strpush *strpush; /* for pushing strings at this level */
  444. struct strpush basestrpush; /* so pushing one is fast */
  445. };
  446. static struct parsefile basepf; /* top level input file */
  447. #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
  448. static struct parsefile *parsefile = &basepf; /* current input file */
  449. static int tokpushback; /* last token pushed back */
  450. #define NEOF ((union node *)&tokpushback)
  451. static int parsebackquote; /* nonzero if we are inside backquotes */
  452. static int doprompt; /* if set, prompt the user */
  453. static int needprompt; /* true if interactive and at start of line */
  454. static int lasttoken; /* last token read */
  455. static char *wordtext; /* text of last word returned by readtoken */
  456. static int checkkwd;
  457. static struct nodelist *backquotelist;
  458. static union node *redirnode;
  459. static struct heredoc *heredoc;
  460. static int quoteflag; /* set if (part of) last token was quoted */
  461. static int startlinno; /* line # where last token started */
  462. static union node *parsecmd(int);
  463. static void fixredir(union node *, const char *, int);
  464. static const char *const *findkwd(const char *);
  465. static char *endofname(const char *);
  466. /* shell.h */
  467. typedef void *pointer;
  468. static char nullstr[1]; /* zero length string */
  469. static const char spcstr[] = " ";
  470. static const char snlfmt[] = "%s\n";
  471. static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
  472. static const char illnum[] = "Illegal number: %s";
  473. static const char homestr[] = "HOME";
  474. #if DEBUG
  475. #define TRACE(param) trace param
  476. #define TRACEV(param) tracev param
  477. #else
  478. #define TRACE(param)
  479. #define TRACEV(param)
  480. #endif
  481. #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
  482. #define __builtin_expect(x, expected_value) (x)
  483. #endif
  484. #define xlikely(x) __builtin_expect((x),1)
  485. #define TEOF 0
  486. #define TNL 1
  487. #define TREDIR 2
  488. #define TWORD 3
  489. #define TSEMI 4
  490. #define TBACKGND 5
  491. #define TAND 6
  492. #define TOR 7
  493. #define TPIPE 8
  494. #define TLP 9
  495. #define TRP 10
  496. #define TENDCASE 11
  497. #define TENDBQUOTE 12
  498. #define TNOT 13
  499. #define TCASE 14
  500. #define TDO 15
  501. #define TDONE 16
  502. #define TELIF 17
  503. #define TELSE 18
  504. #define TESAC 19
  505. #define TFI 20
  506. #define TFOR 21
  507. #define TIF 22
  508. #define TIN 23
  509. #define TTHEN 24
  510. #define TUNTIL 25
  511. #define TWHILE 26
  512. #define TBEGIN 27
  513. #define TEND 28
  514. /* first char is indicating which tokens mark the end of a list */
  515. static const char *const tokname_array[] = {
  516. "\1end of file",
  517. "\0newline",
  518. "\0redirection",
  519. "\0word",
  520. "\0;",
  521. "\0&",
  522. "\0&&",
  523. "\0||",
  524. "\0|",
  525. "\0(",
  526. "\1)",
  527. "\1;;",
  528. "\1`",
  529. #define KWDOFFSET 13
  530. /* the following are keywords */
  531. "\0!",
  532. "\0case",
  533. "\1do",
  534. "\1done",
  535. "\1elif",
  536. "\1else",
  537. "\1esac",
  538. "\1fi",
  539. "\0for",
  540. "\0if",
  541. "\0in",
  542. "\1then",
  543. "\0until",
  544. "\0while",
  545. "\0{",
  546. "\1}",
  547. };
  548. static const char *tokname(int tok)
  549. {
  550. static char buf[16];
  551. if (tok >= TSEMI)
  552. buf[0] = '"';
  553. sprintf(buf + (tok >= TSEMI), "%s%c",
  554. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  555. return buf;
  556. }
  557. /* machdep.h */
  558. /*
  559. * Most machines require the value returned from malloc to be aligned
  560. * in some way. The following macro will get this right on many machines.
  561. */
  562. #define SHELL_SIZE (sizeof(union {int i; char *cp; double d; }) - 1)
  563. /*
  564. * It appears that grabstackstr() will barf with such alignments
  565. * because stalloc() will return a string allocated in a new stackblock.
  566. */
  567. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  568. /*
  569. * This file was generated by the mksyntax program.
  570. */
  571. /* Syntax classes */
  572. #define CWORD 0 /* character is nothing special */
  573. #define CNL 1 /* newline character */
  574. #define CBACK 2 /* a backslash character */
  575. #define CSQUOTE 3 /* single quote */
  576. #define CDQUOTE 4 /* double quote */
  577. #define CENDQUOTE 5 /* a terminating quote */
  578. #define CBQUOTE 6 /* backwards single quote */
  579. #define CVAR 7 /* a dollar sign */
  580. #define CENDVAR 8 /* a '}' character */
  581. #define CLP 9 /* a left paren in arithmetic */
  582. #define CRP 10 /* a right paren in arithmetic */
  583. #define CENDFILE 11 /* end of file */
  584. #define CCTL 12 /* like CWORD, except it must be escaped */
  585. #define CSPCL 13 /* these terminate a word */
  586. #define CIGN 14 /* character should be ignored */
  587. #ifdef CONFIG_ASH_ALIAS
  588. #define SYNBASE 130
  589. #define PEOF -130
  590. #define PEOA -129
  591. #define PEOA_OR_PEOF PEOA
  592. #else
  593. #define SYNBASE 129
  594. #define PEOF -129
  595. #define PEOA_OR_PEOF PEOF
  596. #endif
  597. #define is_digit(c) ((unsigned)((c) - '0') <= 9)
  598. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  599. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  600. /* C99 say: "char" declaration may be signed or unsigned default */
  601. #define SC2INT(chr2may_be_negative_int) (int)((signed char)chr2may_be_negative_int)
  602. /*
  603. * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  604. * (assuming ascii char codes, as the original implementation did)
  605. */
  606. #define is_special(c) \
  607. ( (((unsigned int)c) - 33 < 32) \
  608. && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
  609. #define digit_val(c) ((c) - '0')
  610. /*
  611. * This file was generated by the mksyntax program.
  612. */
  613. #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
  614. #define USE_SIT_FUNCTION
  615. #endif
  616. /* number syntax index */
  617. #define BASESYNTAX 0 /* not in quotes */
  618. #define DQSYNTAX 1 /* in double quotes */
  619. #define SQSYNTAX 2 /* in single quotes */
  620. #define ARISYNTAX 3 /* in arithmetic */
  621. #ifdef CONFIG_ASH_MATH_SUPPORT
  622. static const char S_I_T[][4] = {
  623. #ifdef CONFIG_ASH_ALIAS
  624. {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
  625. #endif
  626. {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
  627. {CNL, CNL, CNL, CNL}, /* 2, \n */
  628. {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
  629. {CDQUOTE, CENDQUOTE, CWORD, CWORD}, /* 4, '"' */
  630. {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
  631. {CSQUOTE, CWORD, CENDQUOTE, CWORD}, /* 6, "'" */
  632. {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
  633. {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
  634. {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
  635. {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
  636. {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
  637. #ifndef USE_SIT_FUNCTION
  638. {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
  639. {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
  640. {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
  641. #endif
  642. };
  643. #else
  644. static const char S_I_T[][3] = {
  645. #ifdef CONFIG_ASH_ALIAS
  646. {CSPCL, CIGN, CIGN}, /* 0, PEOA */
  647. #endif
  648. {CSPCL, CWORD, CWORD}, /* 1, ' ' */
  649. {CNL, CNL, CNL}, /* 2, \n */
  650. {CWORD, CCTL, CCTL}, /* 3, !*-/:=?[]~ */
  651. {CDQUOTE, CENDQUOTE, CWORD}, /* 4, '"' */
  652. {CVAR, CVAR, CWORD}, /* 5, $ */
  653. {CSQUOTE, CWORD, CENDQUOTE}, /* 6, "'" */
  654. {CSPCL, CWORD, CWORD}, /* 7, ( */
  655. {CSPCL, CWORD, CWORD}, /* 8, ) */
  656. {CBACK, CBACK, CCTL}, /* 9, \ */
  657. {CBQUOTE, CBQUOTE, CWORD}, /* 10, ` */
  658. {CENDVAR, CENDVAR, CWORD}, /* 11, } */
  659. #ifndef USE_SIT_FUNCTION
  660. {CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
  661. {CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
  662. {CCTL, CCTL, CCTL} /* 14, CTLESC ... */
  663. #endif
  664. };
  665. #endif /* CONFIG_ASH_MATH_SUPPORT */
  666. #ifdef USE_SIT_FUNCTION
  667. #define U_C(c) ((unsigned char)(c))
  668. static int SIT(int c, int syntax)
  669. {
  670. static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  671. #ifdef CONFIG_ASH_ALIAS
  672. static const char syntax_index_table[] = {
  673. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  674. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  675. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  676. 11, 3 /* "}~" */
  677. };
  678. #else
  679. static const char syntax_index_table[] = {
  680. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  681. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  682. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  683. 10, 2 /* "}~" */
  684. };
  685. #endif
  686. const char *s;
  687. int indx;
  688. if (c == PEOF) /* 2^8+2 */
  689. return CENDFILE;
  690. #ifdef CONFIG_ASH_ALIAS
  691. if (c == PEOA) /* 2^8+1 */
  692. indx = 0;
  693. else
  694. #endif
  695. if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
  696. return CCTL;
  697. else {
  698. s = strchr(spec_symbls, c);
  699. if (s == 0 || *s == 0)
  700. return CWORD;
  701. indx = syntax_index_table[(s - spec_symbls)];
  702. }
  703. return S_I_T[indx][syntax];
  704. }
  705. #else /* USE_SIT_FUNCTION */
  706. #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
  707. #ifdef CONFIG_ASH_ALIAS
  708. #define CSPCL_CIGN_CIGN_CIGN 0
  709. #define CSPCL_CWORD_CWORD_CWORD 1
  710. #define CNL_CNL_CNL_CNL 2
  711. #define CWORD_CCTL_CCTL_CWORD 3
  712. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  713. #define CVAR_CVAR_CWORD_CVAR 5
  714. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  715. #define CSPCL_CWORD_CWORD_CLP 7
  716. #define CSPCL_CWORD_CWORD_CRP 8
  717. #define CBACK_CBACK_CCTL_CBACK 9
  718. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  719. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  720. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  721. #define CWORD_CWORD_CWORD_CWORD 13
  722. #define CCTL_CCTL_CCTL_CCTL 14
  723. #else
  724. #define CSPCL_CWORD_CWORD_CWORD 0
  725. #define CNL_CNL_CNL_CNL 1
  726. #define CWORD_CCTL_CCTL_CWORD 2
  727. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  728. #define CVAR_CVAR_CWORD_CVAR 4
  729. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  730. #define CSPCL_CWORD_CWORD_CLP 6
  731. #define CSPCL_CWORD_CWORD_CRP 7
  732. #define CBACK_CBACK_CCTL_CBACK 8
  733. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  734. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  735. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  736. #define CWORD_CWORD_CWORD_CWORD 12
  737. #define CCTL_CCTL_CCTL_CCTL 13
  738. #endif
  739. static const char syntax_index_table[258] = {
  740. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  741. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  742. #ifdef CONFIG_ASH_ALIAS
  743. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  744. #endif
  745. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  746. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  747. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  748. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  749. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  750. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  751. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  752. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  753. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  754. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  755. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  756. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  757. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  758. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  759. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  760. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  761. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  762. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  763. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  764. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  765. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  766. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  767. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  768. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  769. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  770. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  771. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  772. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  773. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  774. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  775. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  776. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  777. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  778. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  779. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  780. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  781. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  782. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  783. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  784. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  785. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  786. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  787. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  788. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  789. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  790. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  791. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  792. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  793. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  794. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  795. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  796. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  797. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  798. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  799. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  800. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  801. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  802. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  803. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  804. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  805. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  806. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  807. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  808. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  809. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  810. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  811. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  812. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  813. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  814. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  815. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  816. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  817. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  818. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  819. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  820. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  821. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  822. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  823. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  824. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  825. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  826. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  827. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  828. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  829. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  830. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  831. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  832. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  833. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  834. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  835. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  836. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  837. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  838. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  839. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  840. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  841. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  842. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  843. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  844. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  845. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  846. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  847. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  848. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  849. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  850. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  851. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  852. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  853. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  854. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  855. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  856. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  857. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  858. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  859. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  860. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  861. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  862. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  863. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  864. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  865. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  866. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  867. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  868. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  869. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  870. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  871. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  872. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  873. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  874. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  875. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  876. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  877. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  878. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  879. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  880. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  881. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  882. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  883. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  884. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  885. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  886. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  887. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  888. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  889. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  890. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  891. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  892. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  893. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  894. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  895. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  896. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  897. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  898. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  899. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  900. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  901. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  902. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  903. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  904. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  905. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  906. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  907. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  908. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  909. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  910. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  911. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  912. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  913. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  914. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  915. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  916. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  917. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  918. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  919. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  920. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  921. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  922. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  923. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  924. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  925. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  926. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  927. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  928. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  929. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  930. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  931. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  932. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  933. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  934. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  935. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  936. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  937. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  938. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  939. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  940. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  941. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  942. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  943. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  944. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  945. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  946. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  947. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  948. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  949. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  950. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  951. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  952. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  953. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  954. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  955. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  956. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  957. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  958. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  959. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  960. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  961. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  962. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  963. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  964. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  965. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  966. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  967. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  968. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  969. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  970. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  971. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  972. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  973. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  974. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  975. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  976. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  977. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  978. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  979. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  980. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  981. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  982. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  983. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  984. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  985. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  986. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  987. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  988. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  989. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  990. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  991. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  992. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  993. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  994. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  995. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  996. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  997. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  998. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  999. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  1000. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  1001. };
  1002. #endif /* USE_SIT_FUNCTION */
  1003. /* alias.c */
  1004. #define ATABSIZE 39
  1005. static int funcblocksize; /* size of structures in function */
  1006. static int funcstringsize; /* size of strings in node */
  1007. static pointer funcblock; /* block to allocate function from */
  1008. static char *funcstring; /* block to allocate strings from */
  1009. static const short nodesize[26] = {
  1010. SHELL_ALIGN(sizeof (struct ncmd)),
  1011. SHELL_ALIGN(sizeof (struct npipe)),
  1012. SHELL_ALIGN(sizeof (struct nredir)),
  1013. SHELL_ALIGN(sizeof (struct nredir)),
  1014. SHELL_ALIGN(sizeof (struct nredir)),
  1015. SHELL_ALIGN(sizeof (struct nbinary)),
  1016. SHELL_ALIGN(sizeof (struct nbinary)),
  1017. SHELL_ALIGN(sizeof (struct nbinary)),
  1018. SHELL_ALIGN(sizeof (struct nif)),
  1019. SHELL_ALIGN(sizeof (struct nbinary)),
  1020. SHELL_ALIGN(sizeof (struct nbinary)),
  1021. SHELL_ALIGN(sizeof (struct nfor)),
  1022. SHELL_ALIGN(sizeof (struct ncase)),
  1023. SHELL_ALIGN(sizeof (struct nclist)),
  1024. SHELL_ALIGN(sizeof (struct narg)),
  1025. SHELL_ALIGN(sizeof (struct narg)),
  1026. SHELL_ALIGN(sizeof (struct nfile)),
  1027. SHELL_ALIGN(sizeof (struct nfile)),
  1028. SHELL_ALIGN(sizeof (struct nfile)),
  1029. SHELL_ALIGN(sizeof (struct nfile)),
  1030. SHELL_ALIGN(sizeof (struct nfile)),
  1031. SHELL_ALIGN(sizeof (struct ndup)),
  1032. SHELL_ALIGN(sizeof (struct ndup)),
  1033. SHELL_ALIGN(sizeof (struct nhere)),
  1034. SHELL_ALIGN(sizeof (struct nhere)),
  1035. SHELL_ALIGN(sizeof (struct nnot)),
  1036. };
  1037. static void calcsize(union node *);
  1038. static void sizenodelist(struct nodelist *);
  1039. static union node *copynode(union node *);
  1040. static struct nodelist *copynodelist(struct nodelist *);
  1041. static char *nodesavestr(char *);
  1042. static int evalstring(char *, int mask);
  1043. union node; /* BLETCH for ansi C */
  1044. static void evaltree(union node *, int);
  1045. static void evalbackcmd(union node *, struct backcmd *);
  1046. static int evalskip; /* set if we are skipping commands */
  1047. static int skipcount; /* number of levels to skip */
  1048. static int funcnest; /* depth of function calls */
  1049. /* reasons for skipping commands (see comment on breakcmd routine) */
  1050. #define SKIPBREAK (1 << 0)
  1051. #define SKIPCONT (1 << 1)
  1052. #define SKIPFUNC (1 << 2)
  1053. #define SKIPFILE (1 << 3)
  1054. #define SKIPEVAL (1 << 4)
  1055. /*
  1056. * This file was generated by the mkbuiltins program.
  1057. */
  1058. #if JOBS
  1059. static int bgcmd(int, char **);
  1060. #endif
  1061. static int breakcmd(int, char **);
  1062. static int cdcmd(int, char **);
  1063. #ifdef CONFIG_ASH_CMDCMD
  1064. static int commandcmd(int, char **);
  1065. #endif
  1066. static int dotcmd(int, char **);
  1067. static int evalcmd(int, char **);
  1068. #ifdef CONFIG_ASH_BUILTIN_ECHO
  1069. static int echocmd(int, char **);
  1070. #endif
  1071. #ifdef CONFIG_ASH_BUILTIN_TEST
  1072. static int testcmd(int, char **);
  1073. #endif
  1074. static int execcmd(int, char **);
  1075. static int exitcmd(int, char **);
  1076. static int exportcmd(int, char **);
  1077. static int falsecmd(int, char **);
  1078. #if JOBS
  1079. static int fgcmd(int, char **);
  1080. #endif
  1081. #ifdef CONFIG_ASH_GETOPTS
  1082. static int getoptscmd(int, char **);
  1083. #endif
  1084. static int hashcmd(int, char **);
  1085. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  1086. static int helpcmd(int argc, char **argv);
  1087. #endif
  1088. #if JOBS
  1089. static int jobscmd(int, char **);
  1090. #endif
  1091. #ifdef CONFIG_ASH_MATH_SUPPORT
  1092. static int letcmd(int, char **);
  1093. #endif
  1094. static int localcmd(int, char **);
  1095. static int pwdcmd(int, char **);
  1096. static int readcmd(int, char **);
  1097. static int returncmd(int, char **);
  1098. static int setcmd(int, char **);
  1099. static int shiftcmd(int, char **);
  1100. static int timescmd(int, char **);
  1101. static int trapcmd(int, char **);
  1102. static int truecmd(int, char **);
  1103. static int typecmd(int, char **);
  1104. static int umaskcmd(int, char **);
  1105. static int unsetcmd(int, char **);
  1106. static int waitcmd(int, char **);
  1107. static int ulimitcmd(int, char **);
  1108. #if JOBS
  1109. static int killcmd(int, char **);
  1110. #endif
  1111. /* mail.h */
  1112. #ifdef CONFIG_ASH_MAIL
  1113. static void chkmail(void);
  1114. static void changemail(const char *);
  1115. #endif
  1116. /* exec.h */
  1117. /* values of cmdtype */
  1118. #define CMDUNKNOWN -1 /* no entry in table for command */
  1119. #define CMDNORMAL 0 /* command is an executable program */
  1120. #define CMDFUNCTION 1 /* command is a shell function */
  1121. #define CMDBUILTIN 2 /* command is a shell builtin */
  1122. struct builtincmd {
  1123. const char *name;
  1124. int (*builtin)(int, char **);
  1125. /* unsigned flags; */
  1126. };
  1127. #define COMMANDCMD (builtincmd + 5 + \
  1128. 2 * ENABLE_ASH_BUILTIN_TEST + \
  1129. ENABLE_ASH_ALIAS + \
  1130. ENABLE_ASH_JOB_CONTROL)
  1131. #define EXECCMD (builtincmd + 7 + \
  1132. 2 * ENABLE_ASH_BUILTIN_TEST + \
  1133. ENABLE_ASH_ALIAS + \
  1134. ENABLE_ASH_JOB_CONTROL + \
  1135. ENABLE_ASH_CMDCMD + \
  1136. ENABLE_ASH_BUILTIN_ECHO)
  1137. #define BUILTIN_NOSPEC "0"
  1138. #define BUILTIN_SPECIAL "1"
  1139. #define BUILTIN_REGULAR "2"
  1140. #define BUILTIN_SPEC_REG "3"
  1141. #define BUILTIN_ASSIGN "4"
  1142. #define BUILTIN_SPEC_ASSG "5"
  1143. #define BUILTIN_REG_ASSG "6"
  1144. #define BUILTIN_SPEC_REG_ASSG "7"
  1145. #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
  1146. #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
  1147. #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
  1148. /* make sure to keep these in proper order since it is searched via bsearch() */
  1149. static const struct builtincmd builtincmd[] = {
  1150. { BUILTIN_SPEC_REG ".", dotcmd },
  1151. { BUILTIN_SPEC_REG ":", truecmd },
  1152. #ifdef CONFIG_ASH_BUILTIN_TEST
  1153. { BUILTIN_REGULAR "[", testcmd },
  1154. { BUILTIN_REGULAR "[[", testcmd },
  1155. #endif
  1156. #ifdef CONFIG_ASH_ALIAS
  1157. { BUILTIN_REG_ASSG "alias", aliascmd },
  1158. #endif
  1159. #if JOBS
  1160. { BUILTIN_REGULAR "bg", bgcmd },
  1161. #endif
  1162. { BUILTIN_SPEC_REG "break", breakcmd },
  1163. { BUILTIN_REGULAR "cd", cdcmd },
  1164. { BUILTIN_NOSPEC "chdir", cdcmd },
  1165. #ifdef CONFIG_ASH_CMDCMD
  1166. { BUILTIN_REGULAR "command", commandcmd },
  1167. #endif
  1168. { BUILTIN_SPEC_REG "continue", breakcmd },
  1169. #ifdef CONFIG_ASH_BUILTIN_ECHO
  1170. { BUILTIN_REGULAR "echo", echocmd },
  1171. #endif
  1172. { BUILTIN_SPEC_REG "eval", evalcmd },
  1173. { BUILTIN_SPEC_REG "exec", execcmd },
  1174. { BUILTIN_SPEC_REG "exit", exitcmd },
  1175. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  1176. { BUILTIN_REGULAR "false", falsecmd },
  1177. #if JOBS
  1178. { BUILTIN_REGULAR "fg", fgcmd },
  1179. #endif
  1180. #ifdef CONFIG_ASH_GETOPTS
  1181. { BUILTIN_REGULAR "getopts", getoptscmd },
  1182. #endif
  1183. { BUILTIN_NOSPEC "hash", hashcmd },
  1184. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  1185. { BUILTIN_NOSPEC "help", helpcmd },
  1186. #endif
  1187. #if JOBS
  1188. { BUILTIN_REGULAR "jobs", jobscmd },
  1189. { BUILTIN_REGULAR "kill", killcmd },
  1190. #endif
  1191. #ifdef CONFIG_ASH_MATH_SUPPORT
  1192. { BUILTIN_NOSPEC "let", letcmd },
  1193. #endif
  1194. { BUILTIN_ASSIGN "local", localcmd },
  1195. { BUILTIN_NOSPEC "pwd", pwdcmd },
  1196. { BUILTIN_REGULAR "read", readcmd },
  1197. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  1198. { BUILTIN_SPEC_REG "return", returncmd },
  1199. { BUILTIN_SPEC_REG "set", setcmd },
  1200. { BUILTIN_SPEC_REG "shift", shiftcmd },
  1201. { BUILTIN_SPEC_REG "source", dotcmd },
  1202. #ifdef CONFIG_ASH_BUILTIN_TEST
  1203. { BUILTIN_REGULAR "test", testcmd },
  1204. #endif
  1205. { BUILTIN_SPEC_REG "times", timescmd },
  1206. { BUILTIN_SPEC_REG "trap", trapcmd },
  1207. { BUILTIN_REGULAR "true", truecmd },
  1208. { BUILTIN_NOSPEC "type", typecmd },
  1209. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  1210. { BUILTIN_REGULAR "umask", umaskcmd },
  1211. #ifdef CONFIG_ASH_ALIAS
  1212. { BUILTIN_REGULAR "unalias", unaliascmd },
  1213. #endif
  1214. { BUILTIN_SPEC_REG "unset", unsetcmd },
  1215. { BUILTIN_REGULAR "wait", waitcmd },
  1216. };
  1217. #define NUMBUILTINS (sizeof (builtincmd) / sizeof (struct builtincmd) )
  1218. static const char *safe_applets[] = {
  1219. "[", "test", "echo", "cat",
  1220. "ln", "cp", "touch", "mkdir", "rm",
  1221. "cut", "hexdump", "awk", "sort",
  1222. "find", "xargs", "ls", "dd",
  1223. "chown", "chmod"
  1224. };
  1225. struct cmdentry {
  1226. int cmdtype;
  1227. union param {
  1228. int index;
  1229. const struct builtincmd *cmd;
  1230. struct funcnode *func;
  1231. } u;
  1232. };
  1233. /* action to find_command() */
  1234. #define DO_ERR 0x01 /* prints errors */
  1235. #define DO_ABS 0x02 /* checks absolute paths */
  1236. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  1237. #define DO_ALTPATH 0x08 /* using alternate path */
  1238. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  1239. static const char *pathopt; /* set by padvance */
  1240. static void shellexec(char **, const char *, int)
  1241. ATTRIBUTE_NORETURN;
  1242. static char *padvance(const char **, const char *);
  1243. static void find_command(char *, struct cmdentry *, int, const char *);
  1244. static struct builtincmd *find_builtin(const char *);
  1245. static void hashcd(void);
  1246. static void changepath(const char *);
  1247. static void defun(char *, union node *);
  1248. static void unsetfunc(const char *);
  1249. #ifdef CONFIG_ASH_MATH_SUPPORT_64
  1250. typedef int64_t arith_t;
  1251. #define arith_t_type (long long)
  1252. #else
  1253. typedef long arith_t;
  1254. #define arith_t_type (long)
  1255. #endif
  1256. #ifdef CONFIG_ASH_MATH_SUPPORT
  1257. static arith_t dash_arith(const char *);
  1258. static arith_t arith(const char *expr, int *perrcode);
  1259. #endif
  1260. #ifdef CONFIG_ASH_RANDOM_SUPPORT
  1261. static unsigned long rseed;
  1262. static void change_random(const char *);
  1263. # ifndef DYNAMIC_VAR
  1264. # define DYNAMIC_VAR
  1265. # endif
  1266. #endif
  1267. /* init.h */
  1268. static void reset(void);
  1269. /* var.h */
  1270. /*
  1271. * Shell variables.
  1272. */
  1273. /* flags */
  1274. #define VEXPORT 0x01 /* variable is exported */
  1275. #define VREADONLY 0x02 /* variable cannot be modified */
  1276. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1277. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1278. #define VSTACK 0x10 /* text is allocated on the stack */
  1279. #define VUNSET 0x20 /* the variable is not set */
  1280. #define VNOFUNC 0x40 /* don't call the callback function */
  1281. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1282. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1283. #ifdef DYNAMIC_VAR
  1284. # define VDYNAMIC 0x200 /* dynamic variable */
  1285. # else
  1286. # define VDYNAMIC 0
  1287. #endif
  1288. struct var {
  1289. struct var *next; /* next entry in hash list */
  1290. int flags; /* flags are defined above */
  1291. const char *text; /* name=value */
  1292. void (*func)(const char *); /* function to be called when */
  1293. /* the variable gets set/unset */
  1294. };
  1295. struct localvar {
  1296. struct localvar *next; /* next local variable in list */
  1297. struct var *vp; /* the variable that was made local */
  1298. int flags; /* saved flags */
  1299. const char *text; /* saved text */
  1300. };
  1301. static struct localvar *localvars;
  1302. /*
  1303. * Shell variables.
  1304. */
  1305. #ifdef CONFIG_ASH_GETOPTS
  1306. static void getoptsreset(const char *);
  1307. #endif
  1308. #ifdef CONFIG_LOCALE_SUPPORT
  1309. static void change_lc_all(const char *value);
  1310. static void change_lc_ctype(const char *value);
  1311. #endif
  1312. #define VTABSIZE 39
  1313. static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
  1314. #ifdef IFS_BROKEN
  1315. static const char defifsvar[] = "IFS= \t\n";
  1316. #define defifs (defifsvar + 4)
  1317. #else
  1318. static const char defifs[] = " \t\n";
  1319. #endif
  1320. static struct var varinit[] = {
  1321. #ifdef IFS_BROKEN
  1322. { 0, VSTRFIXED|VTEXTFIXED, defifsvar, 0 },
  1323. #else
  1324. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", 0 },
  1325. #endif
  1326. #ifdef CONFIG_ASH_MAIL
  1327. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
  1328. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1329. #endif
  1330. { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
  1331. { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
  1332. { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
  1333. { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
  1334. #ifdef CONFIG_ASH_GETOPTS
  1335. { 0, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
  1336. #endif
  1337. #ifdef CONFIG_ASH_RANDOM_SUPPORT
  1338. {0, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1339. #endif
  1340. #ifdef CONFIG_LOCALE_SUPPORT
  1341. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
  1342. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1343. #endif
  1344. #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
  1345. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
  1346. #endif
  1347. };
  1348. #define vifs varinit[0]
  1349. #ifdef CONFIG_ASH_MAIL
  1350. #define vmail (&vifs)[1]
  1351. #define vmpath (&vmail)[1]
  1352. #else
  1353. #define vmpath vifs
  1354. #endif
  1355. #define vpath (&vmpath)[1]
  1356. #define vps1 (&vpath)[1]
  1357. #define vps2 (&vps1)[1]
  1358. #define vps4 (&vps2)[1]
  1359. #define voptind (&vps4)[1]
  1360. #ifdef CONFIG_ASH_GETOPTS
  1361. #define vrandom (&voptind)[1]
  1362. #else
  1363. #define vrandom (&vps4)[1]
  1364. #endif
  1365. #define defpath (defpathvar + 5)
  1366. /*
  1367. * The following macros access the values of the above variables.
  1368. * They have to skip over the name. They return the null string
  1369. * for unset variables.
  1370. */
  1371. #define ifsval() (vifs.text + 4)
  1372. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1373. #define mailval() (vmail.text + 5)
  1374. #define mpathval() (vmpath.text + 9)
  1375. #define pathval() (vpath.text + 5)
  1376. #define ps1val() (vps1.text + 4)
  1377. #define ps2val() (vps2.text + 4)
  1378. #define ps4val() (vps4.text + 4)
  1379. #define optindval() (voptind.text + 7)
  1380. #define mpathset() ((vmpath.flags & VUNSET) == 0)
  1381. static void setvar(const char *, const char *, int);
  1382. static void setvareq(char *, int);
  1383. static void listsetvar(struct strlist *, int);
  1384. static char *lookupvar(const char *);
  1385. static char *bltinlookup(const char *);
  1386. static char **listvars(int, int, char ***);
  1387. #define environment() listvars(VEXPORT, VUNSET, 0)
  1388. static int showvars(const char *, int, int);
  1389. static void poplocalvars(void);
  1390. static int unsetvar(const char *);
  1391. #ifdef CONFIG_ASH_GETOPTS
  1392. static int setvarsafe(const char *, const char *, int);
  1393. #endif
  1394. static int varcmp(const char *, const char *);
  1395. static struct var **hashvar(const char *);
  1396. static int varequal(const char *a, const char *b) {
  1397. return !varcmp(a, b);
  1398. }
  1399. static int loopnest; /* current loop nesting level */
  1400. /*
  1401. * The parsefile structure pointed to by the global variable parsefile
  1402. * contains information about the current file being read.
  1403. */
  1404. struct redirtab {
  1405. struct redirtab *next;
  1406. int renamed[10];
  1407. int nullredirs;
  1408. };
  1409. static struct redirtab *redirlist;
  1410. static int nullredirs;
  1411. extern char **environ;
  1412. /* output.h */
  1413. static void outstr(const char *, FILE *);
  1414. static void outcslow(int, FILE *);
  1415. static void flushall(void);
  1416. static void flusherr(void);
  1417. static int out1fmt(const char *, ...)
  1418. __attribute__((__format__(__printf__,1,2)));
  1419. static int fmtstr(char *, size_t, const char *, ...)
  1420. __attribute__((__format__(__printf__,3,4)));
  1421. static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1422. static void out1str(const char *p)
  1423. {
  1424. outstr(p, stdout);
  1425. }
  1426. static void out2str(const char *p)
  1427. {
  1428. outstr(p, stderr);
  1429. flusherr();
  1430. }
  1431. /*
  1432. * Initialization code.
  1433. */
  1434. /*
  1435. * This routine initializes the builtin variables.
  1436. */
  1437. static void initvar(void)
  1438. {
  1439. struct var *vp;
  1440. struct var *end;
  1441. struct var **vpp;
  1442. /*
  1443. * PS1 depends on uid
  1444. */
  1445. #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
  1446. vps1.text = "PS1=\\w \\$ ";
  1447. #else
  1448. if (!geteuid())
  1449. vps1.text = "PS1=# ";
  1450. #endif
  1451. vp = varinit;
  1452. end = vp + sizeof(varinit) / sizeof(varinit[0]);
  1453. do {
  1454. vpp = hashvar(vp->text);
  1455. vp->next = *vpp;
  1456. *vpp = vp;
  1457. } while (++vp < end);
  1458. }
  1459. static void init(void)
  1460. {
  1461. /* from input.c: */
  1462. {
  1463. basepf.nextc = basepf.buf = basebuf;
  1464. }
  1465. /* from trap.c: */
  1466. {
  1467. signal(SIGCHLD, SIG_DFL);
  1468. }
  1469. /* from var.c: */
  1470. {
  1471. char **envp;
  1472. char ppid[32];
  1473. const char *p;
  1474. struct stat st1, st2;
  1475. initvar();
  1476. for (envp = environ ; envp && *envp ; envp++) {
  1477. if (strchr(*envp, '=')) {
  1478. setvareq(*envp, VEXPORT|VTEXTFIXED);
  1479. }
  1480. }
  1481. snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
  1482. setvar("PPID", ppid, 0);
  1483. p = lookupvar("PWD");
  1484. if (p)
  1485. if (*p != '/' || stat(p, &st1) || stat(".", &st2) ||
  1486. st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  1487. p = 0;
  1488. setpwd(p, 0);
  1489. }
  1490. }
  1491. /* PEOF (the end of file marker) */
  1492. enum {
  1493. INPUT_PUSH_FILE = 1,
  1494. INPUT_NOFILE_OK = 2,
  1495. };
  1496. /*
  1497. * The input line number. Input.c just defines this variable, and saves
  1498. * and restores it when files are pushed and popped. The user of this
  1499. * package must set its value.
  1500. */
  1501. static int pgetc(void);
  1502. static int pgetc2(void);
  1503. static int preadbuffer(void);
  1504. static void pungetc(void);
  1505. static void pushstring(char *, void *);
  1506. static void popstring(void);
  1507. static void setinputfd(int, int);
  1508. static void setinputstring(char *);
  1509. static void popfile(void);
  1510. static void popallfiles(void);
  1511. static void closescript(void);
  1512. /* jobs.h */
  1513. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  1514. #define FORK_FG 0
  1515. #define FORK_BG 1
  1516. #define FORK_NOJOB 2
  1517. /* mode flags for showjob(s) */
  1518. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  1519. #define SHOW_PID 0x04 /* include process pid */
  1520. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  1521. /*
  1522. * A job structure contains information about a job. A job is either a
  1523. * single process or a set of processes contained in a pipeline. In the
  1524. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  1525. * array of pids.
  1526. */
  1527. struct procstat {
  1528. pid_t pid; /* process id */
  1529. int status; /* last process status from wait() */
  1530. char *cmd; /* text of command being run */
  1531. };
  1532. struct job {
  1533. struct procstat ps0; /* status of process */
  1534. struct procstat *ps; /* status or processes when more than one */
  1535. #if JOBS
  1536. int stopstatus; /* status of a stopped job */
  1537. #endif
  1538. uint32_t
  1539. nprocs: 16, /* number of processes */
  1540. state: 8,
  1541. #define JOBRUNNING 0 /* at least one proc running */
  1542. #define JOBSTOPPED 1 /* all procs are stopped */
  1543. #define JOBDONE 2 /* all procs are completed */
  1544. #if JOBS
  1545. sigint: 1, /* job was killed by SIGINT */
  1546. jobctl: 1, /* job running under job control */
  1547. #endif
  1548. waited: 1, /* true if this entry has been waited for */
  1549. used: 1, /* true if this entry is in used */
  1550. changed: 1; /* true if status has changed */
  1551. struct job *prev_job; /* previous job */
  1552. };
  1553. static pid_t backgndpid; /* pid of last background process */
  1554. static int job_warning; /* user was warned about stopped jobs */
  1555. #if JOBS
  1556. static int jobctl; /* true if doing job control */
  1557. #endif
  1558. static struct job *makejob(union node *, int);
  1559. static int forkshell(struct job *, union node *, int);
  1560. static int waitforjob(struct job *);
  1561. static int stoppedjobs(void);
  1562. #if ! JOBS
  1563. #define setjobctl(on) /* do nothing */
  1564. #else
  1565. static void setjobctl(int);
  1566. static void showjobs(FILE *, int);
  1567. #endif
  1568. /* main.h */
  1569. /* pid of main shell */
  1570. static int rootpid;
  1571. /* shell level: 0 for the main shell, 1 for its children, and so on */
  1572. static int shlvl;
  1573. #define rootshell (!shlvl)
  1574. static void readcmdfile(char *);
  1575. static int cmdloop(int);
  1576. /* memalloc.h */
  1577. struct stackmark {
  1578. struct stack_block *stackp;
  1579. char *stacknxt;
  1580. size_t stacknleft;
  1581. struct stackmark *marknext;
  1582. };
  1583. /* minimum size of a block */
  1584. #define MINSIZE SHELL_ALIGN(504)
  1585. struct stack_block {
  1586. struct stack_block *prev;
  1587. char space[MINSIZE];
  1588. };
  1589. static struct stack_block stackbase;
  1590. static struct stack_block *stackp = &stackbase;
  1591. static struct stackmark *markp;
  1592. static char *stacknxt = stackbase.space;
  1593. static size_t stacknleft = MINSIZE;
  1594. static char *sstrend = stackbase.space + MINSIZE;
  1595. static int herefd = -1;
  1596. static pointer ckmalloc(size_t);
  1597. static pointer ckrealloc(pointer, size_t);
  1598. static char *savestr(const char *);
  1599. static pointer stalloc(size_t);
  1600. static void stunalloc(pointer);
  1601. static void setstackmark(struct stackmark *);
  1602. static void popstackmark(struct stackmark *);
  1603. static void growstackblock(void);
  1604. static void *growstackstr(void);
  1605. static char *makestrspace(size_t, char *);
  1606. static char *stnputs(const char *, size_t, char *);
  1607. static char *stputs(const char *, char *);
  1608. static char *_STPUTC(int c, char *p) {
  1609. if (p == sstrend)
  1610. p = growstackstr();
  1611. *p++ = c;
  1612. return p;
  1613. }
  1614. #define stackblock() ((void *)stacknxt)
  1615. #define stackblocksize() stacknleft
  1616. #define STARTSTACKSTR(p) ((p) = stackblock())
  1617. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1618. #define CHECKSTRSPACE(n, p) \
  1619. ({ \
  1620. char *q = (p); \
  1621. size_t l = (n); \
  1622. size_t m = sstrend - q; \
  1623. if (l > m) \
  1624. (p) = makestrspace(l, q); \
  1625. 0; \
  1626. })
  1627. #define USTPUTC(c, p) (*p++ = (c))
  1628. #define STACKSTRNUL(p) ((p) == sstrend? (p = growstackstr(), *p = '\0') : (*p = '\0'))
  1629. #define STUNPUTC(p) (--p)
  1630. #define STTOPC(p) p[-1]
  1631. #define STADJUST(amount, p) (p += (amount))
  1632. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1633. #define ungrabstackstr(s, p) stunalloc((s))
  1634. #define stackstrend() ((void *)sstrend)
  1635. #define ckfree(p) free((pointer)(p))
  1636. /* mystring.h */
  1637. #define DOLATSTRLEN 4
  1638. static char *prefix(const char *, const char *);
  1639. static int number(const char *);
  1640. static int is_number(const char *);
  1641. static char *single_quote(const char *);
  1642. static char *sstrdup(const char *);
  1643. #define equal(s1, s2) (strcmp(s1, s2) == 0)
  1644. #define scopy(s1, s2) ((void)strcpy(s2, s1))
  1645. /* options.h */
  1646. struct shparam {
  1647. int nparam; /* # of positional parameters (without $0) */
  1648. unsigned char malloc; /* if parameter list dynamically allocated */
  1649. char **p; /* parameter list */
  1650. #ifdef CONFIG_ASH_GETOPTS
  1651. int optind; /* next parameter to be processed by getopts */
  1652. int optoff; /* used by getopts */
  1653. #endif
  1654. };
  1655. #define eflag optlist[0]
  1656. #define fflag optlist[1]
  1657. #define Iflag optlist[2]
  1658. #define iflag optlist[3]
  1659. #define mflag optlist[4]
  1660. #define nflag optlist[5]
  1661. #define sflag optlist[6]
  1662. #define xflag optlist[7]
  1663. #define vflag optlist[8]
  1664. #define Cflag optlist[9]
  1665. #define aflag optlist[10]
  1666. #define bflag optlist[11]
  1667. #define uflag optlist[12]
  1668. #define viflag optlist[13]
  1669. #if DEBUG
  1670. #define nolog optlist[14]
  1671. #define debug optlist[15]
  1672. #endif
  1673. #ifndef CONFIG_FEATURE_COMMAND_EDITING_VI
  1674. #define setvimode(on) viflag = 0 /* forcibly keep the option off */
  1675. #endif
  1676. /* options.c */
  1677. static const char *const optletters_optnames[] = {
  1678. "e" "errexit",
  1679. "f" "noglob",
  1680. "I" "ignoreeof",
  1681. "i" "interactive",
  1682. "m" "monitor",
  1683. "n" "noexec",
  1684. "s" "stdin",
  1685. "x" "xtrace",
  1686. "v" "verbose",
  1687. "C" "noclobber",
  1688. "a" "allexport",
  1689. "b" "notify",
  1690. "u" "nounset",
  1691. "\0" "vi",
  1692. #if DEBUG
  1693. "\0" "nolog",
  1694. "\0" "debug",
  1695. #endif
  1696. };
  1697. #define optletters(n) optletters_optnames[(n)][0]
  1698. #define optnames(n) (&optletters_optnames[(n)][1])
  1699. #define NOPTS (sizeof(optletters_optnames)/sizeof(optletters_optnames[0]))
  1700. static char optlist[NOPTS];
  1701. static char *arg0; /* value of $0 */
  1702. static struct shparam shellparam; /* $@ current positional parameters */
  1703. static char **argptr; /* argument list for builtin commands */
  1704. static char *optionarg; /* set by nextopt (like getopt) */
  1705. static char *optptr; /* used by nextopt */
  1706. static char *minusc; /* argument to -c option */
  1707. static void procargs(int, char **);
  1708. static void optschanged(void);
  1709. static void setparam(char **);
  1710. static void freeparam(volatile struct shparam *);
  1711. static int shiftcmd(int, char **);
  1712. static int setcmd(int, char **);
  1713. static int nextopt(const char *);
  1714. /* redir.h */
  1715. /* flags passed to redirect */
  1716. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  1717. #define REDIR_SAVEFD2 03 /* set preverrout */
  1718. union node;
  1719. static void redirect(union node *, int);
  1720. static void popredir(int);
  1721. static void clearredir(int);
  1722. static int copyfd(int, int);
  1723. static int redirectsafe(union node *, int);
  1724. /* show.h */
  1725. #if DEBUG
  1726. static void showtree(union node *);
  1727. static void trace(const char *, ...);
  1728. static void tracev(const char *, va_list);
  1729. static void trargs(char **);
  1730. static void trputc(int);
  1731. static void trputs(const char *);
  1732. static void opentrace(void);
  1733. #endif
  1734. /* trap.h */
  1735. /* trap handler commands */
  1736. static char *trap[NSIG];
  1737. /* current value of signal */
  1738. static char sigmode[NSIG - 1];
  1739. /* indicates specified signal received */
  1740. static char gotsig[NSIG - 1];
  1741. static void clear_traps(void);
  1742. static void setsignal(int);
  1743. static void ignoresig(int);
  1744. static void onsig(int);
  1745. static int dotrap(void);
  1746. static void setinteractive(int);
  1747. static void exitshell(void) ATTRIBUTE_NORETURN;
  1748. static int is_safe_applet(char *name)
  1749. {
  1750. int n = sizeof(safe_applets) / sizeof(char *);
  1751. int i;
  1752. for (i = 0; i < n; i++)
  1753. if (strcmp(safe_applets[i], name) == 0)
  1754. return 1;
  1755. return 0;
  1756. }
  1757. /*
  1758. * This routine is called when an error or an interrupt occurs in an
  1759. * interactive shell and control is returned to the main command loop.
  1760. */
  1761. static void
  1762. reset(void)
  1763. {
  1764. /* from eval.c: */
  1765. {
  1766. evalskip = 0;
  1767. loopnest = 0;
  1768. }
  1769. /* from input.c: */
  1770. {
  1771. parselleft = parsenleft = 0; /* clear input buffer */
  1772. popallfiles();
  1773. }
  1774. /* from parser.c: */
  1775. {
  1776. tokpushback = 0;
  1777. checkkwd = 0;
  1778. }
  1779. /* from redir.c: */
  1780. {
  1781. clearredir(0);
  1782. }
  1783. }
  1784. #ifdef CONFIG_ASH_ALIAS
  1785. static struct alias *atab[ATABSIZE];
  1786. static void setalias(const char *, const char *);
  1787. static struct alias *freealias(struct alias *);
  1788. static struct alias **__lookupalias(const char *);
  1789. static void
  1790. setalias(const char *name, const char *val)
  1791. {
  1792. struct alias *ap, **app;
  1793. app = __lookupalias(name);
  1794. ap = *app;
  1795. INTOFF;
  1796. if (ap) {
  1797. if (!(ap->flag & ALIASINUSE)) {
  1798. ckfree(ap->val);
  1799. }
  1800. ap->val = savestr(val);
  1801. ap->flag &= ~ALIASDEAD;
  1802. } else {
  1803. /* not found */
  1804. ap = ckmalloc(sizeof (struct alias));
  1805. ap->name = savestr(name);
  1806. ap->val = savestr(val);
  1807. ap->flag = 0;
  1808. ap->next = 0;
  1809. *app = ap;
  1810. }
  1811. INTON;
  1812. }
  1813. static int
  1814. unalias(const char *name)
  1815. {
  1816. struct alias **app;
  1817. app = __lookupalias(name);
  1818. if (*app) {
  1819. INTOFF;
  1820. *app = freealias(*app);
  1821. INTON;
  1822. return 0;
  1823. }
  1824. return 1;
  1825. }
  1826. static void
  1827. rmaliases(void)
  1828. {
  1829. struct alias *ap, **app;
  1830. int i;
  1831. INTOFF;
  1832. for (i = 0; i < ATABSIZE; i++) {
  1833. app = &atab[i];
  1834. for (ap = *app; ap; ap = *app) {
  1835. *app = freealias(*app);
  1836. if (ap == *app) {
  1837. app = &ap->next;
  1838. }
  1839. }
  1840. }
  1841. INTON;
  1842. }
  1843. static struct alias *
  1844. lookupalias(const char *name, int check)
  1845. {
  1846. struct alias *ap = *__lookupalias(name);
  1847. if (check && ap && (ap->flag & ALIASINUSE))
  1848. return NULL;
  1849. return ap;
  1850. }
  1851. /*
  1852. * TODO - sort output
  1853. */
  1854. static int
  1855. aliascmd(int argc, char **argv)
  1856. {
  1857. char *n, *v;
  1858. int ret = 0;
  1859. struct alias *ap;
  1860. if (argc == 1) {
  1861. int i;
  1862. for (i = 0; i < ATABSIZE; i++)
  1863. for (ap = atab[i]; ap; ap = ap->next) {
  1864. printalias(ap);
  1865. }
  1866. return 0;
  1867. }
  1868. while ((n = *++argv) != NULL) {
  1869. if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
  1870. if ((ap = *__lookupalias(n)) == NULL) {
  1871. fprintf(stderr, "%s: %s not found\n", "alias", n);
  1872. ret = 1;
  1873. } else
  1874. printalias(ap);
  1875. } else {
  1876. *v++ = '\0';
  1877. setalias(n, v);
  1878. }
  1879. }
  1880. return ret;
  1881. }
  1882. static int
  1883. unaliascmd(int argc, char **argv)
  1884. {
  1885. int i;
  1886. while ((i = nextopt("a")) != '\0') {
  1887. if (i == 'a') {
  1888. rmaliases();
  1889. return 0;
  1890. }
  1891. }
  1892. for (i = 0; *argptr; argptr++) {
  1893. if (unalias(*argptr)) {
  1894. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  1895. i = 1;
  1896. }
  1897. }
  1898. return i;
  1899. }
  1900. static struct alias *
  1901. freealias(struct alias *ap) {
  1902. struct alias *next;
  1903. if (ap->flag & ALIASINUSE) {
  1904. ap->flag |= ALIASDEAD;
  1905. return ap;
  1906. }
  1907. next = ap->next;
  1908. ckfree(ap->name);
  1909. ckfree(ap->val);
  1910. ckfree(ap);
  1911. return next;
  1912. }
  1913. static void
  1914. printalias(const struct alias *ap) {
  1915. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  1916. }
  1917. static struct alias **
  1918. __lookupalias(const char *name) {
  1919. unsigned int hashval;
  1920. struct alias **app;
  1921. const char *p;
  1922. unsigned int ch;
  1923. p = name;
  1924. ch = (unsigned char)*p;
  1925. hashval = ch << 4;
  1926. while (ch) {
  1927. hashval += ch;
  1928. ch = (unsigned char)*++p;
  1929. }
  1930. app = &atab[hashval % ATABSIZE];
  1931. for (; *app; app = &(*app)->next) {
  1932. if (equal(name, (*app)->name)) {
  1933. break;
  1934. }
  1935. }
  1936. return app;
  1937. }
  1938. #endif /* CONFIG_ASH_ALIAS */
  1939. /* cd.c */
  1940. /*
  1941. * The cd and pwd commands.
  1942. */
  1943. #define CD_PHYSICAL 1
  1944. #define CD_PRINT 2
  1945. static int docd(const char *, int);
  1946. static int cdopt(void);
  1947. static char *curdir = nullstr; /* current working directory */
  1948. static char *physdir = nullstr; /* physical working directory */
  1949. static int
  1950. cdopt(void)
  1951. {
  1952. int flags = 0;
  1953. int i, j;
  1954. j = 'L';
  1955. while ((i = nextopt("LP"))) {
  1956. if (i != j) {
  1957. flags ^= CD_PHYSICAL;
  1958. j = i;
  1959. }
  1960. }
  1961. return flags;
  1962. }
  1963. static int
  1964. cdcmd(int argc, char **argv)
  1965. {
  1966. const char *dest;
  1967. const char *path;
  1968. const char *p;
  1969. char c;
  1970. struct stat statb;
  1971. int flags;
  1972. flags = cdopt();
  1973. dest = *argptr;
  1974. if (!dest)
  1975. dest = bltinlookup(homestr);
  1976. else if (dest[0] == '-' && dest[1] == '\0') {
  1977. dest = bltinlookup("OLDPWD");
  1978. flags |= CD_PRINT;
  1979. }
  1980. if (!dest)
  1981. dest = nullstr;
  1982. if (*dest == '/')
  1983. goto step7;
  1984. if (*dest == '.') {
  1985. c = dest[1];
  1986. dotdot:
  1987. switch (c) {
  1988. case '\0':
  1989. case '/':
  1990. goto step6;
  1991. case '.':
  1992. c = dest[2];
  1993. if (c != '.')
  1994. goto dotdot;
  1995. }
  1996. }
  1997. if (!*dest)
  1998. dest = ".";
  1999. if (!(path = bltinlookup("CDPATH"))) {
  2000. step6:
  2001. step7:
  2002. p = dest;
  2003. goto docd;
  2004. }
  2005. do {
  2006. c = *path;
  2007. p = padvance(&path, dest);
  2008. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2009. if (c && c != ':')
  2010. flags |= CD_PRINT;
  2011. docd:
  2012. if (!docd(p, flags))
  2013. goto out;
  2014. break;
  2015. }
  2016. } while (path);
  2017. sh_error("can't cd to %s", dest);
  2018. /* NOTREACHED */
  2019. out:
  2020. if (flags & CD_PRINT)
  2021. out1fmt(snlfmt, curdir);
  2022. return 0;
  2023. }
  2024. /*
  2025. * Update curdir (the name of the current directory) in response to a
  2026. * cd command.
  2027. */
  2028. static const char * updatepwd(const char *dir)
  2029. {
  2030. char *new;
  2031. char *p;
  2032. char *cdcomppath;
  2033. const char *lim;
  2034. cdcomppath = sstrdup(dir);
  2035. STARTSTACKSTR(new);
  2036. if (*dir != '/') {
  2037. if (curdir == nullstr)
  2038. return 0;
  2039. new = stputs(curdir, new);
  2040. }
  2041. new = makestrspace(strlen(dir) + 2, new);
  2042. lim = stackblock() + 1;
  2043. if (*dir != '/') {
  2044. if (new[-1] != '/')
  2045. USTPUTC('/', new);
  2046. if (new > lim && *lim == '/')
  2047. lim++;
  2048. } else {
  2049. USTPUTC('/', new);
  2050. cdcomppath++;
  2051. if (dir[1] == '/' && dir[2] != '/') {
  2052. USTPUTC('/', new);
  2053. cdcomppath++;
  2054. lim++;
  2055. }
  2056. }
  2057. p = strtok(cdcomppath, "/");
  2058. while (p) {
  2059. switch(*p) {
  2060. case '.':
  2061. if (p[1] == '.' && p[2] == '\0') {
  2062. while (new > lim) {
  2063. STUNPUTC(new);
  2064. if (new[-1] == '/')
  2065. break;
  2066. }
  2067. break;
  2068. } else if (p[1] == '\0')
  2069. break;
  2070. /* fall through */
  2071. default:
  2072. new = stputs(p, new);
  2073. USTPUTC('/', new);
  2074. }
  2075. p = strtok(0, "/");
  2076. }
  2077. if (new > lim)
  2078. STUNPUTC(new);
  2079. *new = 0;
  2080. return stackblock();
  2081. }
  2082. /*
  2083. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2084. * know that the current directory has changed.
  2085. */
  2086. static int
  2087. docd(const char *dest, int flags)
  2088. {
  2089. const char *dir = 0;
  2090. int err;
  2091. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2092. INTOFF;
  2093. if (!(flags & CD_PHYSICAL)) {
  2094. dir = updatepwd(dest);
  2095. if (dir)
  2096. dest = dir;
  2097. }
  2098. err = chdir(dest);
  2099. if (err)
  2100. goto out;
  2101. setpwd(dir, 1);
  2102. hashcd();
  2103. out:
  2104. INTON;
  2105. return err;
  2106. }
  2107. /*
  2108. * Find out what the current directory is. If we already know the current
  2109. * directory, this routine returns immediately.
  2110. */
  2111. static char * getpwd(void)
  2112. {
  2113. char *dir = getcwd(0, 0);
  2114. return dir ? dir : nullstr;
  2115. }
  2116. static int
  2117. pwdcmd(int argc, char **argv)
  2118. {
  2119. int flags;
  2120. const char *dir = curdir;
  2121. flags = cdopt();
  2122. if (flags) {
  2123. if (physdir == nullstr)
  2124. setpwd(dir, 0);
  2125. dir = physdir;
  2126. }
  2127. out1fmt(snlfmt, dir);
  2128. return 0;
  2129. }
  2130. static void
  2131. setpwd(const char *val, int setold)
  2132. {
  2133. char *oldcur, *dir;
  2134. oldcur = dir = curdir;
  2135. if (setold) {
  2136. setvar("OLDPWD", oldcur, VEXPORT);
  2137. }
  2138. INTOFF;
  2139. if (physdir != nullstr) {
  2140. if (physdir != oldcur)
  2141. free(physdir);
  2142. physdir = nullstr;
  2143. }
  2144. if (oldcur == val || !val) {
  2145. char *s = getpwd();
  2146. physdir = s;
  2147. if (!val)
  2148. dir = s;
  2149. } else
  2150. dir = savestr(val);
  2151. if (oldcur != dir && oldcur != nullstr) {
  2152. free(oldcur);
  2153. }
  2154. curdir = dir;
  2155. INTON;
  2156. setvar("PWD", dir, VEXPORT);
  2157. }
  2158. /* error.c */
  2159. /*
  2160. * Errors and exceptions.
  2161. */
  2162. /*
  2163. * Code to handle exceptions in C.
  2164. */
  2165. static void exverror(int, const char *, va_list)
  2166. ATTRIBUTE_NORETURN;
  2167. /*
  2168. * Called to raise an exception. Since C doesn't include exceptions, we
  2169. * just do a longjmp to the exception handler. The type of exception is
  2170. * stored in the global variable "exception".
  2171. */
  2172. static void
  2173. exraise(int e)
  2174. {
  2175. #if DEBUG
  2176. if (handler == NULL)
  2177. abort();
  2178. #endif
  2179. INTOFF;
  2180. exception = e;
  2181. longjmp(handler->loc, 1);
  2182. }
  2183. /*
  2184. * Called from trap.c when a SIGINT is received. (If the user specifies
  2185. * that SIGINT is to be trapped or ignored using the trap builtin, then
  2186. * this routine is not called.) Suppressint is nonzero when interrupts
  2187. * are held using the INTOFF macro. (The test for iflag is just
  2188. * defensive programming.)
  2189. */
  2190. static void
  2191. onint(void) {
  2192. int i;
  2193. intpending = 0;
  2194. i = EXSIG;
  2195. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  2196. if (!(rootshell && iflag)) {
  2197. signal(SIGINT, SIG_DFL);
  2198. raise(SIGINT);
  2199. }
  2200. i = EXINT;
  2201. }
  2202. exraise(i);
  2203. /* NOTREACHED */
  2204. }
  2205. static void
  2206. exvwarning(const char *msg, va_list ap)
  2207. {
  2208. FILE *errs;
  2209. errs = stderr;
  2210. fprintf(errs, "%s: ", arg0);
  2211. if (commandname) {
  2212. const char *fmt = (!iflag || parsefile->fd) ?
  2213. "%s: %d: " : "%s: ";
  2214. fprintf(errs, fmt, commandname, startlinno);
  2215. }
  2216. vfprintf(errs, msg, ap);
  2217. outcslow('\n', errs);
  2218. }
  2219. /*
  2220. * Exverror is called to raise the error exception. If the second argument
  2221. * is not NULL then error prints an error message using printf style
  2222. * formatting. It then raises the error exception.
  2223. */
  2224. static void
  2225. exverror(int cond, const char *msg, va_list ap)
  2226. {
  2227. #if DEBUG
  2228. if (msg) {
  2229. TRACE(("exverror(%d, \"", cond));
  2230. TRACEV((msg, ap));
  2231. TRACE(("\") pid=%d\n", getpid()));
  2232. } else
  2233. TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
  2234. if (msg)
  2235. #endif
  2236. exvwarning(msg, ap);
  2237. flushall();
  2238. exraise(cond);
  2239. /* NOTREACHED */
  2240. }
  2241. static void
  2242. sh_error(const char *msg, ...)
  2243. {
  2244. va_list ap;
  2245. va_start(ap, msg);
  2246. exverror(EXERROR, msg, ap);
  2247. /* NOTREACHED */
  2248. va_end(ap);
  2249. }
  2250. static void
  2251. exerror(int cond, const char *msg, ...)
  2252. {
  2253. va_list ap;
  2254. va_start(ap, msg);
  2255. exverror(cond, msg, ap);
  2256. /* NOTREACHED */
  2257. va_end(ap);
  2258. }
  2259. /*
  2260. * error/warning routines for external builtins
  2261. */
  2262. static void
  2263. sh_warnx(const char *fmt, ...)
  2264. {
  2265. va_list ap;
  2266. va_start(ap, fmt);
  2267. exvwarning(fmt, ap);
  2268. va_end(ap);
  2269. }
  2270. /*
  2271. * Return a string describing an error. The returned string may be a
  2272. * pointer to a static buffer that will be overwritten on the next call.
  2273. * Action describes the operation that got the error.
  2274. */
  2275. static const char *
  2276. errmsg(int e, const char *em)
  2277. {
  2278. if(e == ENOENT || e == ENOTDIR) {
  2279. return em;
  2280. }
  2281. return strerror(e);
  2282. }
  2283. /* eval.c */
  2284. /*
  2285. * Evaluate a command.
  2286. */
  2287. /* flags in argument to evaltree */
  2288. #define EV_EXIT 01 /* exit after evaluating tree */
  2289. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  2290. #define EV_BACKCMD 04 /* command executing within back quotes */
  2291. static void evalloop(union node *, int);
  2292. static void evalfor(union node *, int);
  2293. static void evalcase(union node *, int);
  2294. static void evalsubshell(union node *, int);
  2295. static void expredir(union node *);
  2296. static void evalpipe(union node *, int);
  2297. static void evalcommand(union node *, int);
  2298. static int evalbltin(const struct builtincmd *, int, char **);
  2299. static int evalfun(struct funcnode *, int, char **, int);
  2300. static void prehash(union node *);
  2301. static int bltincmd(int, char **);
  2302. static const struct builtincmd bltin = {
  2303. "\0\0", bltincmd
  2304. };
  2305. /*
  2306. * Called to reset things after an exception.
  2307. */
  2308. /*
  2309. * The eval command.
  2310. */
  2311. static int
  2312. evalcmd(int argc, char **argv)
  2313. {
  2314. char *p;
  2315. char *concat;
  2316. char **ap;
  2317. if (argc > 1) {
  2318. p = argv[1];
  2319. if (argc > 2) {
  2320. STARTSTACKSTR(concat);
  2321. ap = argv + 2;
  2322. for (;;) {
  2323. concat = stputs(p, concat);
  2324. if ((p = *ap++) == NULL)
  2325. break;
  2326. STPUTC(' ', concat);
  2327. }
  2328. STPUTC('\0', concat);
  2329. p = grabstackstr(concat);
  2330. }
  2331. evalstring(p, ~SKIPEVAL);
  2332. }
  2333. return exitstatus;
  2334. }
  2335. /*
  2336. * Execute a command or commands contained in a string.
  2337. */
  2338. static int
  2339. evalstring(char *s, int mask)
  2340. {
  2341. union node *n;
  2342. struct stackmark smark;
  2343. int skip;
  2344. setinputstring(s);
  2345. setstackmark(&smark);
  2346. skip = 0;
  2347. while ((n = parsecmd(0)) != NEOF) {
  2348. evaltree(n, 0);
  2349. popstackmark(&smark);
  2350. skip = evalskip;
  2351. if (skip)
  2352. break;
  2353. }
  2354. popfile();
  2355. skip &= mask;
  2356. evalskip = skip;
  2357. return skip;
  2358. }
  2359. /*
  2360. * Evaluate a parse tree. The value is left in the global variable
  2361. * exitstatus.
  2362. */
  2363. static void
  2364. evaltree(union node *n, int flags)
  2365. {
  2366. int checkexit = 0;
  2367. void (*evalfn)(union node *, int);
  2368. unsigned isor;
  2369. int status;
  2370. if (n == NULL) {
  2371. TRACE(("evaltree(NULL) called\n"));
  2372. goto out;
  2373. }
  2374. TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
  2375. getpid(), n, n->type, flags));
  2376. switch (n->type) {
  2377. default:
  2378. #if DEBUG
  2379. out1fmt("Node type = %d\n", n->type);
  2380. fflush(stdout);
  2381. break;
  2382. #endif
  2383. case NNOT:
  2384. evaltree(n->nnot.com, EV_TESTED);
  2385. status = !exitstatus;
  2386. goto setstatus;
  2387. case NREDIR:
  2388. expredir(n->nredir.redirect);
  2389. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  2390. if (!status) {
  2391. evaltree(n->nredir.n, flags & EV_TESTED);
  2392. status = exitstatus;
  2393. }
  2394. popredir(0);
  2395. goto setstatus;
  2396. case NCMD:
  2397. evalfn = evalcommand;
  2398. checkexit:
  2399. if (eflag && !(flags & EV_TESTED))
  2400. checkexit = ~0;
  2401. goto calleval;
  2402. case NFOR:
  2403. evalfn = evalfor;
  2404. goto calleval;
  2405. case NWHILE:
  2406. case NUNTIL:
  2407. evalfn = evalloop;
  2408. goto calleval;
  2409. case NSUBSHELL:
  2410. case NBACKGND:
  2411. evalfn = evalsubshell;
  2412. goto calleval;
  2413. case NPIPE:
  2414. evalfn = evalpipe;
  2415. goto checkexit;
  2416. case NCASE:
  2417. evalfn = evalcase;
  2418. goto calleval;
  2419. case NAND:
  2420. case NOR:
  2421. case NSEMI:
  2422. #if NAND + 1 != NOR
  2423. #error NAND + 1 != NOR
  2424. #endif
  2425. #if NOR + 1 != NSEMI
  2426. #error NOR + 1 != NSEMI
  2427. #endif
  2428. isor = n->type - NAND;
  2429. evaltree(
  2430. n->nbinary.ch1,
  2431. (flags | ((isor >> 1) - 1)) & EV_TESTED
  2432. );
  2433. if (!exitstatus == isor)
  2434. break;
  2435. if (!evalskip) {
  2436. n = n->nbinary.ch2;
  2437. evaln:
  2438. evalfn = evaltree;
  2439. calleval:
  2440. evalfn(n, flags);
  2441. break;
  2442. }
  2443. break;
  2444. case NIF:
  2445. evaltree(n->nif.test, EV_TESTED);
  2446. if (evalskip)
  2447. break;
  2448. if (exitstatus == 0) {
  2449. n = n->nif.ifpart;
  2450. goto evaln;
  2451. } else if (n->nif.elsepart) {
  2452. n = n->nif.elsepart;
  2453. goto evaln;
  2454. }
  2455. goto success;
  2456. case NDEFUN:
  2457. defun(n->narg.text, n->narg.next);
  2458. success:
  2459. status = 0;
  2460. setstatus:
  2461. exitstatus = status;
  2462. break;
  2463. }
  2464. out:
  2465. if ((checkexit & exitstatus))
  2466. evalskip |= SKIPEVAL;
  2467. else if (pendingsigs && dotrap())
  2468. goto exexit;
  2469. if (flags & EV_EXIT) {
  2470. exexit:
  2471. exraise(EXEXIT);
  2472. }
  2473. }
  2474. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  2475. static
  2476. #endif
  2477. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  2478. static void
  2479. evalloop(union node *n, int flags)
  2480. {
  2481. int status;
  2482. loopnest++;
  2483. status = 0;
  2484. flags &= EV_TESTED;
  2485. for (;;) {
  2486. int i;
  2487. evaltree(n->nbinary.ch1, EV_TESTED);
  2488. if (evalskip) {
  2489. skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
  2490. evalskip = 0;
  2491. continue;
  2492. }
  2493. if (evalskip == SKIPBREAK && --skipcount <= 0)
  2494. evalskip = 0;
  2495. break;
  2496. }
  2497. i = exitstatus;
  2498. if (n->type != NWHILE)
  2499. i = !i;
  2500. if (i != 0)
  2501. break;
  2502. evaltree(n->nbinary.ch2, flags);
  2503. status = exitstatus;
  2504. if (evalskip)
  2505. goto skipping;
  2506. }
  2507. loopnest--;
  2508. exitstatus = status;
  2509. }
  2510. static void
  2511. evalfor(union node *n, int flags)
  2512. {
  2513. struct arglist arglist;
  2514. union node *argp;
  2515. struct strlist *sp;
  2516. struct stackmark smark;
  2517. setstackmark(&smark);
  2518. arglist.lastp = &arglist.list;
  2519. for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
  2520. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  2521. /* XXX */
  2522. if (evalskip)
  2523. goto out;
  2524. }
  2525. *arglist.lastp = NULL;
  2526. exitstatus = 0;
  2527. loopnest++;
  2528. flags &= EV_TESTED;
  2529. for (sp = arglist.list ; sp ; sp = sp->next) {
  2530. setvar(n->nfor.var, sp->text, 0);
  2531. evaltree(n->nfor.body, flags);
  2532. if (evalskip) {
  2533. if (evalskip == SKIPCONT && --skipcount <= 0) {
  2534. evalskip = 0;
  2535. continue;
  2536. }
  2537. if (evalskip == SKIPBREAK && --skipcount <= 0)
  2538. evalskip = 0;
  2539. break;
  2540. }
  2541. }
  2542. loopnest--;
  2543. out:
  2544. popstackmark(&smark);
  2545. }
  2546. static void
  2547. evalcase(union node *n, int flags)
  2548. {
  2549. union node *cp;
  2550. union node *patp;
  2551. struct arglist arglist;
  2552. struct stackmark smark;
  2553. setstackmark(&smark);
  2554. arglist.lastp = &arglist.list;
  2555. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  2556. exitstatus = 0;
  2557. for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
  2558. for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
  2559. if (casematch(patp, arglist.list->text)) {
  2560. if (evalskip == 0) {
  2561. evaltree(cp->nclist.body, flags);
  2562. }
  2563. goto out;
  2564. }
  2565. }
  2566. }
  2567. out:
  2568. popstackmark(&smark);
  2569. }
  2570. /*
  2571. * Kick off a subshell to evaluate a tree.
  2572. */
  2573. static void
  2574. evalsubshell(union node *n, int flags)
  2575. {
  2576. struct job *jp;
  2577. int backgnd = (n->type == NBACKGND);
  2578. int status;
  2579. expredir(n->nredir.redirect);
  2580. if (!backgnd && flags & EV_EXIT && !trap[0])
  2581. goto nofork;
  2582. INTOFF;
  2583. jp = makejob(n, 1);
  2584. if (forkshell(jp, n, backgnd) == 0) {
  2585. INTON;
  2586. flags |= EV_EXIT;
  2587. if (backgnd)
  2588. flags &=~ EV_TESTED;
  2589. nofork:
  2590. redirect(n->nredir.redirect, 0);
  2591. evaltreenr(n->nredir.n, flags);
  2592. /* never returns */
  2593. }
  2594. status = 0;
  2595. if (! backgnd)
  2596. status = waitforjob(jp);
  2597. exitstatus = status;
  2598. INTON;
  2599. }
  2600. /*
  2601. * Compute the names of the files in a redirection list.
  2602. */
  2603. static void
  2604. expredir(union node *n)
  2605. {
  2606. union node *redir;
  2607. for (redir = n ; redir ; redir = redir->nfile.next) {
  2608. struct arglist fn;
  2609. memset(&fn, 0, sizeof(struct arglist));
  2610. fn.lastp = &fn.list;
  2611. switch (redir->type) {
  2612. case NFROMTO:
  2613. case NFROM:
  2614. case NTO:
  2615. case NCLOBBER:
  2616. case NAPPEND:
  2617. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  2618. redir->nfile.expfname = fn.list->text;
  2619. break;
  2620. case NFROMFD:
  2621. case NTOFD:
  2622. if (redir->ndup.vname) {
  2623. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  2624. if (fn.list != NULL)
  2625. fixredir(redir, fn.list->text, 1);
  2626. else
  2627. sh_error("redir error");
  2628. }
  2629. break;
  2630. }
  2631. }
  2632. }
  2633. /*
  2634. * Evaluate a pipeline. All the processes in the pipeline are children
  2635. * of the process creating the pipeline. (This differs from some versions
  2636. * of the shell, which make the last process in a pipeline the parent
  2637. * of all the rest.)
  2638. */
  2639. static void
  2640. evalpipe(union node *n, int flags)
  2641. {
  2642. struct job *jp;
  2643. struct nodelist *lp;
  2644. int pipelen;
  2645. int prevfd;
  2646. int pip[2];
  2647. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  2648. pipelen = 0;
  2649. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
  2650. pipelen++;
  2651. flags |= EV_EXIT;
  2652. INTOFF;
  2653. jp = makejob(n, pipelen);
  2654. prevfd = -1;
  2655. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
  2656. prehash(lp->n);
  2657. pip[1] = -1;
  2658. if (lp->next) {
  2659. if (pipe(pip) < 0) {
  2660. close(prevfd);
  2661. sh_error("Pipe call failed");
  2662. }
  2663. }
  2664. if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
  2665. INTON;
  2666. if (pip[1] >= 0) {
  2667. close(pip[0]);
  2668. }
  2669. if (prevfd > 0) {
  2670. dup2(prevfd, 0);
  2671. close(prevfd);
  2672. }
  2673. if (pip[1] > 1) {
  2674. dup2(pip[1], 1);
  2675. close(pip[1]);
  2676. }
  2677. evaltreenr(lp->n, flags);
  2678. /* never returns */
  2679. }
  2680. if (prevfd >= 0)
  2681. close(prevfd);
  2682. prevfd = pip[0];
  2683. close(pip[1]);
  2684. }
  2685. if (n->npipe.backgnd == 0) {
  2686. exitstatus = waitforjob(jp);
  2687. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  2688. }
  2689. INTON;
  2690. }
  2691. /*
  2692. * Execute a command inside back quotes. If it's a builtin command, we
  2693. * want to save its output in a block obtained from malloc. Otherwise
  2694. * we fork off a subprocess and get the output of the command via a pipe.
  2695. * Should be called with interrupts off.
  2696. */
  2697. static void
  2698. evalbackcmd(union node *n, struct backcmd *result)
  2699. {
  2700. int saveherefd;
  2701. result->fd = -1;
  2702. result->buf = NULL;
  2703. result->nleft = 0;
  2704. result->jp = NULL;
  2705. if (n == NULL) {
  2706. goto out;
  2707. }
  2708. saveherefd = herefd;
  2709. herefd = -1;
  2710. {
  2711. int pip[2];
  2712. struct job *jp;
  2713. if (pipe(pip) < 0)
  2714. sh_error("Pipe call failed");
  2715. jp = makejob(n, 1);
  2716. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  2717. FORCEINTON;
  2718. close(pip[0]);
  2719. if (pip[1] != 1) {
  2720. close(1);
  2721. copyfd(pip[1], 1);
  2722. close(pip[1]);
  2723. }
  2724. eflag = 0;
  2725. evaltreenr(n, EV_EXIT);
  2726. /* NOTREACHED */
  2727. }
  2728. close(pip[1]);
  2729. result->fd = pip[0];
  2730. result->jp = jp;
  2731. }
  2732. herefd = saveherefd;
  2733. out:
  2734. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  2735. result->fd, result->buf, result->nleft, result->jp));
  2736. }
  2737. #ifdef CONFIG_ASH_CMDCMD
  2738. static char ** parse_command_args(char **argv, const char **path)
  2739. {
  2740. char *cp, c;
  2741. for (;;) {
  2742. cp = *++argv;
  2743. if (!cp)
  2744. return 0;
  2745. if (*cp++ != '-')
  2746. break;
  2747. if (!(c = *cp++))
  2748. break;
  2749. if (c == '-' && !*cp) {
  2750. argv++;
  2751. break;
  2752. }
  2753. do {
  2754. switch (c) {
  2755. case 'p':
  2756. *path = defpath;
  2757. break;
  2758. default:
  2759. /* run 'typecmd' for other options */
  2760. return 0;
  2761. }
  2762. } while ((c = *cp++));
  2763. }
  2764. return argv;
  2765. }
  2766. #endif
  2767. static int isassignment(const char *p)
  2768. {
  2769. const char *q = endofname(p);
  2770. if (p == q)
  2771. return 0;
  2772. return *q == '=';
  2773. }
  2774. #ifdef CONFIG_ASH_EXPAND_PRMT
  2775. static const char *expandstr(const char *ps);
  2776. #else
  2777. #define expandstr(s) s
  2778. #endif
  2779. /*
  2780. * Execute a simple command.
  2781. */
  2782. static void
  2783. evalcommand(union node *cmd, int flags)
  2784. {
  2785. struct stackmark smark;
  2786. union node *argp;
  2787. struct arglist arglist;
  2788. struct arglist varlist;
  2789. char **argv;
  2790. int argc;
  2791. const struct strlist *sp;
  2792. struct cmdentry cmdentry;
  2793. struct job *jp;
  2794. char *lastarg;
  2795. const char *path;
  2796. int spclbltin;
  2797. int cmd_is_exec;
  2798. int status;
  2799. char **nargv;
  2800. struct builtincmd *bcmd;
  2801. int pseudovarflag = 0;
  2802. /* First expand the arguments. */
  2803. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  2804. setstackmark(&smark);
  2805. back_exitstatus = 0;
  2806. cmdentry.cmdtype = CMDBUILTIN;
  2807. cmdentry.u.cmd = &bltin;
  2808. varlist.lastp = &varlist.list;
  2809. *varlist.lastp = NULL;
  2810. arglist.lastp = &arglist.list;
  2811. *arglist.lastp = NULL;
  2812. argc = 0;
  2813. if (cmd->ncmd.args)
  2814. {
  2815. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  2816. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  2817. }
  2818. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  2819. struct strlist **spp;
  2820. spp = arglist.lastp;
  2821. if (pseudovarflag && isassignment(argp->narg.text))
  2822. expandarg(argp, &arglist, EXP_VARTILDE);
  2823. else
  2824. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  2825. for (sp = *spp; sp; sp = sp->next)
  2826. argc++;
  2827. }
  2828. argv = nargv = stalloc(sizeof (char *) * (argc + 1));
  2829. for (sp = arglist.list ; sp ; sp = sp->next) {
  2830. TRACE(("evalcommand arg: %s\n", sp->text));
  2831. *nargv++ = sp->text;
  2832. }
  2833. *nargv = NULL;
  2834. lastarg = NULL;
  2835. if (iflag && funcnest == 0 && argc > 0)
  2836. lastarg = nargv[-1];
  2837. preverrout_fd = 2;
  2838. expredir(cmd->ncmd.redirect);
  2839. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
  2840. path = vpath.text;
  2841. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  2842. struct strlist **spp;
  2843. char *p;
  2844. spp = varlist.lastp;
  2845. expandarg(argp, &varlist, EXP_VARTILDE);
  2846. /*
  2847. * Modify the command lookup path, if a PATH= assignment
  2848. * is present
  2849. */
  2850. p = (*spp)->text;
  2851. if (varequal(p, path))
  2852. path = p;
  2853. }
  2854. /* Print the command if xflag is set. */
  2855. if (xflag) {
  2856. int n;
  2857. const char *p = " %s";
  2858. p++;
  2859. dprintf(preverrout_fd, p, expandstr(ps4val()));
  2860. sp = varlist.list;
  2861. for(n = 0; n < 2; n++) {
  2862. while (sp) {
  2863. dprintf(preverrout_fd, p, sp->text);
  2864. sp = sp->next;
  2865. if(*p == '%') {
  2866. p--;
  2867. }
  2868. }
  2869. sp = arglist.list;
  2870. }
  2871. full_write(preverrout_fd, "\n", 1);
  2872. }
  2873. cmd_is_exec = 0;
  2874. spclbltin = -1;
  2875. /* Now locate the command. */
  2876. if (argc) {
  2877. const char *oldpath;
  2878. int cmd_flag = DO_ERR;
  2879. path += 5;
  2880. oldpath = path;
  2881. for (;;) {
  2882. find_command(argv[0], &cmdentry, cmd_flag, path);
  2883. if (cmdentry.cmdtype == CMDUNKNOWN) {
  2884. status = 127;
  2885. flusherr();
  2886. goto bail;
  2887. }
  2888. /* implement bltin and command here */
  2889. if (cmdentry.cmdtype != CMDBUILTIN)
  2890. break;
  2891. if (spclbltin < 0)
  2892. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  2893. if (cmdentry.u.cmd == EXECCMD)
  2894. cmd_is_exec++;
  2895. #ifdef CONFIG_ASH_CMDCMD
  2896. if (cmdentry.u.cmd == COMMANDCMD) {
  2897. path = oldpath;
  2898. nargv = parse_command_args(argv, &path);
  2899. if (!nargv)
  2900. break;
  2901. argc -= nargv - argv;
  2902. argv = nargv;
  2903. cmd_flag |= DO_NOFUNC;
  2904. } else
  2905. #endif
  2906. break;
  2907. }
  2908. }
  2909. if (status) {
  2910. /* We have a redirection error. */
  2911. if (spclbltin > 0)
  2912. exraise(EXERROR);
  2913. bail:
  2914. exitstatus = status;
  2915. goto out;
  2916. }
  2917. /* Execute the command. */
  2918. switch (cmdentry.cmdtype) {
  2919. default:
  2920. /* Fork off a child process if necessary. */
  2921. if (!(flags & EV_EXIT) || trap[0]) {
  2922. INTOFF;
  2923. jp = makejob(cmd, 1);
  2924. if (forkshell(jp, cmd, FORK_FG) != 0) {
  2925. exitstatus = waitforjob(jp);
  2926. INTON;
  2927. break;
  2928. }
  2929. FORCEINTON;
  2930. }
  2931. listsetvar(varlist.list, VEXPORT|VSTACK);
  2932. shellexec(argv, path, cmdentry.u.index);
  2933. /* NOTREACHED */
  2934. case CMDBUILTIN:
  2935. cmdenviron = varlist.list;
  2936. if (cmdenviron) {
  2937. struct strlist *list = cmdenviron;
  2938. int i = VNOSET;
  2939. if (spclbltin > 0 || argc == 0) {
  2940. i = 0;
  2941. if (cmd_is_exec && argc > 1)
  2942. i = VEXPORT;
  2943. }
  2944. listsetvar(list, i);
  2945. }
  2946. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  2947. int exit_status;
  2948. int i, j;
  2949. i = exception;
  2950. if (i == EXEXIT)
  2951. goto raise;
  2952. exit_status = 2;
  2953. j = 0;
  2954. if (i == EXINT)
  2955. j = SIGINT;
  2956. if (i == EXSIG)
  2957. j = pendingsigs;
  2958. if (j)
  2959. exit_status = j + 128;
  2960. exitstatus = exit_status;
  2961. if (i == EXINT || spclbltin > 0) {
  2962. raise:
  2963. longjmp(handler->loc, 1);
  2964. }
  2965. FORCEINTON;
  2966. }
  2967. break;
  2968. case CMDFUNCTION:
  2969. listsetvar(varlist.list, 0);
  2970. if (evalfun(cmdentry.u.func, argc, argv, flags))
  2971. goto raise;
  2972. break;
  2973. }
  2974. out:
  2975. popredir(cmd_is_exec);
  2976. if (lastarg)
  2977. /* dsl: I think this is intended to be used to support
  2978. * '_' in 'vi' command mode during line editing...
  2979. * However I implemented that within libedit itself.
  2980. */
  2981. setvar("_", lastarg, 0);
  2982. popstackmark(&smark);
  2983. }
  2984. static int
  2985. evalbltin(const struct builtincmd *cmd, int argc, char **argv) {
  2986. char *volatile savecmdname;
  2987. struct jmploc *volatile savehandler;
  2988. struct jmploc jmploc;
  2989. int i;
  2990. savecmdname = commandname;
  2991. if ((i = setjmp(jmploc.loc)))
  2992. goto cmddone;
  2993. savehandler = handler;
  2994. handler = &jmploc;
  2995. commandname = argv[0];
  2996. argptr = argv + 1;
  2997. optptr = NULL; /* initialize nextopt */
  2998. exitstatus = (*cmd->builtin)(argc, argv);
  2999. flushall();
  3000. cmddone:
  3001. exitstatus |= ferror(stdout);
  3002. clearerr(stdout);
  3003. commandname = savecmdname;
  3004. exsig = 0;
  3005. handler = savehandler;
  3006. return i;
  3007. }
  3008. static int
  3009. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  3010. {
  3011. volatile struct shparam saveparam;
  3012. struct localvar *volatile savelocalvars;
  3013. struct jmploc *volatile savehandler;
  3014. struct jmploc jmploc;
  3015. int e;
  3016. saveparam = shellparam;
  3017. savelocalvars = localvars;
  3018. if ((e = setjmp(jmploc.loc))) {
  3019. goto funcdone;
  3020. }
  3021. INTOFF;
  3022. savehandler = handler;
  3023. handler = &jmploc;
  3024. localvars = NULL;
  3025. shellparam.malloc = 0;
  3026. func->count++;
  3027. funcnest++;
  3028. INTON;
  3029. shellparam.nparam = argc - 1;
  3030. shellparam.p = argv + 1;
  3031. #ifdef CONFIG_ASH_GETOPTS
  3032. shellparam.optind = 1;
  3033. shellparam.optoff = -1;
  3034. #endif
  3035. evaltree(&func->n, flags & EV_TESTED);
  3036. funcdone:
  3037. INTOFF;
  3038. funcnest--;
  3039. freefunc(func);
  3040. poplocalvars();
  3041. localvars = savelocalvars;
  3042. freeparam(&shellparam);
  3043. shellparam = saveparam;
  3044. handler = savehandler;
  3045. INTON;
  3046. evalskip &= ~SKIPFUNC;
  3047. return e;
  3048. }
  3049. static int goodname(const char *p)
  3050. {
  3051. return !*endofname(p);
  3052. }
  3053. /*
  3054. * Search for a command. This is called before we fork so that the
  3055. * location of the command will be available in the parent as well as
  3056. * the child. The check for "goodname" is an overly conservative
  3057. * check that the name will not be subject to expansion.
  3058. */
  3059. static void
  3060. prehash(union node *n)
  3061. {
  3062. struct cmdentry entry;
  3063. if (n->type == NCMD && n->ncmd.args)
  3064. if (goodname(n->ncmd.args->narg.text))
  3065. find_command(n->ncmd.args->narg.text, &entry, 0,
  3066. pathval());
  3067. }
  3068. /*
  3069. * Builtin commands. Builtin commands whose functions are closely
  3070. * tied to evaluation are implemented here.
  3071. */
  3072. /*
  3073. * No command given.
  3074. */
  3075. static int
  3076. bltincmd(int argc, char **argv)
  3077. {
  3078. /*
  3079. * Preserve exitstatus of a previous possible redirection
  3080. * as POSIX mandates
  3081. */
  3082. return back_exitstatus;
  3083. }
  3084. /*
  3085. * Handle break and continue commands. Break, continue, and return are
  3086. * all handled by setting the evalskip flag. The evaluation routines
  3087. * above all check this flag, and if it is set they start skipping
  3088. * commands rather than executing them. The variable skipcount is
  3089. * the number of loops to break/continue, or the number of function
  3090. * levels to return. (The latter is always 1.) It should probably
  3091. * be an error to break out of more loops than exist, but it isn't
  3092. * in the standard shell so we don't make it one here.
  3093. */
  3094. static int
  3095. breakcmd(int argc, char **argv)
  3096. {
  3097. int n = argc > 1 ? number(argv[1]) : 1;
  3098. if (n <= 0)
  3099. sh_error(illnum, argv[1]);
  3100. if (n > loopnest)
  3101. n = loopnest;
  3102. if (n > 0) {
  3103. evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
  3104. skipcount = n;
  3105. }
  3106. return 0;
  3107. }
  3108. /*
  3109. * The return command.
  3110. */
  3111. static int
  3112. returncmd(int argc, char **argv)
  3113. {
  3114. /*
  3115. * If called outside a function, do what ksh does;
  3116. * skip the rest of the file.
  3117. */
  3118. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  3119. return argv[1] ? number(argv[1]) : exitstatus;
  3120. }
  3121. static int
  3122. falsecmd(int argc, char **argv)
  3123. {
  3124. return 1;
  3125. }
  3126. static int
  3127. truecmd(int argc, char **argv)
  3128. {
  3129. return 0;
  3130. }
  3131. static int
  3132. execcmd(int argc, char **argv)
  3133. {
  3134. if (argc > 1) {
  3135. iflag = 0; /* exit on error */
  3136. mflag = 0;
  3137. optschanged();
  3138. shellexec(argv + 1, pathval(), 0);
  3139. }
  3140. return 0;
  3141. }
  3142. /* exec.c */
  3143. /*
  3144. * When commands are first encountered, they are entered in a hash table.
  3145. * This ensures that a full path search will not have to be done for them
  3146. * on each invocation.
  3147. *
  3148. * We should investigate converting to a linear search, even though that
  3149. * would make the command name "hash" a misnomer.
  3150. */
  3151. #define CMDTABLESIZE 31 /* should be prime */
  3152. #define ARB 1 /* actual size determined at run time */
  3153. struct tblentry {
  3154. struct tblentry *next; /* next entry in hash chain */
  3155. union param param; /* definition of builtin function */
  3156. short cmdtype; /* index identifying command */
  3157. char rehash; /* if set, cd done since entry created */
  3158. char cmdname[ARB]; /* name of command */
  3159. };
  3160. static struct tblentry *cmdtable[CMDTABLESIZE];
  3161. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  3162. static void tryexec(char *, char **, char **);
  3163. static void clearcmdentry(int);
  3164. static struct tblentry *cmdlookup(const char *, int);
  3165. static void delete_cmd_entry(void);
  3166. /*
  3167. * Exec a program. Never returns. If you change this routine, you may
  3168. * have to change the find_command routine as well.
  3169. */
  3170. static void
  3171. shellexec(char **argv, const char *path, int idx)
  3172. {
  3173. char *cmdname;
  3174. int e;
  3175. char **envp;
  3176. int exerrno;
  3177. clearredir(1);
  3178. envp = environment();
  3179. if (strchr(argv[0], '/') != NULL
  3180. || is_safe_applet(argv[0])
  3181. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  3182. || find_applet_by_name(argv[0])
  3183. #endif
  3184. ) {
  3185. tryexec(argv[0], argv, envp);
  3186. e = errno;
  3187. } else {
  3188. e = ENOENT;
  3189. while ((cmdname = padvance(&path, argv[0])) != NULL) {
  3190. if (--idx < 0 && pathopt == NULL) {
  3191. tryexec(cmdname, argv, envp);
  3192. if (errno != ENOENT && errno != ENOTDIR)
  3193. e = errno;
  3194. }
  3195. stunalloc(cmdname);
  3196. }
  3197. }
  3198. /* Map to POSIX errors */
  3199. switch (e) {
  3200. case EACCES:
  3201. exerrno = 126;
  3202. break;
  3203. case ENOENT:
  3204. exerrno = 127;
  3205. break;
  3206. default:
  3207. exerrno = 2;
  3208. break;
  3209. }
  3210. exitstatus = exerrno;
  3211. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  3212. argv[0], e, suppressint ));
  3213. exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
  3214. /* NOTREACHED */
  3215. }
  3216. static void
  3217. tryexec(char *cmd, char **argv, char **envp)
  3218. {
  3219. int repeated = 0;
  3220. struct BB_applet *a;
  3221. int argc = 0;
  3222. char **c;
  3223. if(strchr(cmd, '/') == NULL && is_safe_applet(cmd) && (a = find_applet_by_name(cmd)) != NULL) {
  3224. c = argv;
  3225. while (*c != NULL) {
  3226. c++; argc++;
  3227. }
  3228. applet_name = cmd;
  3229. exit(a->main(argc, argv));
  3230. }
  3231. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  3232. if(find_applet_by_name(cmd) != NULL) {
  3233. /* re-exec ourselves with the new arguments */
  3234. execve(CONFIG_BUSYBOX_EXEC_PATH,argv,envp);
  3235. /* If they called chroot or otherwise made the binary no longer
  3236. * executable, fall through */
  3237. }
  3238. #endif
  3239. repeat:
  3240. #ifdef SYSV
  3241. do {
  3242. execve(cmd, argv, envp);
  3243. } while (errno == EINTR);
  3244. #else
  3245. execve(cmd, argv, envp);
  3246. #endif
  3247. if (repeated++) {
  3248. ckfree(argv);
  3249. } else if (errno == ENOEXEC) {
  3250. char **ap;
  3251. char **new;
  3252. for (ap = argv; *ap; ap++)
  3253. ;
  3254. ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
  3255. ap[1] = cmd;
  3256. *ap = cmd = (char *)DEFAULT_SHELL;
  3257. ap += 2;
  3258. argv++;
  3259. while ((*ap++ = *argv++))
  3260. ;
  3261. argv = new;
  3262. goto repeat;
  3263. }
  3264. }
  3265. /*
  3266. * Do a path search. The variable path (passed by reference) should be
  3267. * set to the start of the path before the first call; padvance will update
  3268. * this value as it proceeds. Successive calls to padvance will return
  3269. * the possible path expansions in sequence. If an option (indicated by
  3270. * a percent sign) appears in the path entry then the global variable
  3271. * pathopt will be set to point to it; otherwise pathopt will be set to
  3272. * NULL.
  3273. */
  3274. static char *
  3275. padvance(const char **path, const char *name)
  3276. {
  3277. const char *p;
  3278. char *q;
  3279. const char *start;
  3280. size_t len;
  3281. if (*path == NULL)
  3282. return NULL;
  3283. start = *path;
  3284. for (p = start ; *p && *p != ':' && *p != '%' ; p++);
  3285. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  3286. while (stackblocksize() < len)
  3287. growstackblock();
  3288. q = stackblock();
  3289. if (p != start) {
  3290. memcpy(q, start, p - start);
  3291. q += p - start;
  3292. *q++ = '/';
  3293. }
  3294. strcpy(q, name);
  3295. pathopt = NULL;
  3296. if (*p == '%') {
  3297. pathopt = ++p;
  3298. while (*p && *p != ':') p++;
  3299. }
  3300. if (*p == ':')
  3301. *path = p + 1;
  3302. else
  3303. *path = NULL;
  3304. return stalloc(len);
  3305. }
  3306. /*** Command hashing code ***/
  3307. static void
  3308. printentry(struct tblentry *cmdp)
  3309. {
  3310. int idx;
  3311. const char *path;
  3312. char *name;
  3313. idx = cmdp->param.index;
  3314. path = pathval();
  3315. do {
  3316. name = padvance(&path, cmdp->cmdname);
  3317. stunalloc(name);
  3318. } while (--idx >= 0);
  3319. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  3320. }
  3321. static int
  3322. hashcmd(int argc, char **argv)
  3323. {
  3324. struct tblentry **pp;
  3325. struct tblentry *cmdp;
  3326. int c;
  3327. struct cmdentry entry;
  3328. char *name;
  3329. while ((c = nextopt("r")) != '\0') {
  3330. clearcmdentry(0);
  3331. return 0;
  3332. }
  3333. if (*argptr == NULL) {
  3334. for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
  3335. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3336. if (cmdp->cmdtype == CMDNORMAL)
  3337. printentry(cmdp);
  3338. }
  3339. }
  3340. return 0;
  3341. }
  3342. c = 0;
  3343. while ((name = *argptr) != NULL) {
  3344. if ((cmdp = cmdlookup(name, 0)) != NULL
  3345. && (cmdp->cmdtype == CMDNORMAL
  3346. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
  3347. delete_cmd_entry();
  3348. find_command(name, &entry, DO_ERR, pathval());
  3349. if (entry.cmdtype == CMDUNKNOWN)
  3350. c = 1;
  3351. argptr++;
  3352. }
  3353. return c;
  3354. }
  3355. /*
  3356. * Resolve a command name. If you change this routine, you may have to
  3357. * change the shellexec routine as well.
  3358. */
  3359. static void
  3360. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  3361. {
  3362. struct tblentry *cmdp;
  3363. int idx;
  3364. int prev;
  3365. char *fullname;
  3366. struct stat statb;
  3367. int e;
  3368. int updatetbl;
  3369. struct builtincmd *bcmd;
  3370. /* If name contains a slash, don't use PATH or hash table */
  3371. if (strchr(name, '/') != NULL) {
  3372. entry->u.index = -1;
  3373. if (act & DO_ABS) {
  3374. while (stat(name, &statb) < 0) {
  3375. #ifdef SYSV
  3376. if (errno == EINTR)
  3377. continue;
  3378. #endif
  3379. entry->cmdtype = CMDUNKNOWN;
  3380. return;
  3381. }
  3382. }
  3383. entry->cmdtype = CMDNORMAL;
  3384. return;
  3385. }
  3386. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  3387. if (find_applet_by_name(name)) {
  3388. entry->cmdtype = CMDNORMAL;
  3389. entry->u.index = -1;
  3390. return;
  3391. }
  3392. #endif
  3393. if (is_safe_applet(name)) {
  3394. entry->cmdtype = CMDNORMAL;
  3395. entry->u.index = -1;
  3396. return;
  3397. }
  3398. updatetbl = (path == pathval());
  3399. if (!updatetbl) {
  3400. act |= DO_ALTPATH;
  3401. if (strstr(path, "%builtin") != NULL)
  3402. act |= DO_ALTBLTIN;
  3403. }
  3404. /* If name is in the table, check answer will be ok */
  3405. if ((cmdp = cmdlookup(name, 0)) != NULL) {
  3406. int bit;
  3407. switch (cmdp->cmdtype) {
  3408. default:
  3409. #if DEBUG
  3410. abort();
  3411. #endif
  3412. case CMDNORMAL:
  3413. bit = DO_ALTPATH;
  3414. break;
  3415. case CMDFUNCTION:
  3416. bit = DO_NOFUNC;
  3417. break;
  3418. case CMDBUILTIN:
  3419. bit = DO_ALTBLTIN;
  3420. break;
  3421. }
  3422. if (act & bit) {
  3423. updatetbl = 0;
  3424. cmdp = NULL;
  3425. } else if (cmdp->rehash == 0)
  3426. /* if not invalidated by cd, we're done */
  3427. goto success;
  3428. }
  3429. /* If %builtin not in path, check for builtin next */
  3430. bcmd = find_builtin(name);
  3431. if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
  3432. act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
  3433. )))
  3434. goto builtin_success;
  3435. /* We have to search path. */
  3436. prev = -1; /* where to start */
  3437. if (cmdp && cmdp->rehash) { /* doing a rehash */
  3438. if (cmdp->cmdtype == CMDBUILTIN)
  3439. prev = builtinloc;
  3440. else
  3441. prev = cmdp->param.index;
  3442. }
  3443. e = ENOENT;
  3444. idx = -1;
  3445. loop:
  3446. while ((fullname = padvance(&path, name)) != NULL) {
  3447. stunalloc(fullname);
  3448. idx++;
  3449. if (pathopt) {
  3450. if (prefix(pathopt, "builtin")) {
  3451. if (bcmd)
  3452. goto builtin_success;
  3453. continue;
  3454. } else if (!(act & DO_NOFUNC) &&
  3455. prefix(pathopt, "func")) {
  3456. /* handled below */
  3457. } else {
  3458. /* ignore unimplemented options */
  3459. continue;
  3460. }
  3461. }
  3462. /* if rehash, don't redo absolute path names */
  3463. if (fullname[0] == '/' && idx <= prev) {
  3464. if (idx < prev)
  3465. continue;
  3466. TRACE(("searchexec \"%s\": no change\n", name));
  3467. goto success;
  3468. }
  3469. while (stat(fullname, &statb) < 0) {
  3470. #ifdef SYSV
  3471. if (errno == EINTR)
  3472. continue;
  3473. #endif
  3474. if (errno != ENOENT && errno != ENOTDIR)
  3475. e = errno;
  3476. goto loop;
  3477. }
  3478. e = EACCES; /* if we fail, this will be the error */
  3479. if (!S_ISREG(statb.st_mode))
  3480. continue;
  3481. if (pathopt) { /* this is a %func directory */
  3482. stalloc(strlen(fullname) + 1);
  3483. readcmdfile(fullname);
  3484. if ((cmdp = cmdlookup(name, 0)) == NULL ||
  3485. cmdp->cmdtype != CMDFUNCTION)
  3486. sh_error("%s not defined in %s", name, fullname);
  3487. stunalloc(fullname);
  3488. goto success;
  3489. }
  3490. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  3491. if (!updatetbl) {
  3492. entry->cmdtype = CMDNORMAL;
  3493. entry->u.index = idx;
  3494. return;
  3495. }
  3496. INTOFF;
  3497. cmdp = cmdlookup(name, 1);
  3498. cmdp->cmdtype = CMDNORMAL;
  3499. cmdp->param.index = idx;
  3500. INTON;
  3501. goto success;
  3502. }
  3503. /* We failed. If there was an entry for this command, delete it */
  3504. if (cmdp && updatetbl)
  3505. delete_cmd_entry();
  3506. if (act & DO_ERR)
  3507. sh_warnx("%s: %s", name, errmsg(e, E_EXEC));
  3508. entry->cmdtype = CMDUNKNOWN;
  3509. return;
  3510. builtin_success:
  3511. if (!updatetbl) {
  3512. entry->cmdtype = CMDBUILTIN;
  3513. entry->u.cmd = bcmd;
  3514. return;
  3515. }
  3516. INTOFF;
  3517. cmdp = cmdlookup(name, 1);
  3518. cmdp->cmdtype = CMDBUILTIN;
  3519. cmdp->param.cmd = bcmd;
  3520. INTON;
  3521. success:
  3522. cmdp->rehash = 0;
  3523. entry->cmdtype = cmdp->cmdtype;
  3524. entry->u = cmdp->param;
  3525. }
  3526. /*
  3527. * Wrapper around strcmp for qsort/bsearch/...
  3528. */
  3529. static int pstrcmp(const void *a, const void *b)
  3530. {
  3531. return strcmp((const char *) a, (*(const char *const *) b) + 1);
  3532. }
  3533. /*
  3534. * Search the table of builtin commands.
  3535. */
  3536. static struct builtincmd *
  3537. find_builtin(const char *name)
  3538. {
  3539. struct builtincmd *bp;
  3540. bp = bsearch(
  3541. name, builtincmd, NUMBUILTINS, sizeof(struct builtincmd),
  3542. pstrcmp
  3543. );
  3544. return bp;
  3545. }
  3546. /*
  3547. * Called when a cd is done. Marks all commands so the next time they
  3548. * are executed they will be rehashed.
  3549. */
  3550. static void
  3551. hashcd(void)
  3552. {
  3553. struct tblentry **pp;
  3554. struct tblentry *cmdp;
  3555. for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
  3556. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3557. if (cmdp->cmdtype == CMDNORMAL || (
  3558. cmdp->cmdtype == CMDBUILTIN &&
  3559. !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
  3560. builtinloc > 0
  3561. ))
  3562. cmdp->rehash = 1;
  3563. }
  3564. }
  3565. }
  3566. /*
  3567. * Fix command hash table when PATH changed.
  3568. * Called before PATH is changed. The argument is the new value of PATH;
  3569. * pathval() still returns the old value at this point.
  3570. * Called with interrupts off.
  3571. */
  3572. static void
  3573. changepath(const char *newval)
  3574. {
  3575. const char *old, *new;
  3576. int idx;
  3577. int firstchange;
  3578. int idx_bltin;
  3579. old = pathval();
  3580. new = newval;
  3581. firstchange = 9999; /* assume no change */
  3582. idx = 0;
  3583. idx_bltin = -1;
  3584. for (;;) {
  3585. if (*old != *new) {
  3586. firstchange = idx;
  3587. if ((*old == '\0' && *new == ':')
  3588. || (*old == ':' && *new == '\0'))
  3589. firstchange++;
  3590. old = new; /* ignore subsequent differences */
  3591. }
  3592. if (*new == '\0')
  3593. break;
  3594. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  3595. idx_bltin = idx;
  3596. if (*new == ':') {
  3597. idx++;
  3598. }
  3599. new++, old++;
  3600. }
  3601. if (builtinloc < 0 && idx_bltin >= 0)
  3602. builtinloc = idx_bltin; /* zap builtins */
  3603. if (builtinloc >= 0 && idx_bltin < 0)
  3604. firstchange = 0;
  3605. clearcmdentry(firstchange);
  3606. builtinloc = idx_bltin;
  3607. }
  3608. /*
  3609. * Clear out command entries. The argument specifies the first entry in
  3610. * PATH which has changed.
  3611. */
  3612. static void
  3613. clearcmdentry(int firstchange)
  3614. {
  3615. struct tblentry **tblp;
  3616. struct tblentry **pp;
  3617. struct tblentry *cmdp;
  3618. INTOFF;
  3619. for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
  3620. pp = tblp;
  3621. while ((cmdp = *pp) != NULL) {
  3622. if ((cmdp->cmdtype == CMDNORMAL &&
  3623. cmdp->param.index >= firstchange)
  3624. || (cmdp->cmdtype == CMDBUILTIN &&
  3625. builtinloc >= firstchange)) {
  3626. *pp = cmdp->next;
  3627. ckfree(cmdp);
  3628. } else {
  3629. pp = &cmdp->next;
  3630. }
  3631. }
  3632. }
  3633. INTON;
  3634. }
  3635. /*
  3636. * Locate a command in the command hash table. If "add" is nonzero,
  3637. * add the command to the table if it is not already present. The
  3638. * variable "lastcmdentry" is set to point to the address of the link
  3639. * pointing to the entry, so that delete_cmd_entry can delete the
  3640. * entry.
  3641. *
  3642. * Interrupts must be off if called with add != 0.
  3643. */
  3644. static struct tblentry **lastcmdentry;
  3645. static struct tblentry *
  3646. cmdlookup(const char *name, int add)
  3647. {
  3648. unsigned int hashval;
  3649. const char *p;
  3650. struct tblentry *cmdp;
  3651. struct tblentry **pp;
  3652. p = name;
  3653. hashval = (unsigned char)*p << 4;
  3654. while (*p)
  3655. hashval += (unsigned char)*p++;
  3656. hashval &= 0x7FFF;
  3657. pp = &cmdtable[hashval % CMDTABLESIZE];
  3658. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3659. if (equal(cmdp->cmdname, name))
  3660. break;
  3661. pp = &cmdp->next;
  3662. }
  3663. if (add && cmdp == NULL) {
  3664. cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
  3665. + strlen(name) + 1);
  3666. cmdp->next = NULL;
  3667. cmdp->cmdtype = CMDUNKNOWN;
  3668. strcpy(cmdp->cmdname, name);
  3669. }
  3670. lastcmdentry = pp;
  3671. return cmdp;
  3672. }
  3673. /*
  3674. * Delete the command entry returned on the last lookup.
  3675. */
  3676. static void
  3677. delete_cmd_entry(void)
  3678. {
  3679. struct tblentry *cmdp;
  3680. INTOFF;
  3681. cmdp = *lastcmdentry;
  3682. *lastcmdentry = cmdp->next;
  3683. if (cmdp->cmdtype == CMDFUNCTION)
  3684. freefunc(cmdp->param.func);
  3685. ckfree(cmdp);
  3686. INTON;
  3687. }
  3688. /*
  3689. * Add a new command entry, replacing any existing command entry for
  3690. * the same name - except special builtins.
  3691. */
  3692. static void addcmdentry(char *name, struct cmdentry *entry)
  3693. {
  3694. struct tblentry *cmdp;
  3695. cmdp = cmdlookup(name, 1);
  3696. if (cmdp->cmdtype == CMDFUNCTION) {
  3697. freefunc(cmdp->param.func);
  3698. }
  3699. cmdp->cmdtype = entry->cmdtype;
  3700. cmdp->param = entry->u;
  3701. cmdp->rehash = 0;
  3702. }
  3703. /*
  3704. * Make a copy of a parse tree.
  3705. */
  3706. static struct funcnode * copyfunc(union node *n)
  3707. {
  3708. struct funcnode *f;
  3709. size_t blocksize;
  3710. funcblocksize = offsetof(struct funcnode, n);
  3711. funcstringsize = 0;
  3712. calcsize(n);
  3713. blocksize = funcblocksize;
  3714. f = ckmalloc(blocksize + funcstringsize);
  3715. funcblock = (char *) f + offsetof(struct funcnode, n);
  3716. funcstring = (char *) f + blocksize;
  3717. copynode(n);
  3718. f->count = 0;
  3719. return f;
  3720. }
  3721. /*
  3722. * Define a shell function.
  3723. */
  3724. static void
  3725. defun(char *name, union node *func)
  3726. {
  3727. struct cmdentry entry;
  3728. INTOFF;
  3729. entry.cmdtype = CMDFUNCTION;
  3730. entry.u.func = copyfunc(func);
  3731. addcmdentry(name, &entry);
  3732. INTON;
  3733. }
  3734. /*
  3735. * Delete a function if it exists.
  3736. */
  3737. static void
  3738. unsetfunc(const char *name)
  3739. {
  3740. struct tblentry *cmdp;
  3741. if ((cmdp = cmdlookup(name, 0)) != NULL &&
  3742. cmdp->cmdtype == CMDFUNCTION)
  3743. delete_cmd_entry();
  3744. }
  3745. /*
  3746. * Locate and print what a word is...
  3747. */
  3748. #ifdef CONFIG_ASH_CMDCMD
  3749. static int
  3750. describe_command(char *command, int describe_command_verbose)
  3751. #else
  3752. #define describe_command_verbose 1
  3753. static int
  3754. describe_command(char *command)
  3755. #endif
  3756. {
  3757. struct cmdentry entry;
  3758. struct tblentry *cmdp;
  3759. #ifdef CONFIG_ASH_ALIAS
  3760. const struct alias *ap;
  3761. #endif
  3762. const char *path = pathval();
  3763. if (describe_command_verbose) {
  3764. out1str(command);
  3765. }
  3766. /* First look at the keywords */
  3767. if (findkwd(command)) {
  3768. out1str(describe_command_verbose ? " is a shell keyword" : command);
  3769. goto out;
  3770. }
  3771. #ifdef CONFIG_ASH_ALIAS
  3772. /* Then look at the aliases */
  3773. if ((ap = lookupalias(command, 0)) != NULL) {
  3774. if (describe_command_verbose) {
  3775. out1fmt(" is an alias for %s", ap->val);
  3776. } else {
  3777. out1str("alias ");
  3778. printalias(ap);
  3779. return 0;
  3780. }
  3781. goto out;
  3782. }
  3783. #endif
  3784. /* Then check if it is a tracked alias */
  3785. if ((cmdp = cmdlookup(command, 0)) != NULL) {
  3786. entry.cmdtype = cmdp->cmdtype;
  3787. entry.u = cmdp->param;
  3788. } else {
  3789. /* Finally use brute force */
  3790. find_command(command, &entry, DO_ABS, path);
  3791. }
  3792. switch (entry.cmdtype) {
  3793. case CMDNORMAL: {
  3794. int j = entry.u.index;
  3795. char *p;
  3796. if (j == -1) {
  3797. p = command;
  3798. } else {
  3799. do {
  3800. p = padvance(&path, command);
  3801. stunalloc(p);
  3802. } while (--j >= 0);
  3803. }
  3804. if (describe_command_verbose) {
  3805. out1fmt(" is%s %s",
  3806. (cmdp ? " a tracked alias for" : nullstr), p
  3807. );
  3808. } else {
  3809. out1str(p);
  3810. }
  3811. break;
  3812. }
  3813. case CMDFUNCTION:
  3814. if (describe_command_verbose) {
  3815. out1str(" is a shell function");
  3816. } else {
  3817. out1str(command);
  3818. }
  3819. break;
  3820. case CMDBUILTIN:
  3821. if (describe_command_verbose) {
  3822. out1fmt(" is a %sshell builtin",
  3823. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  3824. "special " : nullstr
  3825. );
  3826. } else {
  3827. out1str(command);
  3828. }
  3829. break;
  3830. default:
  3831. if (describe_command_verbose) {
  3832. out1str(": not found\n");
  3833. }
  3834. return 127;
  3835. }
  3836. out:
  3837. outstr("\n", stdout);
  3838. return 0;
  3839. }
  3840. static int
  3841. typecmd(int argc, char **argv)
  3842. {
  3843. int i;
  3844. int err = 0;
  3845. for (i = 1; i < argc; i++) {
  3846. #ifdef CONFIG_ASH_CMDCMD
  3847. err |= describe_command(argv[i], 1);
  3848. #else
  3849. err |= describe_command(argv[i]);
  3850. #endif
  3851. }
  3852. return err;
  3853. }
  3854. #ifdef CONFIG_ASH_CMDCMD
  3855. static int
  3856. commandcmd(int argc, char **argv)
  3857. {
  3858. int c;
  3859. enum {
  3860. VERIFY_BRIEF = 1,
  3861. VERIFY_VERBOSE = 2,
  3862. } verify = 0;
  3863. while ((c = nextopt("pvV")) != '\0')
  3864. if (c == 'V')
  3865. verify |= VERIFY_VERBOSE;
  3866. else if (c == 'v')
  3867. verify |= VERIFY_BRIEF;
  3868. #if DEBUG
  3869. else if (c != 'p')
  3870. abort();
  3871. #endif
  3872. if (verify)
  3873. return describe_command(*argptr, verify - VERIFY_BRIEF);
  3874. return 0;
  3875. }
  3876. #endif
  3877. /* expand.c */
  3878. /*
  3879. * Routines to expand arguments to commands. We have to deal with
  3880. * backquotes, shell variables, and file metacharacters.
  3881. */
  3882. /*
  3883. * _rmescape() flags
  3884. */
  3885. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  3886. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  3887. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  3888. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  3889. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  3890. /*
  3891. * Structure specifying which parts of the string should be searched
  3892. * for IFS characters.
  3893. */
  3894. struct ifsregion {
  3895. struct ifsregion *next; /* next region in list */
  3896. int begoff; /* offset of start of region */
  3897. int endoff; /* offset of end of region */
  3898. int nulonly; /* search for nul bytes only */
  3899. };
  3900. /* output of current string */
  3901. static char *expdest;
  3902. /* list of back quote expressions */
  3903. static struct nodelist *argbackq;
  3904. /* first struct in list of ifs regions */
  3905. static struct ifsregion ifsfirst;
  3906. /* last struct in list */
  3907. static struct ifsregion *ifslastp;
  3908. /* holds expanded arg list */
  3909. static struct arglist exparg;
  3910. static void argstr(char *, int);
  3911. static char *exptilde(char *, char *, int);
  3912. static void expbackq(union node *, int, int);
  3913. static const char *subevalvar(char *, char *, int, int, int, int, int);
  3914. static char *evalvar(char *, int);
  3915. static void strtodest(const char *, int, int);
  3916. static void memtodest(const char *p, size_t len, int syntax, int quotes);
  3917. static ssize_t varvalue(char *, int, int);
  3918. static void recordregion(int, int, int);
  3919. static void removerecordregions(int);
  3920. static void ifsbreakup(char *, struct arglist *);
  3921. static void ifsfree(void);
  3922. static void expandmeta(struct strlist *, int);
  3923. static int patmatch(char *, const char *);
  3924. static int cvtnum(arith_t);
  3925. static size_t esclen(const char *, const char *);
  3926. static char *scanleft(char *, char *, char *, char *, int, int);
  3927. static char *scanright(char *, char *, char *, char *, int, int);
  3928. static void varunset(const char *, const char *, const char *, int)
  3929. ATTRIBUTE_NORETURN;
  3930. #define pmatch(a, b) !fnmatch((a), (b), 0)
  3931. /*
  3932. * Prepare a pattern for a expmeta (internal glob(3)) call.
  3933. *
  3934. * Returns an stalloced string.
  3935. */
  3936. static char * preglob(const char *pattern, int quoted, int flag) {
  3937. flag |= RMESCAPE_GLOB;
  3938. if (quoted) {
  3939. flag |= RMESCAPE_QUOTED;
  3940. }
  3941. return _rmescapes((char *)pattern, flag);
  3942. }
  3943. static size_t
  3944. esclen(const char *start, const char *p) {
  3945. size_t esc = 0;
  3946. while (p > start && *--p == CTLESC) {
  3947. esc++;
  3948. }
  3949. return esc;
  3950. }
  3951. /*
  3952. * Expand shell variables and backquotes inside a here document.
  3953. */
  3954. static void expandhere(union node *arg, int fd)
  3955. {
  3956. herefd = fd;
  3957. expandarg(arg, (struct arglist *)NULL, 0);
  3958. full_write(fd, stackblock(), expdest - (char *)stackblock());
  3959. }
  3960. /*
  3961. * Perform variable substitution and command substitution on an argument,
  3962. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  3963. * perform splitting and file name expansion. When arglist is NULL, perform
  3964. * here document expansion.
  3965. */
  3966. void
  3967. expandarg(union node *arg, struct arglist *arglist, int flag)
  3968. {
  3969. struct strlist *sp;
  3970. char *p;
  3971. argbackq = arg->narg.backquote;
  3972. STARTSTACKSTR(expdest);
  3973. ifsfirst.next = NULL;
  3974. ifslastp = NULL;
  3975. argstr(arg->narg.text, flag);
  3976. p = _STPUTC('\0', expdest);
  3977. expdest = p - 1;
  3978. if (arglist == NULL) {
  3979. return; /* here document expanded */
  3980. }
  3981. p = grabstackstr(p);
  3982. exparg.lastp = &exparg.list;
  3983. /*
  3984. * TODO - EXP_REDIR
  3985. */
  3986. if (flag & EXP_FULL) {
  3987. ifsbreakup(p, &exparg);
  3988. *exparg.lastp = NULL;
  3989. exparg.lastp = &exparg.list;
  3990. expandmeta(exparg.list, flag);
  3991. } else {
  3992. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  3993. rmescapes(p);
  3994. sp = (struct strlist *)stalloc(sizeof (struct strlist));
  3995. sp->text = p;
  3996. *exparg.lastp = sp;
  3997. exparg.lastp = &sp->next;
  3998. }
  3999. if (ifsfirst.next)
  4000. ifsfree();
  4001. *exparg.lastp = NULL;
  4002. if (exparg.list) {
  4003. *arglist->lastp = exparg.list;
  4004. arglist->lastp = exparg.lastp;
  4005. }
  4006. }
  4007. /*
  4008. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  4009. * characters to allow for further processing. Otherwise treat
  4010. * $@ like $* since no splitting will be performed.
  4011. */
  4012. static void
  4013. argstr(char *p, int flag)
  4014. {
  4015. static const char spclchars[] = {
  4016. '=',
  4017. ':',
  4018. CTLQUOTEMARK,
  4019. CTLENDVAR,
  4020. CTLESC,
  4021. CTLVAR,
  4022. CTLBACKQ,
  4023. CTLBACKQ | CTLQUOTE,
  4024. #ifdef CONFIG_ASH_MATH_SUPPORT
  4025. CTLENDARI,
  4026. #endif
  4027. 0
  4028. };
  4029. const char *reject = spclchars;
  4030. int c;
  4031. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  4032. int breakall = flag & EXP_WORD;
  4033. int inquotes;
  4034. size_t length;
  4035. int startloc;
  4036. if (!(flag & EXP_VARTILDE)) {
  4037. reject += 2;
  4038. } else if (flag & EXP_VARTILDE2) {
  4039. reject++;
  4040. }
  4041. inquotes = 0;
  4042. length = 0;
  4043. if (flag & EXP_TILDE) {
  4044. char *q;
  4045. flag &= ~EXP_TILDE;
  4046. tilde:
  4047. q = p;
  4048. if (*q == CTLESC && (flag & EXP_QWORD))
  4049. q++;
  4050. if (*q == '~')
  4051. p = exptilde(p, q, flag);
  4052. }
  4053. start:
  4054. startloc = expdest - (char *)stackblock();
  4055. for (;;) {
  4056. length += strcspn(p + length, reject);
  4057. c = p[length];
  4058. if (c && (!(c & 0x80)
  4059. #ifdef CONFIG_ASH_MATH_SUPPORT
  4060. || c == CTLENDARI
  4061. #endif
  4062. )) {
  4063. /* c == '=' || c == ':' || c == CTLENDARI */
  4064. length++;
  4065. }
  4066. if (length > 0) {
  4067. int newloc;
  4068. expdest = stnputs(p, length, expdest);
  4069. newloc = expdest - (char *)stackblock();
  4070. if (breakall && !inquotes && newloc > startloc) {
  4071. recordregion(startloc, newloc, 0);
  4072. }
  4073. startloc = newloc;
  4074. }
  4075. p += length + 1;
  4076. length = 0;
  4077. switch (c) {
  4078. case '\0':
  4079. goto breakloop;
  4080. case '=':
  4081. if (flag & EXP_VARTILDE2) {
  4082. p--;
  4083. continue;
  4084. }
  4085. flag |= EXP_VARTILDE2;
  4086. reject++;
  4087. /* fall through */
  4088. case ':':
  4089. /*
  4090. * sort of a hack - expand tildes in variable
  4091. * assignments (after the first '=' and after ':'s).
  4092. */
  4093. if (*--p == '~') {
  4094. goto tilde;
  4095. }
  4096. continue;
  4097. }
  4098. switch (c) {
  4099. case CTLENDVAR: /* ??? */
  4100. goto breakloop;
  4101. case CTLQUOTEMARK:
  4102. /* "$@" syntax adherence hack */
  4103. if (
  4104. !inquotes &&
  4105. !memcmp(p, dolatstr, DOLATSTRLEN) &&
  4106. (p[4] == CTLQUOTEMARK || (
  4107. p[4] == CTLENDVAR &&
  4108. p[5] == CTLQUOTEMARK
  4109. ))
  4110. ) {
  4111. p = evalvar(p + 1, flag) + 1;
  4112. goto start;
  4113. }
  4114. inquotes = !inquotes;
  4115. addquote:
  4116. if (quotes) {
  4117. p--;
  4118. length++;
  4119. startloc++;
  4120. }
  4121. break;
  4122. case CTLESC:
  4123. startloc++;
  4124. length++;
  4125. goto addquote;
  4126. case CTLVAR:
  4127. p = evalvar(p, flag);
  4128. goto start;
  4129. case CTLBACKQ:
  4130. c = 0;
  4131. case CTLBACKQ|CTLQUOTE:
  4132. expbackq(argbackq->n, c, quotes);
  4133. argbackq = argbackq->next;
  4134. goto start;
  4135. #ifdef CONFIG_ASH_MATH_SUPPORT
  4136. case CTLENDARI:
  4137. p--;
  4138. expari(quotes);
  4139. goto start;
  4140. #endif
  4141. }
  4142. }
  4143. breakloop:
  4144. ;
  4145. }
  4146. static char *
  4147. exptilde(char *startp, char *p, int flag)
  4148. {
  4149. char c;
  4150. char *name;
  4151. struct passwd *pw;
  4152. const char *home;
  4153. int quotes = flag & (EXP_FULL | EXP_CASE);
  4154. int startloc;
  4155. name = p + 1;
  4156. while ((c = *++p) != '\0') {
  4157. switch(c) {
  4158. case CTLESC:
  4159. return startp;
  4160. case CTLQUOTEMARK:
  4161. return startp;
  4162. case ':':
  4163. if (flag & EXP_VARTILDE)
  4164. goto done;
  4165. break;
  4166. case '/':
  4167. case CTLENDVAR:
  4168. goto done;
  4169. }
  4170. }
  4171. done:
  4172. *p = '\0';
  4173. if (*name == '\0') {
  4174. home = lookupvar(homestr);
  4175. } else {
  4176. if ((pw = getpwnam(name)) == NULL)
  4177. goto lose;
  4178. home = pw->pw_dir;
  4179. }
  4180. if (!home || !*home)
  4181. goto lose;
  4182. *p = c;
  4183. startloc = expdest - (char *)stackblock();
  4184. strtodest(home, SQSYNTAX, quotes);
  4185. recordregion(startloc, expdest - (char *)stackblock(), 0);
  4186. return p;
  4187. lose:
  4188. *p = c;
  4189. return startp;
  4190. }
  4191. static void
  4192. removerecordregions(int endoff)
  4193. {
  4194. if (ifslastp == NULL)
  4195. return;
  4196. if (ifsfirst.endoff > endoff) {
  4197. while (ifsfirst.next != NULL) {
  4198. struct ifsregion *ifsp;
  4199. INTOFF;
  4200. ifsp = ifsfirst.next->next;
  4201. ckfree(ifsfirst.next);
  4202. ifsfirst.next = ifsp;
  4203. INTON;
  4204. }
  4205. if (ifsfirst.begoff > endoff)
  4206. ifslastp = NULL;
  4207. else {
  4208. ifslastp = &ifsfirst;
  4209. ifsfirst.endoff = endoff;
  4210. }
  4211. return;
  4212. }
  4213. ifslastp = &ifsfirst;
  4214. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4215. ifslastp=ifslastp->next;
  4216. while (ifslastp->next != NULL) {
  4217. struct ifsregion *ifsp;
  4218. INTOFF;
  4219. ifsp = ifslastp->next->next;
  4220. ckfree(ifslastp->next);
  4221. ifslastp->next = ifsp;
  4222. INTON;
  4223. }
  4224. if (ifslastp->endoff > endoff)
  4225. ifslastp->endoff = endoff;
  4226. }
  4227. #ifdef CONFIG_ASH_MATH_SUPPORT
  4228. /*
  4229. * Expand arithmetic expression. Backup to start of expression,
  4230. * evaluate, place result in (backed up) result, adjust string position.
  4231. */
  4232. void
  4233. expari(int quotes)
  4234. {
  4235. char *p, *start;
  4236. int begoff;
  4237. int flag;
  4238. int len;
  4239. /* ifsfree(); */
  4240. /*
  4241. * This routine is slightly over-complicated for
  4242. * efficiency. Next we scan backwards looking for the
  4243. * start of arithmetic.
  4244. */
  4245. start = stackblock();
  4246. p = expdest - 1;
  4247. *p = '\0';
  4248. p--;
  4249. do {
  4250. int esc;
  4251. while (*p != CTLARI) {
  4252. p--;
  4253. #if DEBUG
  4254. if (p < start) {
  4255. sh_error("missing CTLARI (shouldn't happen)");
  4256. }
  4257. #endif
  4258. }
  4259. esc = esclen(start, p);
  4260. if (!(esc % 2)) {
  4261. break;
  4262. }
  4263. p -= esc + 1;
  4264. } while (1);
  4265. begoff = p - start;
  4266. removerecordregions(begoff);
  4267. flag = p[1];
  4268. expdest = p;
  4269. if (quotes)
  4270. rmescapes(p + 2);
  4271. len = cvtnum(dash_arith(p + 2));
  4272. if (flag != '"')
  4273. recordregion(begoff, begoff + len, 0);
  4274. }
  4275. #endif
  4276. /*
  4277. * Expand stuff in backwards quotes.
  4278. */
  4279. static void
  4280. expbackq(union node *cmd, int quoted, int quotes)
  4281. {
  4282. struct backcmd in;
  4283. int i;
  4284. char buf[128];
  4285. char *p;
  4286. char *dest;
  4287. int startloc;
  4288. int syntax = quoted? DQSYNTAX : BASESYNTAX;
  4289. struct stackmark smark;
  4290. INTOFF;
  4291. setstackmark(&smark);
  4292. dest = expdest;
  4293. startloc = dest - (char *)stackblock();
  4294. grabstackstr(dest);
  4295. evalbackcmd(cmd, (struct backcmd *) &in);
  4296. popstackmark(&smark);
  4297. p = in.buf;
  4298. i = in.nleft;
  4299. if (i == 0)
  4300. goto read;
  4301. for (;;) {
  4302. memtodest(p, i, syntax, quotes);
  4303. read:
  4304. if (in.fd < 0)
  4305. break;
  4306. i = safe_read(in.fd, buf, sizeof buf);
  4307. TRACE(("expbackq: read returns %d\n", i));
  4308. if (i <= 0)
  4309. break;
  4310. p = buf;
  4311. }
  4312. if (in.buf)
  4313. ckfree(in.buf);
  4314. if (in.fd >= 0) {
  4315. close(in.fd);
  4316. back_exitstatus = waitforjob(in.jp);
  4317. }
  4318. INTON;
  4319. /* Eat all trailing newlines */
  4320. dest = expdest;
  4321. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  4322. STUNPUTC(dest);
  4323. expdest = dest;
  4324. if (quoted == 0)
  4325. recordregion(startloc, dest - (char *)stackblock(), 0);
  4326. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  4327. (dest - (char *)stackblock()) - startloc,
  4328. (dest - (char *)stackblock()) - startloc,
  4329. stackblock() + startloc));
  4330. }
  4331. static char *
  4332. scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  4333. int zero)
  4334. {
  4335. char *loc;
  4336. char *loc2;
  4337. char c;
  4338. loc = startp;
  4339. loc2 = rmesc;
  4340. do {
  4341. int match;
  4342. const char *s = loc2;
  4343. c = *loc2;
  4344. if (zero) {
  4345. *loc2 = '\0';
  4346. s = rmesc;
  4347. }
  4348. match = pmatch(str, s);
  4349. *loc2 = c;
  4350. if (match)
  4351. return loc;
  4352. if (quotes && *loc == CTLESC)
  4353. loc++;
  4354. loc++;
  4355. loc2++;
  4356. } while (c);
  4357. return 0;
  4358. }
  4359. static char *
  4360. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  4361. int zero)
  4362. {
  4363. int esc = 0;
  4364. char *loc;
  4365. char *loc2;
  4366. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  4367. int match;
  4368. char c = *loc2;
  4369. const char *s = loc2;
  4370. if (zero) {
  4371. *loc2 = '\0';
  4372. s = rmesc;
  4373. }
  4374. match = pmatch(str, s);
  4375. *loc2 = c;
  4376. if (match)
  4377. return loc;
  4378. loc--;
  4379. if (quotes) {
  4380. if (--esc < 0) {
  4381. esc = esclen(startp, loc);
  4382. }
  4383. if (esc % 2) {
  4384. esc--;
  4385. loc--;
  4386. }
  4387. }
  4388. }
  4389. return 0;
  4390. }
  4391. static const char *
  4392. subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
  4393. {
  4394. char *startp;
  4395. char *loc;
  4396. int saveherefd = herefd;
  4397. struct nodelist *saveargbackq = argbackq;
  4398. int amount;
  4399. char *rmesc, *rmescend;
  4400. int zero;
  4401. char *(*scan)(char *, char *, char *, char *, int , int);
  4402. herefd = -1;
  4403. argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
  4404. STPUTC('\0', expdest);
  4405. herefd = saveherefd;
  4406. argbackq = saveargbackq;
  4407. startp = stackblock() + startloc;
  4408. switch (subtype) {
  4409. case VSASSIGN:
  4410. setvar(str, startp, 0);
  4411. amount = startp - expdest;
  4412. STADJUST(amount, expdest);
  4413. return startp;
  4414. case VSQUESTION:
  4415. varunset(p, str, startp, varflags);
  4416. /* NOTREACHED */
  4417. }
  4418. subtype -= VSTRIMRIGHT;
  4419. #if DEBUG
  4420. if (subtype < 0 || subtype > 3)
  4421. abort();
  4422. #endif
  4423. rmesc = startp;
  4424. rmescend = stackblock() + strloc;
  4425. if (quotes) {
  4426. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  4427. if (rmesc != startp) {
  4428. rmescend = expdest;
  4429. startp = stackblock() + startloc;
  4430. }
  4431. }
  4432. rmescend--;
  4433. str = stackblock() + strloc;
  4434. preglob(str, varflags & VSQUOTE, 0);
  4435. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  4436. zero = subtype >> 1;
  4437. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  4438. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  4439. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  4440. if (loc) {
  4441. if (zero) {
  4442. memmove(startp, loc, str - loc);
  4443. loc = startp + (str - loc) - 1;
  4444. }
  4445. *loc = '\0';
  4446. amount = loc - expdest;
  4447. STADJUST(amount, expdest);
  4448. }
  4449. return loc;
  4450. }
  4451. /*
  4452. * Expand a variable, and return a pointer to the next character in the
  4453. * input string.
  4454. */
  4455. static char *
  4456. evalvar(char *p, int flag)
  4457. {
  4458. int subtype;
  4459. int varflags;
  4460. char *var;
  4461. int patloc;
  4462. int c;
  4463. int startloc;
  4464. ssize_t varlen;
  4465. int easy;
  4466. int quotes;
  4467. int quoted;
  4468. quotes = flag & (EXP_FULL | EXP_CASE);
  4469. varflags = *p++;
  4470. subtype = varflags & VSTYPE;
  4471. quoted = varflags & VSQUOTE;
  4472. var = p;
  4473. easy = (!quoted || (*var == '@' && shellparam.nparam));
  4474. startloc = expdest - (char *)stackblock();
  4475. p = strchr(p, '=') + 1;
  4476. again:
  4477. varlen = varvalue(var, varflags, flag);
  4478. if (varflags & VSNUL)
  4479. varlen--;
  4480. if (subtype == VSPLUS) {
  4481. varlen = -1 - varlen;
  4482. goto vsplus;
  4483. }
  4484. if (subtype == VSMINUS) {
  4485. vsplus:
  4486. if (varlen < 0) {
  4487. argstr(
  4488. p, flag | EXP_TILDE |
  4489. (quoted ? EXP_QWORD : EXP_WORD)
  4490. );
  4491. goto end;
  4492. }
  4493. if (easy)
  4494. goto record;
  4495. goto end;
  4496. }
  4497. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  4498. if (varlen < 0) {
  4499. if (subevalvar(p, var, 0, subtype, startloc,
  4500. varflags, 0)) {
  4501. varflags &= ~VSNUL;
  4502. /*
  4503. * Remove any recorded regions beyond
  4504. * start of variable
  4505. */
  4506. removerecordregions(startloc);
  4507. goto again;
  4508. }
  4509. goto end;
  4510. }
  4511. if (easy)
  4512. goto record;
  4513. goto end;
  4514. }
  4515. if (varlen < 0 && uflag)
  4516. varunset(p, var, 0, 0);
  4517. if (subtype == VSLENGTH) {
  4518. cvtnum(varlen > 0 ? varlen : 0);
  4519. goto record;
  4520. }
  4521. if (subtype == VSNORMAL) {
  4522. if (!easy)
  4523. goto end;
  4524. record:
  4525. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  4526. goto end;
  4527. }
  4528. #if DEBUG
  4529. switch (subtype) {
  4530. case VSTRIMLEFT:
  4531. case VSTRIMLEFTMAX:
  4532. case VSTRIMRIGHT:
  4533. case VSTRIMRIGHTMAX:
  4534. break;
  4535. default:
  4536. abort();
  4537. }
  4538. #endif
  4539. if (varlen >= 0) {
  4540. /*
  4541. * Terminate the string and start recording the pattern
  4542. * right after it
  4543. */
  4544. STPUTC('\0', expdest);
  4545. patloc = expdest - (char *)stackblock();
  4546. if (subevalvar(p, NULL, patloc, subtype,
  4547. startloc, varflags, quotes) == 0) {
  4548. int amount = expdest - (
  4549. (char *)stackblock() + patloc - 1
  4550. );
  4551. STADJUST(-amount, expdest);
  4552. }
  4553. /* Remove any recorded regions beyond start of variable */
  4554. removerecordregions(startloc);
  4555. goto record;
  4556. }
  4557. end:
  4558. if (subtype != VSNORMAL) { /* skip to end of alternative */
  4559. int nesting = 1;
  4560. for (;;) {
  4561. if ((c = *p++) == CTLESC)
  4562. p++;
  4563. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  4564. if (varlen >= 0)
  4565. argbackq = argbackq->next;
  4566. } else if (c == CTLVAR) {
  4567. if ((*p++ & VSTYPE) != VSNORMAL)
  4568. nesting++;
  4569. } else if (c == CTLENDVAR) {
  4570. if (--nesting == 0)
  4571. break;
  4572. }
  4573. }
  4574. }
  4575. return p;
  4576. }
  4577. /*
  4578. * Put a string on the stack.
  4579. */
  4580. static void
  4581. memtodest(const char *p, size_t len, int syntax, int quotes) {
  4582. char *q = expdest;
  4583. q = makestrspace(len * 2, q);
  4584. while (len--) {
  4585. int c = SC2INT(*p++);
  4586. if (!c)
  4587. continue;
  4588. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4589. USTPUTC(CTLESC, q);
  4590. USTPUTC(c, q);
  4591. }
  4592. expdest = q;
  4593. }
  4594. static void
  4595. strtodest(const char *p, int syntax, int quotes)
  4596. {
  4597. memtodest(p, strlen(p), syntax, quotes);
  4598. }
  4599. /*
  4600. * Add the value of a specialized variable to the stack string.
  4601. */
  4602. static ssize_t
  4603. varvalue(char *name, int varflags, int flags)
  4604. {
  4605. int num;
  4606. char *p;
  4607. int i;
  4608. int sep = 0;
  4609. int sepq = 0;
  4610. ssize_t len = 0;
  4611. char **ap;
  4612. int syntax;
  4613. int quoted = varflags & VSQUOTE;
  4614. int subtype = varflags & VSTYPE;
  4615. int quotes = flags & (EXP_FULL | EXP_CASE);
  4616. if (quoted && (flags & EXP_FULL))
  4617. sep = 1 << CHAR_BIT;
  4618. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  4619. switch (*name) {
  4620. case '$':
  4621. num = rootpid;
  4622. goto numvar;
  4623. case '?':
  4624. num = exitstatus;
  4625. goto numvar;
  4626. case '#':
  4627. num = shellparam.nparam;
  4628. goto numvar;
  4629. case '!':
  4630. num = backgndpid;
  4631. if (num == 0)
  4632. return -1;
  4633. numvar:
  4634. len = cvtnum(num);
  4635. break;
  4636. case '-':
  4637. p = makestrspace(NOPTS, expdest);
  4638. for (i = NOPTS - 1; i >= 0; i--) {
  4639. if (optlist[i]) {
  4640. USTPUTC(optletters(i), p);
  4641. len++;
  4642. }
  4643. }
  4644. expdest = p;
  4645. break;
  4646. case '@':
  4647. if (sep)
  4648. goto param;
  4649. /* fall through */
  4650. case '*':
  4651. sep = ifsset() ? SC2INT(ifsval()[0]) : ' ';
  4652. if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
  4653. sepq = 1;
  4654. param:
  4655. if (!(ap = shellparam.p))
  4656. return -1;
  4657. while ((p = *ap++)) {
  4658. size_t partlen;
  4659. partlen = strlen(p);
  4660. len += partlen;
  4661. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  4662. memtodest(p, partlen, syntax, quotes);
  4663. if (*ap && sep) {
  4664. char *q;
  4665. len++;
  4666. if (subtype == VSPLUS || subtype == VSLENGTH) {
  4667. continue;
  4668. }
  4669. q = expdest;
  4670. if (sepq)
  4671. STPUTC(CTLESC, q);
  4672. STPUTC(sep, q);
  4673. expdest = q;
  4674. }
  4675. }
  4676. return len;
  4677. case '0':
  4678. case '1':
  4679. case '2':
  4680. case '3':
  4681. case '4':
  4682. case '5':
  4683. case '6':
  4684. case '7':
  4685. case '8':
  4686. case '9':
  4687. num = atoi(name);
  4688. if (num < 0 || num > shellparam.nparam)
  4689. return -1;
  4690. p = num ? shellparam.p[num - 1] : arg0;
  4691. goto value;
  4692. default:
  4693. p = lookupvar(name);
  4694. value:
  4695. if (!p)
  4696. return -1;
  4697. len = strlen(p);
  4698. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  4699. memtodest(p, len, syntax, quotes);
  4700. return len;
  4701. }
  4702. if (subtype == VSPLUS || subtype == VSLENGTH)
  4703. STADJUST(-len, expdest);
  4704. return len;
  4705. }
  4706. /*
  4707. * Record the fact that we have to scan this region of the
  4708. * string for IFS characters.
  4709. */
  4710. static void
  4711. recordregion(int start, int end, int nulonly)
  4712. {
  4713. struct ifsregion *ifsp;
  4714. if (ifslastp == NULL) {
  4715. ifsp = &ifsfirst;
  4716. } else {
  4717. INTOFF;
  4718. ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
  4719. ifsp->next = NULL;
  4720. ifslastp->next = ifsp;
  4721. INTON;
  4722. }
  4723. ifslastp = ifsp;
  4724. ifslastp->begoff = start;
  4725. ifslastp->endoff = end;
  4726. ifslastp->nulonly = nulonly;
  4727. }
  4728. /*
  4729. * Break the argument string into pieces based upon IFS and add the
  4730. * strings to the argument list. The regions of the string to be
  4731. * searched for IFS characters have been stored by recordregion.
  4732. */
  4733. static void
  4734. ifsbreakup(char *string, struct arglist *arglist)
  4735. {
  4736. struct ifsregion *ifsp;
  4737. struct strlist *sp;
  4738. char *start;
  4739. char *p;
  4740. char *q;
  4741. const char *ifs, *realifs;
  4742. int ifsspc;
  4743. int nulonly;
  4744. start = string;
  4745. if (ifslastp != NULL) {
  4746. ifsspc = 0;
  4747. nulonly = 0;
  4748. realifs = ifsset() ? ifsval() : defifs;
  4749. ifsp = &ifsfirst;
  4750. do {
  4751. p = string + ifsp->begoff;
  4752. nulonly = ifsp->nulonly;
  4753. ifs = nulonly ? nullstr : realifs;
  4754. ifsspc = 0;
  4755. while (p < string + ifsp->endoff) {
  4756. q = p;
  4757. if (*p == CTLESC)
  4758. p++;
  4759. if (strchr(ifs, *p)) {
  4760. if (!nulonly)
  4761. ifsspc = (strchr(defifs, *p) != NULL);
  4762. /* Ignore IFS whitespace at start */
  4763. if (q == start && ifsspc) {
  4764. p++;
  4765. start = p;
  4766. continue;
  4767. }
  4768. *q = '\0';
  4769. sp = (struct strlist *)stalloc(sizeof *sp);
  4770. sp->text = start;
  4771. *arglist->lastp = sp;
  4772. arglist->lastp = &sp->next;
  4773. p++;
  4774. if (!nulonly) {
  4775. for (;;) {
  4776. if (p >= string + ifsp->endoff) {
  4777. break;
  4778. }
  4779. q = p;
  4780. if (*p == CTLESC)
  4781. p++;
  4782. if (strchr(ifs, *p) == NULL ) {
  4783. p = q;
  4784. break;
  4785. } else if (strchr(defifs, *p) == NULL) {
  4786. if (ifsspc) {
  4787. p++;
  4788. ifsspc = 0;
  4789. } else {
  4790. p = q;
  4791. break;
  4792. }
  4793. } else
  4794. p++;
  4795. }
  4796. }
  4797. start = p;
  4798. } else
  4799. p++;
  4800. }
  4801. } while ((ifsp = ifsp->next) != NULL);
  4802. if (nulonly)
  4803. goto add;
  4804. }
  4805. if (!*start)
  4806. return;
  4807. add:
  4808. sp = (struct strlist *)stalloc(sizeof *sp);
  4809. sp->text = start;
  4810. *arglist->lastp = sp;
  4811. arglist->lastp = &sp->next;
  4812. }
  4813. static void
  4814. ifsfree(void)
  4815. {
  4816. struct ifsregion *p;
  4817. INTOFF;
  4818. p = ifsfirst.next;
  4819. do {
  4820. struct ifsregion *ifsp;
  4821. ifsp = p->next;
  4822. ckfree(p);
  4823. p = ifsp;
  4824. } while (p);
  4825. ifslastp = NULL;
  4826. ifsfirst.next = NULL;
  4827. INTON;
  4828. }
  4829. static void expmeta(char *, char *);
  4830. static struct strlist *expsort(struct strlist *);
  4831. static struct strlist *msort(struct strlist *, int);
  4832. static char *expdir;
  4833. static void
  4834. expandmeta(struct strlist *str, int flag)
  4835. {
  4836. static const char metachars[] = {
  4837. '*', '?', '[', 0
  4838. };
  4839. /* TODO - EXP_REDIR */
  4840. while (str) {
  4841. struct strlist **savelastp;
  4842. struct strlist *sp;
  4843. char *p;
  4844. if (fflag)
  4845. goto nometa;
  4846. if (!strpbrk(str->text, metachars))
  4847. goto nometa;
  4848. savelastp = exparg.lastp;
  4849. INTOFF;
  4850. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  4851. {
  4852. int i = strlen(str->text);
  4853. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  4854. }
  4855. expmeta(expdir, p);
  4856. ckfree(expdir);
  4857. if (p != str->text)
  4858. ckfree(p);
  4859. INTON;
  4860. if (exparg.lastp == savelastp) {
  4861. /*
  4862. * no matches
  4863. */
  4864. nometa:
  4865. *exparg.lastp = str;
  4866. rmescapes(str->text);
  4867. exparg.lastp = &str->next;
  4868. } else {
  4869. *exparg.lastp = NULL;
  4870. *savelastp = sp = expsort(*savelastp);
  4871. while (sp->next != NULL)
  4872. sp = sp->next;
  4873. exparg.lastp = &sp->next;
  4874. }
  4875. str = str->next;
  4876. }
  4877. }
  4878. /*
  4879. * Add a file name to the list.
  4880. */
  4881. static void
  4882. addfname(const char *name)
  4883. {
  4884. struct strlist *sp;
  4885. sp = (struct strlist *)stalloc(sizeof *sp);
  4886. sp->text = sstrdup(name);
  4887. *exparg.lastp = sp;
  4888. exparg.lastp = &sp->next;
  4889. }
  4890. /*
  4891. * Do metacharacter (i.e. *, ?, [...]) expansion.
  4892. */
  4893. static void
  4894. expmeta(char *enddir, char *name)
  4895. {
  4896. char *p;
  4897. const char *cp;
  4898. char *start;
  4899. char *endname;
  4900. int metaflag;
  4901. struct stat statb;
  4902. DIR *dirp;
  4903. struct dirent *dp;
  4904. int atend;
  4905. int matchdot;
  4906. metaflag = 0;
  4907. start = name;
  4908. for (p = name; *p; p++) {
  4909. if (*p == '*' || *p == '?')
  4910. metaflag = 1;
  4911. else if (*p == '[') {
  4912. char *q = p + 1;
  4913. if (*q == '!')
  4914. q++;
  4915. for (;;) {
  4916. if (*q == '\\')
  4917. q++;
  4918. if (*q == '/' || *q == '\0')
  4919. break;
  4920. if (*++q == ']') {
  4921. metaflag = 1;
  4922. break;
  4923. }
  4924. }
  4925. } else if (*p == '\\')
  4926. p++;
  4927. else if (*p == '/') {
  4928. if (metaflag)
  4929. goto out;
  4930. start = p + 1;
  4931. }
  4932. }
  4933. out:
  4934. if (metaflag == 0) { /* we've reached the end of the file name */
  4935. if (enddir != expdir)
  4936. metaflag++;
  4937. p = name;
  4938. do {
  4939. if (*p == '\\')
  4940. p++;
  4941. *enddir++ = *p;
  4942. } while (*p++);
  4943. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  4944. addfname(expdir);
  4945. return;
  4946. }
  4947. endname = p;
  4948. if (name < start) {
  4949. p = name;
  4950. do {
  4951. if (*p == '\\')
  4952. p++;
  4953. *enddir++ = *p++;
  4954. } while (p < start);
  4955. }
  4956. if (enddir == expdir) {
  4957. cp = ".";
  4958. } else if (enddir == expdir + 1 && *expdir == '/') {
  4959. cp = "/";
  4960. } else {
  4961. cp = expdir;
  4962. enddir[-1] = '\0';
  4963. }
  4964. if ((dirp = opendir(cp)) == NULL)
  4965. return;
  4966. if (enddir != expdir)
  4967. enddir[-1] = '/';
  4968. if (*endname == 0) {
  4969. atend = 1;
  4970. } else {
  4971. atend = 0;
  4972. *endname++ = '\0';
  4973. }
  4974. matchdot = 0;
  4975. p = start;
  4976. if (*p == '\\')
  4977. p++;
  4978. if (*p == '.')
  4979. matchdot++;
  4980. while (! intpending && (dp = readdir(dirp)) != NULL) {
  4981. if (dp->d_name[0] == '.' && ! matchdot)
  4982. continue;
  4983. if (pmatch(start, dp->d_name)) {
  4984. if (atend) {
  4985. scopy(dp->d_name, enddir);
  4986. addfname(expdir);
  4987. } else {
  4988. for (p = enddir, cp = dp->d_name;
  4989. (*p++ = *cp++) != '\0';)
  4990. continue;
  4991. p[-1] = '/';
  4992. expmeta(p, endname);
  4993. }
  4994. }
  4995. }
  4996. closedir(dirp);
  4997. if (! atend)
  4998. endname[-1] = '/';
  4999. }
  5000. /*
  5001. * Sort the results of file name expansion. It calculates the number of
  5002. * strings to sort and then calls msort (short for merge sort) to do the
  5003. * work.
  5004. */
  5005. static struct strlist *
  5006. expsort(struct strlist *str)
  5007. {
  5008. int len;
  5009. struct strlist *sp;
  5010. len = 0;
  5011. for (sp = str ; sp ; sp = sp->next)
  5012. len++;
  5013. return msort(str, len);
  5014. }
  5015. static struct strlist *
  5016. msort(struct strlist *list, int len)
  5017. {
  5018. struct strlist *p, *q = NULL;
  5019. struct strlist **lpp;
  5020. int half;
  5021. int n;
  5022. if (len <= 1)
  5023. return list;
  5024. half = len >> 1;
  5025. p = list;
  5026. for (n = half ; --n >= 0 ; ) {
  5027. q = p;
  5028. p = p->next;
  5029. }
  5030. q->next = NULL; /* terminate first half of list */
  5031. q = msort(list, half); /* sort first half of list */
  5032. p = msort(p, len - half); /* sort second half */
  5033. lpp = &list;
  5034. for (;;) {
  5035. #ifdef CONFIG_LOCALE_SUPPORT
  5036. if (strcoll(p->text, q->text) < 0)
  5037. #else
  5038. if (strcmp(p->text, q->text) < 0)
  5039. #endif
  5040. {
  5041. *lpp = p;
  5042. lpp = &p->next;
  5043. if ((p = *lpp) == NULL) {
  5044. *lpp = q;
  5045. break;
  5046. }
  5047. } else {
  5048. *lpp = q;
  5049. lpp = &q->next;
  5050. if ((q = *lpp) == NULL) {
  5051. *lpp = p;
  5052. break;
  5053. }
  5054. }
  5055. }
  5056. return list;
  5057. }
  5058. /*
  5059. * Returns true if the pattern matches the string.
  5060. */
  5061. static int patmatch(char *pattern, const char *string)
  5062. {
  5063. return pmatch(preglob(pattern, 0, 0), string);
  5064. }
  5065. /*
  5066. * Remove any CTLESC characters from a string.
  5067. */
  5068. static char *
  5069. _rmescapes(char *str, int flag)
  5070. {
  5071. char *p, *q, *r;
  5072. static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
  5073. unsigned inquotes;
  5074. int notescaped;
  5075. int globbing;
  5076. p = strpbrk(str, qchars);
  5077. if (!p) {
  5078. return str;
  5079. }
  5080. q = p;
  5081. r = str;
  5082. if (flag & RMESCAPE_ALLOC) {
  5083. size_t len = p - str;
  5084. size_t fulllen = len + strlen(p) + 1;
  5085. if (flag & RMESCAPE_GROW) {
  5086. r = makestrspace(fulllen, expdest);
  5087. } else if (flag & RMESCAPE_HEAP) {
  5088. r = ckmalloc(fulllen);
  5089. } else {
  5090. r = stalloc(fulllen);
  5091. }
  5092. q = r;
  5093. if (len > 0) {
  5094. q = mempcpy(q, str, len);
  5095. }
  5096. }
  5097. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  5098. globbing = flag & RMESCAPE_GLOB;
  5099. notescaped = globbing;
  5100. while (*p) {
  5101. if (*p == CTLQUOTEMARK) {
  5102. inquotes = ~inquotes;
  5103. p++;
  5104. notescaped = globbing;
  5105. continue;
  5106. }
  5107. if (*p == '\\') {
  5108. /* naked back slash */
  5109. notescaped = 0;
  5110. goto copy;
  5111. }
  5112. if (*p == CTLESC) {
  5113. p++;
  5114. if (notescaped && inquotes && *p != '/') {
  5115. *q++ = '\\';
  5116. }
  5117. }
  5118. notescaped = globbing;
  5119. copy:
  5120. *q++ = *p++;
  5121. }
  5122. *q = '\0';
  5123. if (flag & RMESCAPE_GROW) {
  5124. expdest = r;
  5125. STADJUST(q - r + 1, expdest);
  5126. }
  5127. return r;
  5128. }
  5129. /*
  5130. * See if a pattern matches in a case statement.
  5131. */
  5132. int
  5133. casematch(union node *pattern, char *val)
  5134. {
  5135. struct stackmark smark;
  5136. int result;
  5137. setstackmark(&smark);
  5138. argbackq = pattern->narg.backquote;
  5139. STARTSTACKSTR(expdest);
  5140. ifslastp = NULL;
  5141. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  5142. STACKSTRNUL(expdest);
  5143. result = patmatch(stackblock(), val);
  5144. popstackmark(&smark);
  5145. return result;
  5146. }
  5147. /*
  5148. * Our own itoa().
  5149. */
  5150. static int
  5151. cvtnum(arith_t num)
  5152. {
  5153. int len;
  5154. expdest = makestrspace(32, expdest);
  5155. #ifdef CONFIG_ASH_MATH_SUPPORT_64
  5156. len = fmtstr(expdest, 32, "%lld", (long long) num);
  5157. #else
  5158. len = fmtstr(expdest, 32, "%ld", num);
  5159. #endif
  5160. STADJUST(len, expdest);
  5161. return len;
  5162. }
  5163. static void
  5164. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5165. {
  5166. const char *msg;
  5167. const char *tail;
  5168. tail = nullstr;
  5169. msg = "parameter not set";
  5170. if (umsg) {
  5171. if (*end == CTLENDVAR) {
  5172. if (varflags & VSNUL)
  5173. tail = " or null";
  5174. } else
  5175. msg = umsg;
  5176. }
  5177. sh_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5178. }
  5179. /* input.c */
  5180. /*
  5181. * This implements the input routines used by the parser.
  5182. */
  5183. #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
  5184. static void pushfile(void);
  5185. /*
  5186. * Read a character from the script, returning PEOF on end of file.
  5187. * Nul characters in the input are silently discarded.
  5188. */
  5189. #define pgetc_as_macro() (--parsenleft >= 0? SC2INT(*parsenextc++) : preadbuffer())
  5190. #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
  5191. #define pgetc_macro() pgetc()
  5192. static int
  5193. pgetc(void)
  5194. {
  5195. return pgetc_as_macro();
  5196. }
  5197. #else
  5198. #define pgetc_macro() pgetc_as_macro()
  5199. static int
  5200. pgetc(void)
  5201. {
  5202. return pgetc_macro();
  5203. }
  5204. #endif
  5205. /*
  5206. * Same as pgetc(), but ignores PEOA.
  5207. */
  5208. #ifdef CONFIG_ASH_ALIAS
  5209. static int pgetc2(void)
  5210. {
  5211. int c;
  5212. do {
  5213. c = pgetc_macro();
  5214. } while (c == PEOA);
  5215. return c;
  5216. }
  5217. #else
  5218. static int pgetc2(void)
  5219. {
  5220. return pgetc_macro();
  5221. }
  5222. #endif
  5223. /*
  5224. * Read a line from the script.
  5225. */
  5226. static char * pfgets(char *line, int len)
  5227. {
  5228. char *p = line;
  5229. int nleft = len;
  5230. int c;
  5231. while (--nleft > 0) {
  5232. c = pgetc2();
  5233. if (c == PEOF) {
  5234. if (p == line)
  5235. return NULL;
  5236. break;
  5237. }
  5238. *p++ = c;
  5239. if (c == '\n')
  5240. break;
  5241. }
  5242. *p = '\0';
  5243. return line;
  5244. }
  5245. #ifdef CONFIG_FEATURE_COMMAND_EDITING
  5246. #ifdef CONFIG_ASH_EXPAND_PRMT
  5247. static char *cmdedit_prompt;
  5248. #else
  5249. static const char *cmdedit_prompt;
  5250. #endif
  5251. static void putprompt(const char *s)
  5252. {
  5253. #ifdef CONFIG_ASH_EXPAND_PRMT
  5254. free(cmdedit_prompt);
  5255. cmdedit_prompt = xstrdup(s);
  5256. #else
  5257. cmdedit_prompt = s;
  5258. #endif
  5259. }
  5260. #else
  5261. static void putprompt(const char *s)
  5262. {
  5263. out2str(s);
  5264. }
  5265. #endif
  5266. static int preadfd(void)
  5267. {
  5268. int nr;
  5269. char *buf = parsefile->buf;
  5270. parsenextc = buf;
  5271. retry:
  5272. #ifdef CONFIG_FEATURE_COMMAND_EDITING
  5273. if (!iflag || parsefile->fd)
  5274. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  5275. else {
  5276. #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
  5277. cmdedit_path_lookup = pathval();
  5278. #endif
  5279. nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
  5280. if(nr == 0) {
  5281. /* Ctrl+C presend */
  5282. if(trap[SIGINT]) {
  5283. buf[0] = '\n';
  5284. buf[1] = 0;
  5285. raise(SIGINT);
  5286. return 1;
  5287. }
  5288. goto retry;
  5289. }
  5290. if(nr < 0 && errno == 0) {
  5291. /* Ctrl+D presend */
  5292. nr = 0;
  5293. }
  5294. }
  5295. #else
  5296. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  5297. #endif
  5298. if (nr < 0) {
  5299. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  5300. int flags = fcntl(0, F_GETFL, 0);
  5301. if (flags >= 0 && flags & O_NONBLOCK) {
  5302. flags &=~ O_NONBLOCK;
  5303. if (fcntl(0, F_SETFL, flags) >= 0) {
  5304. out2str("sh: turning off NDELAY mode\n");
  5305. goto retry;
  5306. }
  5307. }
  5308. }
  5309. }
  5310. return nr;
  5311. }
  5312. /*
  5313. * Refill the input buffer and return the next input character:
  5314. *
  5315. * 1) If a string was pushed back on the input, pop it;
  5316. * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
  5317. * from a string so we can't refill the buffer, return EOF.
  5318. * 3) If the is more stuff in this buffer, use it else call read to fill it.
  5319. * 4) Process input up to the next newline, deleting nul characters.
  5320. */
  5321. int
  5322. preadbuffer(void)
  5323. {
  5324. char *q;
  5325. int more;
  5326. char savec;
  5327. while (parsefile->strpush) {
  5328. #ifdef CONFIG_ASH_ALIAS
  5329. if (parsenleft == -1 && parsefile->strpush->ap &&
  5330. parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
  5331. return PEOA;
  5332. }
  5333. #endif
  5334. popstring();
  5335. if (--parsenleft >= 0)
  5336. return SC2INT(*parsenextc++);
  5337. }
  5338. if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
  5339. return PEOF;
  5340. flushall();
  5341. more = parselleft;
  5342. if (more <= 0) {
  5343. again:
  5344. if ((more = preadfd()) <= 0) {
  5345. parselleft = parsenleft = EOF_NLEFT;
  5346. return PEOF;
  5347. }
  5348. }
  5349. q = parsenextc;
  5350. /* delete nul characters */
  5351. for (;;) {
  5352. int c;
  5353. more--;
  5354. c = *q;
  5355. if (!c)
  5356. memmove(q, q + 1, more);
  5357. else {
  5358. q++;
  5359. if (c == '\n') {
  5360. parsenleft = q - parsenextc - 1;
  5361. break;
  5362. }
  5363. }
  5364. if (more <= 0) {
  5365. parsenleft = q - parsenextc - 1;
  5366. if (parsenleft < 0)
  5367. goto again;
  5368. break;
  5369. }
  5370. }
  5371. parselleft = more;
  5372. savec = *q;
  5373. *q = '\0';
  5374. if (vflag) {
  5375. out2str(parsenextc);
  5376. }
  5377. *q = savec;
  5378. return SC2INT(*parsenextc++);
  5379. }
  5380. /*
  5381. * Undo the last call to pgetc. Only one character may be pushed back.
  5382. * PEOF may be pushed back.
  5383. */
  5384. void
  5385. pungetc(void)
  5386. {
  5387. parsenleft++;
  5388. parsenextc--;
  5389. }
  5390. /*
  5391. * Push a string back onto the input at this current parsefile level.
  5392. * We handle aliases this way.
  5393. */
  5394. void
  5395. pushstring(char *s, void *ap)
  5396. {
  5397. struct strpush *sp;
  5398. size_t len;
  5399. len = strlen(s);
  5400. INTOFF;
  5401. /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
  5402. if (parsefile->strpush) {
  5403. sp = ckmalloc(sizeof (struct strpush));
  5404. sp->prev = parsefile->strpush;
  5405. parsefile->strpush = sp;
  5406. } else
  5407. sp = parsefile->strpush = &(parsefile->basestrpush);
  5408. sp->prevstring = parsenextc;
  5409. sp->prevnleft = parsenleft;
  5410. #ifdef CONFIG_ASH_ALIAS
  5411. sp->ap = (struct alias *)ap;
  5412. if (ap) {
  5413. ((struct alias *)ap)->flag |= ALIASINUSE;
  5414. sp->string = s;
  5415. }
  5416. #endif
  5417. parsenextc = s;
  5418. parsenleft = len;
  5419. INTON;
  5420. }
  5421. void
  5422. popstring(void)
  5423. {
  5424. struct strpush *sp = parsefile->strpush;
  5425. INTOFF;
  5426. #ifdef CONFIG_ASH_ALIAS
  5427. if (sp->ap) {
  5428. if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
  5429. checkkwd |= CHKALIAS;
  5430. }
  5431. if (sp->string != sp->ap->val) {
  5432. ckfree(sp->string);
  5433. }
  5434. sp->ap->flag &= ~ALIASINUSE;
  5435. if (sp->ap->flag & ALIASDEAD) {
  5436. unalias(sp->ap->name);
  5437. }
  5438. }
  5439. #endif
  5440. parsenextc = sp->prevstring;
  5441. parsenleft = sp->prevnleft;
  5442. /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
  5443. parsefile->strpush = sp->prev;
  5444. if (sp != &(parsefile->basestrpush))
  5445. ckfree(sp);
  5446. INTON;
  5447. }
  5448. /*
  5449. * Set the input to take input from a file. If push is set, push the
  5450. * old input onto the stack first.
  5451. */
  5452. static int
  5453. setinputfile(const char *fname, int flags)
  5454. {
  5455. int fd;
  5456. int fd2;
  5457. INTOFF;
  5458. if ((fd = open(fname, O_RDONLY)) < 0) {
  5459. if (flags & INPUT_NOFILE_OK)
  5460. goto out;
  5461. sh_error("Can't open %s", fname);
  5462. }
  5463. if (fd < 10) {
  5464. fd2 = copyfd(fd, 10);
  5465. close(fd);
  5466. if (fd2 < 0)
  5467. sh_error("Out of file descriptors");
  5468. fd = fd2;
  5469. }
  5470. setinputfd(fd, flags & INPUT_PUSH_FILE);
  5471. out:
  5472. INTON;
  5473. return fd;
  5474. }
  5475. /*
  5476. * Like setinputfile, but takes an open file descriptor. Call this with
  5477. * interrupts off.
  5478. */
  5479. static void
  5480. setinputfd(int fd, int push)
  5481. {
  5482. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  5483. if (push) {
  5484. pushfile();
  5485. parsefile->buf = 0;
  5486. }
  5487. parsefile->fd = fd;
  5488. if (parsefile->buf == NULL)
  5489. parsefile->buf = ckmalloc(IBUFSIZ);
  5490. parselleft = parsenleft = 0;
  5491. plinno = 1;
  5492. }
  5493. /*
  5494. * Like setinputfile, but takes input from a string.
  5495. */
  5496. static void
  5497. setinputstring(char *string)
  5498. {
  5499. INTOFF;
  5500. pushfile();
  5501. parsenextc = string;
  5502. parsenleft = strlen(string);
  5503. parsefile->buf = NULL;
  5504. plinno = 1;
  5505. INTON;
  5506. }
  5507. /*
  5508. * To handle the "." command, a stack of input files is used. Pushfile
  5509. * adds a new entry to the stack and popfile restores the previous level.
  5510. */
  5511. static void
  5512. pushfile(void)
  5513. {
  5514. struct parsefile *pf;
  5515. parsefile->nleft = parsenleft;
  5516. parsefile->lleft = parselleft;
  5517. parsefile->nextc = parsenextc;
  5518. parsefile->linno = plinno;
  5519. pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
  5520. pf->prev = parsefile;
  5521. pf->fd = -1;
  5522. pf->strpush = NULL;
  5523. pf->basestrpush.prev = NULL;
  5524. parsefile = pf;
  5525. }
  5526. static void
  5527. popfile(void)
  5528. {
  5529. struct parsefile *pf = parsefile;
  5530. INTOFF;
  5531. if (pf->fd >= 0)
  5532. close(pf->fd);
  5533. if (pf->buf)
  5534. ckfree(pf->buf);
  5535. while (pf->strpush)
  5536. popstring();
  5537. parsefile = pf->prev;
  5538. ckfree(pf);
  5539. parsenleft = parsefile->nleft;
  5540. parselleft = parsefile->lleft;
  5541. parsenextc = parsefile->nextc;
  5542. plinno = parsefile->linno;
  5543. INTON;
  5544. }
  5545. /*
  5546. * Return to top level.
  5547. */
  5548. static void
  5549. popallfiles(void)
  5550. {
  5551. while (parsefile != &basepf)
  5552. popfile();
  5553. }
  5554. /*
  5555. * Close the file(s) that the shell is reading commands from. Called
  5556. * after a fork is done.
  5557. */
  5558. static void
  5559. closescript(void)
  5560. {
  5561. popallfiles();
  5562. if (parsefile->fd > 0) {
  5563. close(parsefile->fd);
  5564. parsefile->fd = 0;
  5565. }
  5566. }
  5567. /* jobs.c */
  5568. /* mode flags for set_curjob */
  5569. #define CUR_DELETE 2
  5570. #define CUR_RUNNING 1
  5571. #define CUR_STOPPED 0
  5572. /* mode flags for dowait */
  5573. #define DOWAIT_NORMAL 0
  5574. #define DOWAIT_BLOCK 1
  5575. /* array of jobs */
  5576. static struct job *jobtab;
  5577. /* size of array */
  5578. static unsigned njobs;
  5579. #if JOBS
  5580. /* pgrp of shell on invocation */
  5581. static int initialpgrp;
  5582. static int ttyfd = -1;
  5583. #endif
  5584. /* current job */
  5585. static struct job *curjob;
  5586. /* number of presumed living untracked jobs */
  5587. static int jobless;
  5588. static void set_curjob(struct job *, unsigned);
  5589. #if JOBS
  5590. static int restartjob(struct job *, int);
  5591. static void xtcsetpgrp(int, pid_t);
  5592. static char *commandtext(union node *);
  5593. static void cmdlist(union node *, int);
  5594. static void cmdtxt(union node *);
  5595. static void cmdputs(const char *);
  5596. static void showpipe(struct job *, FILE *);
  5597. #endif
  5598. static int sprint_status(char *, int, int);
  5599. static void freejob(struct job *);
  5600. static struct job *getjob(const char *, int);
  5601. static struct job *growjobtab(void);
  5602. static void forkchild(struct job *, union node *, int);
  5603. static void forkparent(struct job *, union node *, int, pid_t);
  5604. static int dowait(int, struct job *);
  5605. static int getstatus(struct job *);
  5606. static void
  5607. set_curjob(struct job *jp, unsigned mode)
  5608. {
  5609. struct job *jp1;
  5610. struct job **jpp, **curp;
  5611. /* first remove from list */
  5612. jpp = curp = &curjob;
  5613. do {
  5614. jp1 = *jpp;
  5615. if (jp1 == jp)
  5616. break;
  5617. jpp = &jp1->prev_job;
  5618. } while (1);
  5619. *jpp = jp1->prev_job;
  5620. /* Then re-insert in correct position */
  5621. jpp = curp;
  5622. switch (mode) {
  5623. default:
  5624. #if DEBUG
  5625. abort();
  5626. #endif
  5627. case CUR_DELETE:
  5628. /* job being deleted */
  5629. break;
  5630. case CUR_RUNNING:
  5631. /* newly created job or backgrounded job,
  5632. put after all stopped jobs. */
  5633. do {
  5634. jp1 = *jpp;
  5635. #if JOBS
  5636. if (!jp1 || jp1->state != JOBSTOPPED)
  5637. #endif
  5638. break;
  5639. jpp = &jp1->prev_job;
  5640. } while (1);
  5641. /* FALLTHROUGH */
  5642. #if JOBS
  5643. case CUR_STOPPED:
  5644. #endif
  5645. /* newly stopped job - becomes curjob */
  5646. jp->prev_job = *jpp;
  5647. *jpp = jp;
  5648. break;
  5649. }
  5650. }
  5651. #if JOBS
  5652. /*
  5653. * Turn job control on and off.
  5654. *
  5655. * Note: This code assumes that the third arg to ioctl is a character
  5656. * pointer, which is true on Berkeley systems but not System V. Since
  5657. * System V doesn't have job control yet, this isn't a problem now.
  5658. *
  5659. * Called with interrupts off.
  5660. */
  5661. void
  5662. setjobctl(int on)
  5663. {
  5664. int fd;
  5665. int pgrp;
  5666. if (on == jobctl || rootshell == 0)
  5667. return;
  5668. if (on) {
  5669. int ofd;
  5670. ofd = fd = open(_PATH_TTY, O_RDWR);
  5671. if (fd < 0) {
  5672. fd += 3;
  5673. while (!isatty(fd) && --fd >= 0)
  5674. ;
  5675. }
  5676. fd = fcntl(fd, F_DUPFD, 10);
  5677. close(ofd);
  5678. if (fd < 0)
  5679. goto out;
  5680. fcntl(fd, F_SETFD, FD_CLOEXEC);
  5681. do { /* while we are in the background */
  5682. if ((pgrp = tcgetpgrp(fd)) < 0) {
  5683. out:
  5684. sh_warnx("can't access tty; job control turned off");
  5685. mflag = on = 0;
  5686. goto close;
  5687. }
  5688. if (pgrp == getpgrp())
  5689. break;
  5690. killpg(0, SIGTTIN);
  5691. } while (1);
  5692. initialpgrp = pgrp;
  5693. setsignal(SIGTSTP);
  5694. setsignal(SIGTTOU);
  5695. setsignal(SIGTTIN);
  5696. pgrp = rootpid;
  5697. setpgid(0, pgrp);
  5698. xtcsetpgrp(fd, pgrp);
  5699. } else {
  5700. /* turning job control off */
  5701. fd = ttyfd;
  5702. pgrp = initialpgrp;
  5703. xtcsetpgrp(fd, pgrp);
  5704. setpgid(0, pgrp);
  5705. setsignal(SIGTSTP);
  5706. setsignal(SIGTTOU);
  5707. setsignal(SIGTTIN);
  5708. close:
  5709. close(fd);
  5710. fd = -1;
  5711. }
  5712. ttyfd = fd;
  5713. jobctl = on;
  5714. }
  5715. static int
  5716. killcmd(int argc, char **argv)
  5717. {
  5718. int signo = -1;
  5719. int list = 0;
  5720. int i;
  5721. pid_t pid;
  5722. struct job *jp;
  5723. if (argc <= 1) {
  5724. usage:
  5725. sh_error(
  5726. "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
  5727. "kill -l [exitstatus]"
  5728. );
  5729. }
  5730. if (**++argv == '-') {
  5731. signo = get_signum(*argv + 1);
  5732. if (signo < 0) {
  5733. int c;
  5734. while ((c = nextopt("ls:")) != '\0')
  5735. switch (c) {
  5736. default:
  5737. #if DEBUG
  5738. abort();
  5739. #endif
  5740. case 'l':
  5741. list = 1;
  5742. break;
  5743. case 's':
  5744. signo = get_signum(optionarg);
  5745. if (signo < 0) {
  5746. sh_error(
  5747. "invalid signal number or name: %s",
  5748. optionarg
  5749. );
  5750. }
  5751. break;
  5752. }
  5753. argv = argptr;
  5754. } else
  5755. argv++;
  5756. }
  5757. if (!list && signo < 0)
  5758. signo = SIGTERM;
  5759. if ((signo < 0 || !*argv) ^ list) {
  5760. goto usage;
  5761. }
  5762. if (list) {
  5763. const char *name;
  5764. if (!*argv) {
  5765. for (i = 1; i < NSIG; i++) {
  5766. name = get_signame(i);
  5767. if (isdigit(*name))
  5768. out1fmt(snlfmt, name);
  5769. }
  5770. return 0;
  5771. }
  5772. name = get_signame(signo);
  5773. if (isdigit(*name))
  5774. out1fmt(snlfmt, name);
  5775. else
  5776. sh_error("invalid signal number or exit status: %s", *argptr);
  5777. return 0;
  5778. }
  5779. i = 0;
  5780. do {
  5781. if (**argv == '%') {
  5782. jp = getjob(*argv, 0);
  5783. pid = -jp->ps[0].pid;
  5784. } else {
  5785. pid = **argv == '-' ?
  5786. -number(*argv + 1) : number(*argv);
  5787. }
  5788. if (kill(pid, signo) != 0) {
  5789. sh_warnx("(%d) - %m", pid);
  5790. i = 1;
  5791. }
  5792. } while (*++argv);
  5793. return i;
  5794. }
  5795. #endif /* JOBS */
  5796. #if JOBS || DEBUG
  5797. static int
  5798. jobno(const struct job *jp)
  5799. {
  5800. return jp - jobtab + 1;
  5801. }
  5802. #endif
  5803. #if JOBS
  5804. static int
  5805. fgcmd(int argc, char **argv)
  5806. {
  5807. struct job *jp;
  5808. FILE *out;
  5809. int mode;
  5810. int retval;
  5811. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  5812. nextopt(nullstr);
  5813. argv = argptr;
  5814. out = stdout;
  5815. do {
  5816. jp = getjob(*argv, 1);
  5817. if (mode == FORK_BG) {
  5818. set_curjob(jp, CUR_RUNNING);
  5819. fprintf(out, "[%d] ", jobno(jp));
  5820. }
  5821. outstr(jp->ps->cmd, out);
  5822. showpipe(jp, out);
  5823. retval = restartjob(jp, mode);
  5824. } while (*argv && *++argv);
  5825. return retval;
  5826. }
  5827. static int bgcmd(int, char **) __attribute__((__alias__("fgcmd")));
  5828. static int
  5829. restartjob(struct job *jp, int mode)
  5830. {
  5831. struct procstat *ps;
  5832. int i;
  5833. int status;
  5834. pid_t pgid;
  5835. INTOFF;
  5836. if (jp->state == JOBDONE)
  5837. goto out;
  5838. jp->state = JOBRUNNING;
  5839. pgid = jp->ps->pid;
  5840. if (mode == FORK_FG)
  5841. xtcsetpgrp(ttyfd, pgid);
  5842. killpg(pgid, SIGCONT);
  5843. ps = jp->ps;
  5844. i = jp->nprocs;
  5845. do {
  5846. if (WIFSTOPPED(ps->status)) {
  5847. ps->status = -1;
  5848. }
  5849. } while (ps++, --i);
  5850. out:
  5851. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  5852. INTON;
  5853. return status;
  5854. }
  5855. #endif
  5856. static int
  5857. sprint_status(char *s, int status, int sigonly)
  5858. {
  5859. int col;
  5860. int st;
  5861. col = 0;
  5862. if (!WIFEXITED(status)) {
  5863. #if JOBS
  5864. if (WIFSTOPPED(status))
  5865. st = WSTOPSIG(status);
  5866. else
  5867. #endif
  5868. st = WTERMSIG(status);
  5869. if (sigonly) {
  5870. if (st == SIGINT || st == SIGPIPE)
  5871. goto out;
  5872. #if JOBS
  5873. if (WIFSTOPPED(status))
  5874. goto out;
  5875. #endif
  5876. }
  5877. st &= 0x7f;
  5878. col = fmtstr(s, 32, strsignal(st));
  5879. if (WCOREDUMP(status)) {
  5880. col += fmtstr(s + col, 16, " (core dumped)");
  5881. }
  5882. } else if (!sigonly) {
  5883. st = WEXITSTATUS(status);
  5884. if (st)
  5885. col = fmtstr(s, 16, "Done(%d)", st);
  5886. else
  5887. col = fmtstr(s, 16, "Done");
  5888. }
  5889. out:
  5890. return col;
  5891. }
  5892. #if JOBS
  5893. static void
  5894. showjob(FILE *out, struct job *jp, int mode)
  5895. {
  5896. struct procstat *ps;
  5897. struct procstat *psend;
  5898. int col;
  5899. int indent;
  5900. char s[80];
  5901. ps = jp->ps;
  5902. if (mode & SHOW_PGID) {
  5903. /* just output process (group) id of pipeline */
  5904. fprintf(out, "%d\n", ps->pid);
  5905. return;
  5906. }
  5907. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  5908. indent = col;
  5909. if (jp == curjob)
  5910. s[col - 2] = '+';
  5911. else if (curjob && jp == curjob->prev_job)
  5912. s[col - 2] = '-';
  5913. if (mode & SHOW_PID)
  5914. col += fmtstr(s + col, 16, "%d ", ps->pid);
  5915. psend = ps + jp->nprocs;
  5916. if (jp->state == JOBRUNNING) {
  5917. scopy("Running", s + col);
  5918. col += strlen("Running");
  5919. } else {
  5920. int status = psend[-1].status;
  5921. #if JOBS
  5922. if (jp->state == JOBSTOPPED)
  5923. status = jp->stopstatus;
  5924. #endif
  5925. col += sprint_status(s + col, status, 0);
  5926. }
  5927. goto start;
  5928. do {
  5929. /* for each process */
  5930. col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
  5931. start:
  5932. fprintf(out, "%s%*c%s",
  5933. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  5934. );
  5935. if (!(mode & SHOW_PID)) {
  5936. showpipe(jp, out);
  5937. break;
  5938. }
  5939. if (++ps == psend) {
  5940. outcslow('\n', out);
  5941. break;
  5942. }
  5943. } while (1);
  5944. jp->changed = 0;
  5945. if (jp->state == JOBDONE) {
  5946. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  5947. freejob(jp);
  5948. }
  5949. }
  5950. static int
  5951. jobscmd(int argc, char **argv)
  5952. {
  5953. int mode, m;
  5954. FILE *out;
  5955. mode = 0;
  5956. while ((m = nextopt("lp")))
  5957. if (m == 'l')
  5958. mode = SHOW_PID;
  5959. else
  5960. mode = SHOW_PGID;
  5961. out = stdout;
  5962. argv = argptr;
  5963. if (*argv)
  5964. do
  5965. showjob(out, getjob(*argv,0), mode);
  5966. while (*++argv);
  5967. else
  5968. showjobs(out, mode);
  5969. return 0;
  5970. }
  5971. /*
  5972. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  5973. * statuses have changed since the last call to showjobs.
  5974. */
  5975. static void
  5976. showjobs(FILE *out, int mode)
  5977. {
  5978. struct job *jp;
  5979. TRACE(("showjobs(%x) called\n", mode));
  5980. /* If not even one one job changed, there is nothing to do */
  5981. while (dowait(DOWAIT_NORMAL, NULL) > 0)
  5982. continue;
  5983. for (jp = curjob; jp; jp = jp->prev_job) {
  5984. if (!(mode & SHOW_CHANGED) || jp->changed)
  5985. showjob(out, jp, mode);
  5986. }
  5987. }
  5988. #endif /* JOBS */
  5989. /*
  5990. * Mark a job structure as unused.
  5991. */
  5992. static void
  5993. freejob(struct job *jp)
  5994. {
  5995. struct procstat *ps;
  5996. int i;
  5997. INTOFF;
  5998. for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
  5999. if (ps->cmd != nullstr)
  6000. ckfree(ps->cmd);
  6001. }
  6002. if (jp->ps != &jp->ps0)
  6003. ckfree(jp->ps);
  6004. jp->used = 0;
  6005. set_curjob(jp, CUR_DELETE);
  6006. INTON;
  6007. }
  6008. static int
  6009. waitcmd(int argc, char **argv)
  6010. {
  6011. struct job *job;
  6012. int retval;
  6013. struct job *jp;
  6014. EXSIGON();
  6015. nextopt(nullstr);
  6016. retval = 0;
  6017. argv = argptr;
  6018. if (!*argv) {
  6019. /* wait for all jobs */
  6020. for (;;) {
  6021. jp = curjob;
  6022. while (1) {
  6023. if (!jp) {
  6024. /* no running procs */
  6025. goto out;
  6026. }
  6027. if (jp->state == JOBRUNNING)
  6028. break;
  6029. jp->waited = 1;
  6030. jp = jp->prev_job;
  6031. }
  6032. dowait(DOWAIT_BLOCK, 0);
  6033. }
  6034. }
  6035. retval = 127;
  6036. do {
  6037. if (**argv != '%') {
  6038. pid_t pid = number(*argv);
  6039. job = curjob;
  6040. goto start;
  6041. do {
  6042. if (job->ps[job->nprocs - 1].pid == pid)
  6043. break;
  6044. job = job->prev_job;
  6045. start:
  6046. if (!job)
  6047. goto repeat;
  6048. } while (1);
  6049. } else
  6050. job = getjob(*argv, 0);
  6051. /* loop until process terminated or stopped */
  6052. while (job->state == JOBRUNNING)
  6053. dowait(DOWAIT_BLOCK, 0);
  6054. job->waited = 1;
  6055. retval = getstatus(job);
  6056. repeat:
  6057. ;
  6058. } while (*++argv);
  6059. out:
  6060. return retval;
  6061. }
  6062. /*
  6063. * Convert a job name to a job structure.
  6064. */
  6065. static struct job *
  6066. getjob(const char *name, int getctl)
  6067. {
  6068. struct job *jp;
  6069. struct job *found;
  6070. const char *err_msg = "No such job: %s";
  6071. unsigned num;
  6072. int c;
  6073. const char *p;
  6074. char *(*match)(const char *, const char *);
  6075. jp = curjob;
  6076. p = name;
  6077. if (!p)
  6078. goto currentjob;
  6079. if (*p != '%')
  6080. goto err;
  6081. c = *++p;
  6082. if (!c)
  6083. goto currentjob;
  6084. if (!p[1]) {
  6085. if (c == '+' || c == '%') {
  6086. currentjob:
  6087. err_msg = "No current job";
  6088. goto check;
  6089. } else if (c == '-') {
  6090. if (jp)
  6091. jp = jp->prev_job;
  6092. err_msg = "No previous job";
  6093. check:
  6094. if (!jp)
  6095. goto err;
  6096. goto gotit;
  6097. }
  6098. }
  6099. if (is_number(p)) {
  6100. num = atoi(p);
  6101. if (num < njobs) {
  6102. jp = jobtab + num - 1;
  6103. if (jp->used)
  6104. goto gotit;
  6105. goto err;
  6106. }
  6107. }
  6108. match = prefix;
  6109. if (*p == '?') {
  6110. match = strstr;
  6111. p++;
  6112. }
  6113. found = 0;
  6114. while (1) {
  6115. if (!jp)
  6116. goto err;
  6117. if (match(jp->ps[0].cmd, p)) {
  6118. if (found)
  6119. goto err;
  6120. found = jp;
  6121. err_msg = "%s: ambiguous";
  6122. }
  6123. jp = jp->prev_job;
  6124. }
  6125. gotit:
  6126. #if JOBS
  6127. err_msg = "job %s not created under job control";
  6128. if (getctl && jp->jobctl == 0)
  6129. goto err;
  6130. #endif
  6131. return jp;
  6132. err:
  6133. sh_error(err_msg, name);
  6134. }
  6135. /*
  6136. * Return a new job structure.
  6137. * Called with interrupts off.
  6138. */
  6139. static struct job *
  6140. makejob(union node *node, int nprocs)
  6141. {
  6142. int i;
  6143. struct job *jp;
  6144. for (i = njobs, jp = jobtab ; ; jp++) {
  6145. if (--i < 0) {
  6146. jp = growjobtab();
  6147. break;
  6148. }
  6149. if (jp->used == 0)
  6150. break;
  6151. if (jp->state != JOBDONE || !jp->waited)
  6152. continue;
  6153. #if JOBS
  6154. if (jobctl)
  6155. continue;
  6156. #endif
  6157. freejob(jp);
  6158. break;
  6159. }
  6160. memset(jp, 0, sizeof(*jp));
  6161. #if JOBS
  6162. if (jobctl)
  6163. jp->jobctl = 1;
  6164. #endif
  6165. jp->prev_job = curjob;
  6166. curjob = jp;
  6167. jp->used = 1;
  6168. jp->ps = &jp->ps0;
  6169. if (nprocs > 1) {
  6170. jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
  6171. }
  6172. TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
  6173. jobno(jp)));
  6174. return jp;
  6175. }
  6176. static struct job *
  6177. growjobtab(void)
  6178. {
  6179. size_t len;
  6180. ptrdiff_t offset;
  6181. struct job *jp, *jq;
  6182. len = njobs * sizeof(*jp);
  6183. jq = jobtab;
  6184. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  6185. offset = (char *)jp - (char *)jq;
  6186. if (offset) {
  6187. /* Relocate pointers */
  6188. size_t l = len;
  6189. jq = (struct job *)((char *)jq + l);
  6190. while (l) {
  6191. l -= sizeof(*jp);
  6192. jq--;
  6193. #define joff(p) ((struct job *)((char *)(p) + l))
  6194. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  6195. if (xlikely(joff(jp)->ps == &jq->ps0))
  6196. jmove(joff(jp)->ps);
  6197. if (joff(jp)->prev_job)
  6198. jmove(joff(jp)->prev_job);
  6199. }
  6200. if (curjob)
  6201. jmove(curjob);
  6202. #undef joff
  6203. #undef jmove
  6204. }
  6205. njobs += 4;
  6206. jobtab = jp;
  6207. jp = (struct job *)((char *)jp + len);
  6208. jq = jp + 3;
  6209. do {
  6210. jq->used = 0;
  6211. } while (--jq >= jp);
  6212. return jp;
  6213. }
  6214. /*
  6215. * Fork off a subshell. If we are doing job control, give the subshell its
  6216. * own process group. Jp is a job structure that the job is to be added to.
  6217. * N is the command that will be evaluated by the child. Both jp and n may
  6218. * be NULL. The mode parameter can be one of the following:
  6219. * FORK_FG - Fork off a foreground process.
  6220. * FORK_BG - Fork off a background process.
  6221. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  6222. * process group even if job control is on.
  6223. *
  6224. * When job control is turned off, background processes have their standard
  6225. * input redirected to /dev/null (except for the second and later processes
  6226. * in a pipeline).
  6227. *
  6228. * Called with interrupts off.
  6229. */
  6230. static void forkchild(struct job *jp, union node *n, int mode)
  6231. {
  6232. int oldlvl;
  6233. TRACE(("Child shell %d\n", getpid()));
  6234. oldlvl = shlvl;
  6235. shlvl++;
  6236. closescript();
  6237. clear_traps();
  6238. #if JOBS
  6239. /* do job control only in root shell */
  6240. jobctl = 0;
  6241. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  6242. pid_t pgrp;
  6243. if (jp->nprocs == 0)
  6244. pgrp = getpid();
  6245. else
  6246. pgrp = jp->ps[0].pid;
  6247. /* This can fail because we are doing it in the parent also */
  6248. (void)setpgid(0, pgrp);
  6249. if (mode == FORK_FG)
  6250. xtcsetpgrp(ttyfd, pgrp);
  6251. setsignal(SIGTSTP);
  6252. setsignal(SIGTTOU);
  6253. } else
  6254. #endif
  6255. if (mode == FORK_BG) {
  6256. ignoresig(SIGINT);
  6257. ignoresig(SIGQUIT);
  6258. if (jp->nprocs == 0) {
  6259. close(0);
  6260. if (open(bb_dev_null, O_RDONLY) != 0)
  6261. sh_error("Can't open %s", bb_dev_null);
  6262. }
  6263. }
  6264. if (!oldlvl && iflag) {
  6265. setsignal(SIGINT);
  6266. setsignal(SIGQUIT);
  6267. setsignal(SIGTERM);
  6268. }
  6269. for (jp = curjob; jp; jp = jp->prev_job)
  6270. freejob(jp);
  6271. jobless = 0;
  6272. }
  6273. static void forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  6274. {
  6275. TRACE(("In parent shell: child = %d\n", pid));
  6276. if (!jp) {
  6277. while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
  6278. jobless++;
  6279. return;
  6280. }
  6281. #if JOBS
  6282. if (mode != FORK_NOJOB && jp->jobctl) {
  6283. int pgrp;
  6284. if (jp->nprocs == 0)
  6285. pgrp = pid;
  6286. else
  6287. pgrp = jp->ps[0].pid;
  6288. /* This can fail because we are doing it in the child also */
  6289. (void)setpgid(pid, pgrp);
  6290. }
  6291. #endif
  6292. if (mode == FORK_BG) {
  6293. backgndpid = pid; /* set $! */
  6294. set_curjob(jp, CUR_RUNNING);
  6295. }
  6296. if (jp) {
  6297. struct procstat *ps = &jp->ps[jp->nprocs++];
  6298. ps->pid = pid;
  6299. ps->status = -1;
  6300. ps->cmd = nullstr;
  6301. #if JOBS
  6302. if (jobctl && n)
  6303. ps->cmd = commandtext(n);
  6304. #endif
  6305. }
  6306. }
  6307. static int
  6308. forkshell(struct job *jp, union node *n, int mode)
  6309. {
  6310. int pid;
  6311. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  6312. pid = fork();
  6313. if (pid < 0) {
  6314. TRACE(("Fork failed, errno=%d", errno));
  6315. if (jp)
  6316. freejob(jp);
  6317. sh_error("Cannot fork");
  6318. }
  6319. if (pid == 0)
  6320. forkchild(jp, n, mode);
  6321. else
  6322. forkparent(jp, n, mode, pid);
  6323. return pid;
  6324. }
  6325. /*
  6326. * Wait for job to finish.
  6327. *
  6328. * Under job control we have the problem that while a child process is
  6329. * running interrupts generated by the user are sent to the child but not
  6330. * to the shell. This means that an infinite loop started by an inter-
  6331. * active user may be hard to kill. With job control turned off, an
  6332. * interactive user may place an interactive program inside a loop. If
  6333. * the interactive program catches interrupts, the user doesn't want
  6334. * these interrupts to also abort the loop. The approach we take here
  6335. * is to have the shell ignore interrupt signals while waiting for a
  6336. * foreground process to terminate, and then send itself an interrupt
  6337. * signal if the child process was terminated by an interrupt signal.
  6338. * Unfortunately, some programs want to do a bit of cleanup and then
  6339. * exit on interrupt; unless these processes terminate themselves by
  6340. * sending a signal to themselves (instead of calling exit) they will
  6341. * confuse this approach.
  6342. *
  6343. * Called with interrupts off.
  6344. */
  6345. int
  6346. waitforjob(struct job *jp)
  6347. {
  6348. int st;
  6349. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  6350. while (jp->state == JOBRUNNING) {
  6351. dowait(DOWAIT_BLOCK, jp);
  6352. }
  6353. st = getstatus(jp);
  6354. #if JOBS
  6355. if (jp->jobctl) {
  6356. xtcsetpgrp(ttyfd, rootpid);
  6357. /*
  6358. * This is truly gross.
  6359. * If we're doing job control, then we did a TIOCSPGRP which
  6360. * caused us (the shell) to no longer be in the controlling
  6361. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  6362. * intuit from the subprocess exit status whether a SIGINT
  6363. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  6364. */
  6365. if (jp->sigint)
  6366. raise(SIGINT);
  6367. }
  6368. if (jp->state == JOBDONE)
  6369. #endif
  6370. freejob(jp);
  6371. return st;
  6372. }
  6373. /*
  6374. * Do a wait system call. If job control is compiled in, we accept
  6375. * stopped processes. If block is zero, we return a value of zero
  6376. * rather than blocking.
  6377. *
  6378. * System V doesn't have a non-blocking wait system call. It does
  6379. * have a SIGCLD signal that is sent to a process when one of it's
  6380. * children dies. The obvious way to use SIGCLD would be to install
  6381. * a handler for SIGCLD which simply bumped a counter when a SIGCLD
  6382. * was received, and have waitproc bump another counter when it got
  6383. * the status of a process. Waitproc would then know that a wait
  6384. * system call would not block if the two counters were different.
  6385. * This approach doesn't work because if a process has children that
  6386. * have not been waited for, System V will send it a SIGCLD when it
  6387. * installs a signal handler for SIGCLD. What this means is that when
  6388. * a child exits, the shell will be sent SIGCLD signals continuously
  6389. * until is runs out of stack space, unless it does a wait call before
  6390. * restoring the signal handler. The code below takes advantage of
  6391. * this (mis)feature by installing a signal handler for SIGCLD and
  6392. * then checking to see whether it was called. If there are any
  6393. * children to be waited for, it will be.
  6394. *
  6395. * If neither SYSV nor BSD is defined, we don't implement nonblocking
  6396. * waits at all. In this case, the user will not be informed when
  6397. * a background process until the next time she runs a real program
  6398. * (as opposed to running a builtin command or just typing return),
  6399. * and the jobs command may give out of date information.
  6400. */
  6401. static int waitproc(int block, int *status)
  6402. {
  6403. int flags = 0;
  6404. #if JOBS
  6405. if (jobctl)
  6406. flags |= WUNTRACED;
  6407. #endif
  6408. if (block == 0)
  6409. flags |= WNOHANG;
  6410. return wait3(status, flags, (struct rusage *)NULL);
  6411. }
  6412. /*
  6413. * Wait for a process to terminate.
  6414. */
  6415. static int
  6416. dowait(int block, struct job *job)
  6417. {
  6418. int pid;
  6419. int status;
  6420. struct job *jp;
  6421. struct job *thisjob;
  6422. int state;
  6423. TRACE(("dowait(%d) called\n", block));
  6424. pid = waitproc(block, &status);
  6425. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  6426. if (pid <= 0)
  6427. return pid;
  6428. INTOFF;
  6429. thisjob = NULL;
  6430. for (jp = curjob; jp; jp = jp->prev_job) {
  6431. struct procstat *sp;
  6432. struct procstat *spend;
  6433. if (jp->state == JOBDONE)
  6434. continue;
  6435. state = JOBDONE;
  6436. spend = jp->ps + jp->nprocs;
  6437. sp = jp->ps;
  6438. do {
  6439. if (sp->pid == pid) {
  6440. TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status));
  6441. sp->status = status;
  6442. thisjob = jp;
  6443. }
  6444. if (sp->status == -1)
  6445. state = JOBRUNNING;
  6446. #if JOBS
  6447. if (state == JOBRUNNING)
  6448. continue;
  6449. if (WIFSTOPPED(sp->status)) {
  6450. jp->stopstatus = sp->status;
  6451. state = JOBSTOPPED;
  6452. }
  6453. #endif
  6454. } while (++sp < spend);
  6455. if (thisjob)
  6456. goto gotjob;
  6457. }
  6458. #if JOBS
  6459. if (!WIFSTOPPED(status))
  6460. #endif
  6461. jobless--;
  6462. goto out;
  6463. gotjob:
  6464. if (state != JOBRUNNING) {
  6465. thisjob->changed = 1;
  6466. if (thisjob->state != state) {
  6467. TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state));
  6468. thisjob->state = state;
  6469. #if JOBS
  6470. if (state == JOBSTOPPED) {
  6471. set_curjob(thisjob, CUR_STOPPED);
  6472. }
  6473. #endif
  6474. }
  6475. }
  6476. out:
  6477. INTON;
  6478. if (thisjob && thisjob == job) {
  6479. char s[48 + 1];
  6480. int len;
  6481. len = sprint_status(s, status, 1);
  6482. if (len) {
  6483. s[len] = '\n';
  6484. s[len + 1] = 0;
  6485. out2str(s);
  6486. }
  6487. }
  6488. return pid;
  6489. }
  6490. /*
  6491. * return 1 if there are stopped jobs, otherwise 0
  6492. */
  6493. int
  6494. stoppedjobs(void)
  6495. {
  6496. struct job *jp;
  6497. int retval;
  6498. retval = 0;
  6499. if (job_warning)
  6500. goto out;
  6501. jp = curjob;
  6502. if (jp && jp->state == JOBSTOPPED) {
  6503. out2str("You have stopped jobs.\n");
  6504. job_warning = 2;
  6505. retval++;
  6506. }
  6507. out:
  6508. return retval;
  6509. }
  6510. /*
  6511. * Return a string identifying a command (to be printed by the
  6512. * jobs command).
  6513. */
  6514. #if JOBS
  6515. static char *cmdnextc;
  6516. static char *
  6517. commandtext(union node *n)
  6518. {
  6519. char *name;
  6520. STARTSTACKSTR(cmdnextc);
  6521. cmdtxt(n);
  6522. name = stackblock();
  6523. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  6524. name, cmdnextc, cmdnextc));
  6525. return savestr(name);
  6526. }
  6527. static void
  6528. cmdtxt(union node *n)
  6529. {
  6530. union node *np;
  6531. struct nodelist *lp;
  6532. const char *p;
  6533. char s[2];
  6534. if (!n)
  6535. return;
  6536. switch (n->type) {
  6537. default:
  6538. #if DEBUG
  6539. abort();
  6540. #endif
  6541. case NPIPE:
  6542. lp = n->npipe.cmdlist;
  6543. for (;;) {
  6544. cmdtxt(lp->n);
  6545. lp = lp->next;
  6546. if (!lp)
  6547. break;
  6548. cmdputs(" | ");
  6549. }
  6550. break;
  6551. case NSEMI:
  6552. p = "; ";
  6553. goto binop;
  6554. case NAND:
  6555. p = " && ";
  6556. goto binop;
  6557. case NOR:
  6558. p = " || ";
  6559. binop:
  6560. cmdtxt(n->nbinary.ch1);
  6561. cmdputs(p);
  6562. n = n->nbinary.ch2;
  6563. goto donode;
  6564. case NREDIR:
  6565. case NBACKGND:
  6566. n = n->nredir.n;
  6567. goto donode;
  6568. case NNOT:
  6569. cmdputs("!");
  6570. n = n->nnot.com;
  6571. donode:
  6572. cmdtxt(n);
  6573. break;
  6574. case NIF:
  6575. cmdputs("if ");
  6576. cmdtxt(n->nif.test);
  6577. cmdputs("; then ");
  6578. n = n->nif.ifpart;
  6579. if (n->nif.elsepart) {
  6580. cmdtxt(n);
  6581. cmdputs("; else ");
  6582. n = n->nif.elsepart;
  6583. }
  6584. p = "; fi";
  6585. goto dotail;
  6586. case NSUBSHELL:
  6587. cmdputs("(");
  6588. n = n->nredir.n;
  6589. p = ")";
  6590. goto dotail;
  6591. case NWHILE:
  6592. p = "while ";
  6593. goto until;
  6594. case NUNTIL:
  6595. p = "until ";
  6596. until:
  6597. cmdputs(p);
  6598. cmdtxt(n->nbinary.ch1);
  6599. n = n->nbinary.ch2;
  6600. p = "; done";
  6601. dodo:
  6602. cmdputs("; do ");
  6603. dotail:
  6604. cmdtxt(n);
  6605. goto dotail2;
  6606. case NFOR:
  6607. cmdputs("for ");
  6608. cmdputs(n->nfor.var);
  6609. cmdputs(" in ");
  6610. cmdlist(n->nfor.args, 1);
  6611. n = n->nfor.body;
  6612. p = "; done";
  6613. goto dodo;
  6614. case NDEFUN:
  6615. cmdputs(n->narg.text);
  6616. p = "() { ... }";
  6617. goto dotail2;
  6618. case NCMD:
  6619. cmdlist(n->ncmd.args, 1);
  6620. cmdlist(n->ncmd.redirect, 0);
  6621. break;
  6622. case NARG:
  6623. p = n->narg.text;
  6624. dotail2:
  6625. cmdputs(p);
  6626. break;
  6627. case NHERE:
  6628. case NXHERE:
  6629. p = "<<...";
  6630. goto dotail2;
  6631. case NCASE:
  6632. cmdputs("case ");
  6633. cmdputs(n->ncase.expr->narg.text);
  6634. cmdputs(" in ");
  6635. for (np = n->ncase.cases; np; np = np->nclist.next) {
  6636. cmdtxt(np->nclist.pattern);
  6637. cmdputs(") ");
  6638. cmdtxt(np->nclist.body);
  6639. cmdputs(";; ");
  6640. }
  6641. p = "esac";
  6642. goto dotail2;
  6643. case NTO:
  6644. p = ">";
  6645. goto redir;
  6646. case NCLOBBER:
  6647. p = ">|";
  6648. goto redir;
  6649. case NAPPEND:
  6650. p = ">>";
  6651. goto redir;
  6652. case NTOFD:
  6653. p = ">&";
  6654. goto redir;
  6655. case NFROM:
  6656. p = "<";
  6657. goto redir;
  6658. case NFROMFD:
  6659. p = "<&";
  6660. goto redir;
  6661. case NFROMTO:
  6662. p = "<>";
  6663. redir:
  6664. s[0] = n->nfile.fd + '0';
  6665. s[1] = '\0';
  6666. cmdputs(s);
  6667. cmdputs(p);
  6668. if (n->type == NTOFD || n->type == NFROMFD) {
  6669. s[0] = n->ndup.dupfd + '0';
  6670. p = s;
  6671. goto dotail2;
  6672. } else {
  6673. n = n->nfile.fname;
  6674. goto donode;
  6675. }
  6676. }
  6677. }
  6678. static void
  6679. cmdlist(union node *np, int sep)
  6680. {
  6681. for (; np; np = np->narg.next) {
  6682. if (!sep)
  6683. cmdputs(spcstr);
  6684. cmdtxt(np);
  6685. if (sep && np->narg.next)
  6686. cmdputs(spcstr);
  6687. }
  6688. }
  6689. static void
  6690. cmdputs(const char *s)
  6691. {
  6692. const char *p, *str;
  6693. char c, cc[2] = " ";
  6694. char *nextc;
  6695. int subtype = 0;
  6696. int quoted = 0;
  6697. static const char vstype[VSTYPE + 1][4] = {
  6698. "", "}", "-", "+", "?", "=",
  6699. "%", "%%", "#", "##"
  6700. };
  6701. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  6702. p = s;
  6703. while ((c = *p++) != 0) {
  6704. str = 0;
  6705. switch (c) {
  6706. case CTLESC:
  6707. c = *p++;
  6708. break;
  6709. case CTLVAR:
  6710. subtype = *p++;
  6711. if ((subtype & VSTYPE) == VSLENGTH)
  6712. str = "${#";
  6713. else
  6714. str = "${";
  6715. if (!(subtype & VSQUOTE) != !(quoted & 1)) {
  6716. quoted ^= 1;
  6717. c = '"';
  6718. } else
  6719. goto dostr;
  6720. break;
  6721. case CTLENDVAR:
  6722. str = "\"}" + !(quoted & 1);
  6723. quoted >>= 1;
  6724. subtype = 0;
  6725. goto dostr;
  6726. case CTLBACKQ:
  6727. str = "$(...)";
  6728. goto dostr;
  6729. case CTLBACKQ+CTLQUOTE:
  6730. str = "\"$(...)\"";
  6731. goto dostr;
  6732. #ifdef CONFIG_ASH_MATH_SUPPORT
  6733. case CTLARI:
  6734. str = "$((";
  6735. goto dostr;
  6736. case CTLENDARI:
  6737. str = "))";
  6738. goto dostr;
  6739. #endif
  6740. case CTLQUOTEMARK:
  6741. quoted ^= 1;
  6742. c = '"';
  6743. break;
  6744. case '=':
  6745. if (subtype == 0)
  6746. break;
  6747. if ((subtype & VSTYPE) != VSNORMAL)
  6748. quoted <<= 1;
  6749. str = vstype[subtype & VSTYPE];
  6750. if (subtype & VSNUL)
  6751. c = ':';
  6752. else
  6753. goto checkstr;
  6754. break;
  6755. case '\'':
  6756. case '\\':
  6757. case '"':
  6758. case '$':
  6759. /* These can only happen inside quotes */
  6760. cc[0] = c;
  6761. str = cc;
  6762. c = '\\';
  6763. break;
  6764. default:
  6765. break;
  6766. }
  6767. USTPUTC(c, nextc);
  6768. checkstr:
  6769. if (!str)
  6770. continue;
  6771. dostr:
  6772. while ((c = *str++)) {
  6773. USTPUTC(c, nextc);
  6774. }
  6775. }
  6776. if (quoted & 1) {
  6777. USTPUTC('"', nextc);
  6778. }
  6779. *nextc = 0;
  6780. cmdnextc = nextc;
  6781. }
  6782. static void
  6783. showpipe(struct job *jp, FILE *out)
  6784. {
  6785. struct procstat *sp;
  6786. struct procstat *spend;
  6787. spend = jp->ps + jp->nprocs;
  6788. for (sp = jp->ps + 1; sp < spend; sp++)
  6789. fprintf(out, " | %s", sp->cmd);
  6790. outcslow('\n', out);
  6791. flushall();
  6792. }
  6793. static void
  6794. xtcsetpgrp(int fd, pid_t pgrp)
  6795. {
  6796. if (tcsetpgrp(fd, pgrp))
  6797. sh_error("Cannot set tty process group (%m)");
  6798. }
  6799. #endif /* JOBS */
  6800. static int
  6801. getstatus(struct job *job) {
  6802. int status;
  6803. int retval;
  6804. status = job->ps[job->nprocs - 1].status;
  6805. retval = WEXITSTATUS(status);
  6806. if (!WIFEXITED(status)) {
  6807. #if JOBS
  6808. retval = WSTOPSIG(status);
  6809. if (!WIFSTOPPED(status))
  6810. #endif
  6811. {
  6812. /* XXX: limits number of signals */
  6813. retval = WTERMSIG(status);
  6814. #if JOBS
  6815. if (retval == SIGINT)
  6816. job->sigint = 1;
  6817. #endif
  6818. }
  6819. retval += 128;
  6820. }
  6821. TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
  6822. jobno(job), job->nprocs, status, retval));
  6823. return retval;
  6824. }
  6825. #ifdef CONFIG_ASH_MAIL
  6826. /* mail.c */
  6827. /*
  6828. * Routines to check for mail. (Perhaps make part of main.c?)
  6829. */
  6830. #define MAXMBOXES 10
  6831. /* times of mailboxes */
  6832. static time_t mailtime[MAXMBOXES];
  6833. /* Set if MAIL or MAILPATH is changed. */
  6834. static int mail_var_path_changed;
  6835. /*
  6836. * Print appropriate message(s) if mail has arrived.
  6837. * If mail_var_path_changed is set,
  6838. * then the value of MAIL has mail_var_path_changed,
  6839. * so we just update the values.
  6840. */
  6841. static void
  6842. chkmail(void)
  6843. {
  6844. const char *mpath;
  6845. char *p;
  6846. char *q;
  6847. time_t *mtp;
  6848. struct stackmark smark;
  6849. struct stat statb;
  6850. setstackmark(&smark);
  6851. mpath = mpathset() ? mpathval() : mailval();
  6852. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  6853. p = padvance(&mpath, nullstr);
  6854. if (p == NULL)
  6855. break;
  6856. if (*p == '\0')
  6857. continue;
  6858. for (q = p ; *q ; q++);
  6859. #if DEBUG
  6860. if (q[-1] != '/')
  6861. abort();
  6862. #endif
  6863. q[-1] = '\0'; /* delete trailing '/' */
  6864. if (stat(p, &statb) < 0) {
  6865. *mtp = 0;
  6866. continue;
  6867. }
  6868. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  6869. fprintf(
  6870. stderr, snlfmt,
  6871. pathopt ? pathopt : "you have mail"
  6872. );
  6873. }
  6874. *mtp = statb.st_mtime;
  6875. }
  6876. mail_var_path_changed = 0;
  6877. popstackmark(&smark);
  6878. }
  6879. static void
  6880. changemail(const char *val)
  6881. {
  6882. mail_var_path_changed++;
  6883. }
  6884. #endif /* CONFIG_ASH_MAIL */
  6885. /* main.c */
  6886. #if PROFILE
  6887. static short profile_buf[16384];
  6888. extern int etext();
  6889. #endif
  6890. static int isloginsh;
  6891. static void read_profile(const char *);
  6892. /*
  6893. * Main routine. We initialize things, parse the arguments, execute
  6894. * profiles if we're a login shell, and then call cmdloop to execute
  6895. * commands. The setjmp call sets up the location to jump to when an
  6896. * exception occurs. When an exception occurs the variable "state"
  6897. * is used to figure out how far we had gotten.
  6898. */
  6899. int
  6900. ash_main(int argc, char **argv)
  6901. {
  6902. char *shinit;
  6903. volatile int state;
  6904. struct jmploc jmploc;
  6905. struct stackmark smark;
  6906. #ifdef __GLIBC__
  6907. dash_errno = __errno_location();
  6908. #endif
  6909. #if PROFILE
  6910. monitor(4, etext, profile_buf, sizeof profile_buf, 50);
  6911. #endif
  6912. state = 0;
  6913. if (setjmp(jmploc.loc)) {
  6914. int e;
  6915. int s;
  6916. reset();
  6917. e = exception;
  6918. if (e == EXERROR)
  6919. exitstatus = 2;
  6920. s = state;
  6921. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  6922. exitshell();
  6923. if (e == EXINT) {
  6924. outcslow('\n', stderr);
  6925. }
  6926. popstackmark(&smark);
  6927. FORCEINTON; /* enable interrupts */
  6928. if (s == 1)
  6929. goto state1;
  6930. else if (s == 2)
  6931. goto state2;
  6932. else if (s == 3)
  6933. goto state3;
  6934. else
  6935. goto state4;
  6936. }
  6937. handler = &jmploc;
  6938. #if DEBUG
  6939. opentrace();
  6940. trputs("Shell args: "); trargs(argv);
  6941. #endif
  6942. rootpid = getpid();
  6943. #ifdef CONFIG_ASH_RANDOM_SUPPORT
  6944. rseed = rootpid + ((time_t)time((time_t *)0));
  6945. #endif
  6946. init();
  6947. setstackmark(&smark);
  6948. procargs(argc, argv);
  6949. #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
  6950. if ( iflag ) {
  6951. const char *hp = lookupvar("HISTFILE");
  6952. if(hp == NULL ) {
  6953. hp = lookupvar("HOME");
  6954. if(hp != NULL) {
  6955. char *defhp = concat_path_file(hp, ".ash_history");
  6956. setvar("HISTFILE", defhp, 0);
  6957. free(defhp);
  6958. }
  6959. }
  6960. }
  6961. #endif
  6962. if (argv[0] && argv[0][0] == '-')
  6963. isloginsh = 1;
  6964. if (isloginsh) {
  6965. state = 1;
  6966. read_profile("/etc/profile");
  6967. state1:
  6968. state = 2;
  6969. read_profile(".profile");
  6970. }
  6971. state2:
  6972. state = 3;
  6973. if (
  6974. #ifndef linux
  6975. getuid() == geteuid() && getgid() == getegid() &&
  6976. #endif
  6977. iflag
  6978. ) {
  6979. if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
  6980. read_profile(shinit);
  6981. }
  6982. }
  6983. state3:
  6984. state = 4;
  6985. if (minusc)
  6986. evalstring(minusc, 0);
  6987. if (sflag || minusc == NULL) {
  6988. #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
  6989. if ( iflag ) {
  6990. const char *hp = lookupvar("HISTFILE");
  6991. if(hp != NULL )
  6992. load_history ( hp );
  6993. }
  6994. #endif
  6995. state4: /* XXX ??? - why isn't this before the "if" statement */
  6996. cmdloop(1);
  6997. }
  6998. #if PROFILE
  6999. monitor(0);
  7000. #endif
  7001. #ifdef GPROF
  7002. {
  7003. extern void _mcleanup(void);
  7004. _mcleanup();
  7005. }
  7006. #endif
  7007. exitshell();
  7008. /* NOTREACHED */
  7009. }
  7010. /*
  7011. * Read and execute commands. "Top" is nonzero for the top level command
  7012. * loop; it turns on prompting if the shell is interactive.
  7013. */
  7014. static int
  7015. cmdloop(int top)
  7016. {
  7017. union node *n;
  7018. struct stackmark smark;
  7019. int inter;
  7020. int numeof = 0;
  7021. TRACE(("cmdloop(%d) called\n", top));
  7022. for (;;) {
  7023. int skip;
  7024. setstackmark(&smark);
  7025. #if JOBS
  7026. if (jobctl)
  7027. showjobs(stderr, SHOW_CHANGED);
  7028. #endif
  7029. inter = 0;
  7030. if (iflag && top) {
  7031. inter++;
  7032. #ifdef CONFIG_ASH_MAIL
  7033. chkmail();
  7034. #endif
  7035. }
  7036. n = parsecmd(inter);
  7037. /* showtree(n); DEBUG */
  7038. if (n == NEOF) {
  7039. if (!top || numeof >= 50)
  7040. break;
  7041. if (!stoppedjobs()) {
  7042. if (!Iflag)
  7043. break;
  7044. out2str("\nUse \"exit\" to leave shell.\n");
  7045. }
  7046. numeof++;
  7047. } else if (nflag == 0) {
  7048. job_warning = (job_warning == 2) ? 1 : 0;
  7049. numeof = 0;
  7050. evaltree(n, 0);
  7051. }
  7052. popstackmark(&smark);
  7053. skip = evalskip;
  7054. if (skip) {
  7055. evalskip = 0;
  7056. return skip & SKIPEVAL;
  7057. }
  7058. }
  7059. return 0;
  7060. }
  7061. /*
  7062. * Read /etc/profile or .profile. Return on error.
  7063. */
  7064. static void
  7065. read_profile(const char *name)
  7066. {
  7067. int skip;
  7068. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  7069. return;
  7070. skip = cmdloop(0);
  7071. popfile();
  7072. if (skip)
  7073. exitshell();
  7074. }
  7075. /*
  7076. * Read a file containing shell functions.
  7077. */
  7078. static void
  7079. readcmdfile(char *name)
  7080. {
  7081. setinputfile(name, INPUT_PUSH_FILE);
  7082. cmdloop(0);
  7083. popfile();
  7084. }
  7085. /*
  7086. * Take commands from a file. To be compatible we should do a path
  7087. * search for the file, which is necessary to find sub-commands.
  7088. */
  7089. static char * find_dot_file(char *name)
  7090. {
  7091. char *fullname;
  7092. const char *path = pathval();
  7093. struct stat statb;
  7094. /* don't try this for absolute or relative paths */
  7095. if (strchr(name, '/'))
  7096. return name;
  7097. while ((fullname = padvance(&path, name)) != NULL) {
  7098. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  7099. /*
  7100. * Don't bother freeing here, since it will
  7101. * be freed by the caller.
  7102. */
  7103. return fullname;
  7104. }
  7105. stunalloc(fullname);
  7106. }
  7107. /* not found in the PATH */
  7108. sh_error(not_found_msg, name);
  7109. /* NOTREACHED */
  7110. }
  7111. static int dotcmd(int argc, char **argv)
  7112. {
  7113. struct strlist *sp;
  7114. volatile struct shparam saveparam;
  7115. int status = 0;
  7116. for (sp = cmdenviron; sp; sp = sp->next)
  7117. setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  7118. if (argc >= 2) { /* That's what SVR2 does */
  7119. char *fullname;
  7120. fullname = find_dot_file(argv[1]);
  7121. if (argc > 2) {
  7122. saveparam = shellparam;
  7123. shellparam.malloc = 0;
  7124. shellparam.nparam = argc - 2;
  7125. shellparam.p = argv + 2;
  7126. };
  7127. setinputfile(fullname, INPUT_PUSH_FILE);
  7128. commandname = fullname;
  7129. cmdloop(0);
  7130. popfile();
  7131. if (argc > 2) {
  7132. freeparam(&shellparam);
  7133. shellparam = saveparam;
  7134. };
  7135. status = exitstatus;
  7136. }
  7137. return status;
  7138. }
  7139. static int
  7140. exitcmd(int argc, char **argv)
  7141. {
  7142. if (stoppedjobs())
  7143. return 0;
  7144. if (argc > 1)
  7145. exitstatus = number(argv[1]);
  7146. exraise(EXEXIT);
  7147. /* NOTREACHED */
  7148. }
  7149. #ifdef CONFIG_ASH_BUILTIN_ECHO
  7150. static int
  7151. echocmd(int argc, char **argv)
  7152. {
  7153. return bb_echo(argc, argv);
  7154. }
  7155. #endif
  7156. #ifdef CONFIG_ASH_BUILTIN_TEST
  7157. static int
  7158. testcmd(int argc, char **argv)
  7159. {
  7160. return bb_test(argc, argv);
  7161. }
  7162. #endif
  7163. /* memalloc.c */
  7164. /*
  7165. * Same for malloc, realloc, but returns an error when out of space.
  7166. */
  7167. static pointer
  7168. ckrealloc(pointer p, size_t nbytes)
  7169. {
  7170. p = realloc(p, nbytes);
  7171. if (p == NULL)
  7172. sh_error(bb_msg_memory_exhausted);
  7173. return p;
  7174. }
  7175. static pointer
  7176. ckmalloc(size_t nbytes)
  7177. {
  7178. return ckrealloc(NULL, nbytes);
  7179. }
  7180. /*
  7181. * Make a copy of a string in safe storage.
  7182. */
  7183. static char *
  7184. savestr(const char *s)
  7185. {
  7186. char *p = strdup(s);
  7187. if (!p)
  7188. sh_error(bb_msg_memory_exhausted);
  7189. return p;
  7190. }
  7191. /*
  7192. * Parse trees for commands are allocated in lifo order, so we use a stack
  7193. * to make this more efficient, and also to avoid all sorts of exception
  7194. * handling code to handle interrupts in the middle of a parse.
  7195. *
  7196. * The size 504 was chosen because the Ultrix malloc handles that size
  7197. * well.
  7198. */
  7199. static pointer
  7200. stalloc(size_t nbytes)
  7201. {
  7202. char *p;
  7203. size_t aligned;
  7204. aligned = SHELL_ALIGN(nbytes);
  7205. if (aligned > stacknleft) {
  7206. size_t len;
  7207. size_t blocksize;
  7208. struct stack_block *sp;
  7209. blocksize = aligned;
  7210. if (blocksize < MINSIZE)
  7211. blocksize = MINSIZE;
  7212. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  7213. if (len < blocksize)
  7214. sh_error(bb_msg_memory_exhausted);
  7215. INTOFF;
  7216. sp = ckmalloc(len);
  7217. sp->prev = stackp;
  7218. stacknxt = sp->space;
  7219. stacknleft = blocksize;
  7220. sstrend = stacknxt + blocksize;
  7221. stackp = sp;
  7222. INTON;
  7223. }
  7224. p = stacknxt;
  7225. stacknxt += aligned;
  7226. stacknleft -= aligned;
  7227. return p;
  7228. }
  7229. void
  7230. stunalloc(pointer p)
  7231. {
  7232. #if DEBUG
  7233. if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
  7234. write(2, "stunalloc\n", 10);
  7235. abort();
  7236. }
  7237. #endif
  7238. stacknleft += stacknxt - (char *)p;
  7239. stacknxt = p;
  7240. }
  7241. void
  7242. setstackmark(struct stackmark *mark)
  7243. {
  7244. mark->stackp = stackp;
  7245. mark->stacknxt = stacknxt;
  7246. mark->stacknleft = stacknleft;
  7247. mark->marknext = markp;
  7248. markp = mark;
  7249. }
  7250. void
  7251. popstackmark(struct stackmark *mark)
  7252. {
  7253. struct stack_block *sp;
  7254. INTOFF;
  7255. markp = mark->marknext;
  7256. while (stackp != mark->stackp) {
  7257. sp = stackp;
  7258. stackp = sp->prev;
  7259. ckfree(sp);
  7260. }
  7261. stacknxt = mark->stacknxt;
  7262. stacknleft = mark->stacknleft;
  7263. sstrend = mark->stacknxt + mark->stacknleft;
  7264. INTON;
  7265. }
  7266. /*
  7267. * When the parser reads in a string, it wants to stick the string on the
  7268. * stack and only adjust the stack pointer when it knows how big the
  7269. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  7270. * of space on top of the stack and stackblocklen returns the length of
  7271. * this block. Growstackblock will grow this space by at least one byte,
  7272. * possibly moving it (like realloc). Grabstackblock actually allocates the
  7273. * part of the block that has been used.
  7274. */
  7275. void
  7276. growstackblock(void)
  7277. {
  7278. size_t newlen;
  7279. newlen = stacknleft * 2;
  7280. if (newlen < stacknleft)
  7281. sh_error(bb_msg_memory_exhausted);
  7282. if (newlen < 128)
  7283. newlen += 128;
  7284. if (stacknxt == stackp->space && stackp != &stackbase) {
  7285. struct stack_block *oldstackp;
  7286. struct stackmark *xmark;
  7287. struct stack_block *sp;
  7288. struct stack_block *prevstackp;
  7289. size_t grosslen;
  7290. INTOFF;
  7291. oldstackp = stackp;
  7292. sp = stackp;
  7293. prevstackp = sp->prev;
  7294. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  7295. sp = ckrealloc((pointer)sp, grosslen);
  7296. sp->prev = prevstackp;
  7297. stackp = sp;
  7298. stacknxt = sp->space;
  7299. stacknleft = newlen;
  7300. sstrend = sp->space + newlen;
  7301. /*
  7302. * Stack marks pointing to the start of the old block
  7303. * must be relocated to point to the new block
  7304. */
  7305. xmark = markp;
  7306. while (xmark != NULL && xmark->stackp == oldstackp) {
  7307. xmark->stackp = stackp;
  7308. xmark->stacknxt = stacknxt;
  7309. xmark->stacknleft = stacknleft;
  7310. xmark = xmark->marknext;
  7311. }
  7312. INTON;
  7313. } else {
  7314. char *oldspace = stacknxt;
  7315. int oldlen = stacknleft;
  7316. char *p = stalloc(newlen);
  7317. /* free the space we just allocated */
  7318. stacknxt = memcpy(p, oldspace, oldlen);
  7319. stacknleft += newlen;
  7320. }
  7321. }
  7322. static void grabstackblock(size_t len)
  7323. {
  7324. len = SHELL_ALIGN(len);
  7325. stacknxt += len;
  7326. stacknleft -= len;
  7327. }
  7328. /*
  7329. * The following routines are somewhat easier to use than the above.
  7330. * The user declares a variable of type STACKSTR, which may be declared
  7331. * to be a register. The macro STARTSTACKSTR initializes things. Then
  7332. * the user uses the macro STPUTC to add characters to the string. In
  7333. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  7334. * grown as necessary. When the user is done, she can just leave the
  7335. * string there and refer to it using stackblock(). Or she can allocate
  7336. * the space for it using grabstackstr(). If it is necessary to allow
  7337. * someone else to use the stack temporarily and then continue to grow
  7338. * the string, the user should use grabstack to allocate the space, and
  7339. * then call ungrabstr(p) to return to the previous mode of operation.
  7340. *
  7341. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  7342. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  7343. * is space for at least one character.
  7344. */
  7345. void *
  7346. growstackstr(void)
  7347. {
  7348. size_t len = stackblocksize();
  7349. if (herefd >= 0 && len >= 1024) {
  7350. full_write(herefd, stackblock(), len);
  7351. return stackblock();
  7352. }
  7353. growstackblock();
  7354. return stackblock() + len;
  7355. }
  7356. /*
  7357. * Called from CHECKSTRSPACE.
  7358. */
  7359. char *
  7360. makestrspace(size_t newlen, char *p)
  7361. {
  7362. size_t len = p - stacknxt;
  7363. size_t size = stackblocksize();
  7364. for (;;) {
  7365. size_t nleft;
  7366. size = stackblocksize();
  7367. nleft = size - len;
  7368. if (nleft >= newlen)
  7369. break;
  7370. growstackblock();
  7371. }
  7372. return stackblock() + len;
  7373. }
  7374. char *
  7375. stnputs(const char *s, size_t n, char *p)
  7376. {
  7377. p = makestrspace(n, p);
  7378. p = mempcpy(p, s, n);
  7379. return p;
  7380. }
  7381. char *
  7382. stputs(const char *s, char *p)
  7383. {
  7384. return stnputs(s, strlen(s), p);
  7385. }
  7386. /* mystring.c */
  7387. /*
  7388. * String functions.
  7389. *
  7390. * number(s) Convert a string of digits to an integer.
  7391. * is_number(s) Return true if s is a string of digits.
  7392. */
  7393. /*
  7394. * prefix -- see if pfx is a prefix of string.
  7395. */
  7396. char *
  7397. prefix(const char *string, const char *pfx)
  7398. {
  7399. while (*pfx) {
  7400. if (*pfx++ != *string++)
  7401. return 0;
  7402. }
  7403. return (char *) string;
  7404. }
  7405. /*
  7406. * Convert a string of digits to an integer, printing an error message on
  7407. * failure.
  7408. */
  7409. int
  7410. number(const char *s)
  7411. {
  7412. if (! is_number(s))
  7413. sh_error(illnum, s);
  7414. return atoi(s);
  7415. }
  7416. /*
  7417. * Check for a valid number. This should be elsewhere.
  7418. */
  7419. int
  7420. is_number(const char *p)
  7421. {
  7422. do {
  7423. if (! is_digit(*p))
  7424. return 0;
  7425. } while (*++p != '\0');
  7426. return 1;
  7427. }
  7428. /*
  7429. * Produce a possibly single quoted string suitable as input to the shell.
  7430. * The return string is allocated on the stack.
  7431. */
  7432. char *
  7433. single_quote(const char *s) {
  7434. char *p;
  7435. STARTSTACKSTR(p);
  7436. do {
  7437. char *q;
  7438. size_t len;
  7439. len = strchrnul(s, '\'') - s;
  7440. q = p = makestrspace(len + 3, p);
  7441. *q++ = '\'';
  7442. q = mempcpy(q, s, len);
  7443. *q++ = '\'';
  7444. s += len;
  7445. STADJUST(q - p, p);
  7446. len = strspn(s, "'");
  7447. if (!len)
  7448. break;
  7449. q = p = makestrspace(len + 3, p);
  7450. *q++ = '"';
  7451. q = mempcpy(q, s, len);
  7452. *q++ = '"';
  7453. s += len;
  7454. STADJUST(q - p, p);
  7455. } while (*s);
  7456. USTPUTC(0, p);
  7457. return stackblock();
  7458. }
  7459. /*
  7460. * Like strdup but works with the ash stack.
  7461. */
  7462. char *
  7463. sstrdup(const char *p)
  7464. {
  7465. size_t len = strlen(p) + 1;
  7466. return memcpy(stalloc(len), p, len);
  7467. }
  7468. static void
  7469. calcsize(union node *n)
  7470. {
  7471. if (n == NULL)
  7472. return;
  7473. funcblocksize += nodesize[n->type];
  7474. switch (n->type) {
  7475. case NCMD:
  7476. calcsize(n->ncmd.redirect);
  7477. calcsize(n->ncmd.args);
  7478. calcsize(n->ncmd.assign);
  7479. break;
  7480. case NPIPE:
  7481. sizenodelist(n->npipe.cmdlist);
  7482. break;
  7483. case NREDIR:
  7484. case NBACKGND:
  7485. case NSUBSHELL:
  7486. calcsize(n->nredir.redirect);
  7487. calcsize(n->nredir.n);
  7488. break;
  7489. case NAND:
  7490. case NOR:
  7491. case NSEMI:
  7492. case NWHILE:
  7493. case NUNTIL:
  7494. calcsize(n->nbinary.ch2);
  7495. calcsize(n->nbinary.ch1);
  7496. break;
  7497. case NIF:
  7498. calcsize(n->nif.elsepart);
  7499. calcsize(n->nif.ifpart);
  7500. calcsize(n->nif.test);
  7501. break;
  7502. case NFOR:
  7503. funcstringsize += strlen(n->nfor.var) + 1;
  7504. calcsize(n->nfor.body);
  7505. calcsize(n->nfor.args);
  7506. break;
  7507. case NCASE:
  7508. calcsize(n->ncase.cases);
  7509. calcsize(n->ncase.expr);
  7510. break;
  7511. case NCLIST:
  7512. calcsize(n->nclist.body);
  7513. calcsize(n->nclist.pattern);
  7514. calcsize(n->nclist.next);
  7515. break;
  7516. case NDEFUN:
  7517. case NARG:
  7518. sizenodelist(n->narg.backquote);
  7519. funcstringsize += strlen(n->narg.text) + 1;
  7520. calcsize(n->narg.next);
  7521. break;
  7522. case NTO:
  7523. case NCLOBBER:
  7524. case NFROM:
  7525. case NFROMTO:
  7526. case NAPPEND:
  7527. calcsize(n->nfile.fname);
  7528. calcsize(n->nfile.next);
  7529. break;
  7530. case NTOFD:
  7531. case NFROMFD:
  7532. calcsize(n->ndup.vname);
  7533. calcsize(n->ndup.next);
  7534. break;
  7535. case NHERE:
  7536. case NXHERE:
  7537. calcsize(n->nhere.doc);
  7538. calcsize(n->nhere.next);
  7539. break;
  7540. case NNOT:
  7541. calcsize(n->nnot.com);
  7542. break;
  7543. };
  7544. }
  7545. static void
  7546. sizenodelist(struct nodelist *lp)
  7547. {
  7548. while (lp) {
  7549. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7550. calcsize(lp->n);
  7551. lp = lp->next;
  7552. }
  7553. }
  7554. static union node *
  7555. copynode(union node *n)
  7556. {
  7557. union node *new;
  7558. if (n == NULL)
  7559. return NULL;
  7560. new = funcblock;
  7561. funcblock = (char *) funcblock + nodesize[n->type];
  7562. switch (n->type) {
  7563. case NCMD:
  7564. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7565. new->ncmd.args = copynode(n->ncmd.args);
  7566. new->ncmd.assign = copynode(n->ncmd.assign);
  7567. break;
  7568. case NPIPE:
  7569. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7570. new->npipe.backgnd = n->npipe.backgnd;
  7571. break;
  7572. case NREDIR:
  7573. case NBACKGND:
  7574. case NSUBSHELL:
  7575. new->nredir.redirect = copynode(n->nredir.redirect);
  7576. new->nredir.n = copynode(n->nredir.n);
  7577. break;
  7578. case NAND:
  7579. case NOR:
  7580. case NSEMI:
  7581. case NWHILE:
  7582. case NUNTIL:
  7583. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7584. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7585. break;
  7586. case NIF:
  7587. new->nif.elsepart = copynode(n->nif.elsepart);
  7588. new->nif.ifpart = copynode(n->nif.ifpart);
  7589. new->nif.test = copynode(n->nif.test);
  7590. break;
  7591. case NFOR:
  7592. new->nfor.var = nodesavestr(n->nfor.var);
  7593. new->nfor.body = copynode(n->nfor.body);
  7594. new->nfor.args = copynode(n->nfor.args);
  7595. break;
  7596. case NCASE:
  7597. new->ncase.cases = copynode(n->ncase.cases);
  7598. new->ncase.expr = copynode(n->ncase.expr);
  7599. break;
  7600. case NCLIST:
  7601. new->nclist.body = copynode(n->nclist.body);
  7602. new->nclist.pattern = copynode(n->nclist.pattern);
  7603. new->nclist.next = copynode(n->nclist.next);
  7604. break;
  7605. case NDEFUN:
  7606. case NARG:
  7607. new->narg.backquote = copynodelist(n->narg.backquote);
  7608. new->narg.text = nodesavestr(n->narg.text);
  7609. new->narg.next = copynode(n->narg.next);
  7610. break;
  7611. case NTO:
  7612. case NCLOBBER:
  7613. case NFROM:
  7614. case NFROMTO:
  7615. case NAPPEND:
  7616. new->nfile.fname = copynode(n->nfile.fname);
  7617. new->nfile.fd = n->nfile.fd;
  7618. new->nfile.next = copynode(n->nfile.next);
  7619. break;
  7620. case NTOFD:
  7621. case NFROMFD:
  7622. new->ndup.vname = copynode(n->ndup.vname);
  7623. new->ndup.dupfd = n->ndup.dupfd;
  7624. new->ndup.fd = n->ndup.fd;
  7625. new->ndup.next = copynode(n->ndup.next);
  7626. break;
  7627. case NHERE:
  7628. case NXHERE:
  7629. new->nhere.doc = copynode(n->nhere.doc);
  7630. new->nhere.fd = n->nhere.fd;
  7631. new->nhere.next = copynode(n->nhere.next);
  7632. break;
  7633. case NNOT:
  7634. new->nnot.com = copynode(n->nnot.com);
  7635. break;
  7636. };
  7637. new->type = n->type;
  7638. return new;
  7639. }
  7640. static struct nodelist *
  7641. copynodelist(struct nodelist *lp)
  7642. {
  7643. struct nodelist *start;
  7644. struct nodelist **lpp;
  7645. lpp = &start;
  7646. while (lp) {
  7647. *lpp = funcblock;
  7648. funcblock = (char *) funcblock +
  7649. SHELL_ALIGN(sizeof(struct nodelist));
  7650. (*lpp)->n = copynode(lp->n);
  7651. lp = lp->next;
  7652. lpp = &(*lpp)->next;
  7653. }
  7654. *lpp = NULL;
  7655. return start;
  7656. }
  7657. static char *
  7658. nodesavestr(char *s)
  7659. {
  7660. char *rtn = funcstring;
  7661. funcstring = stpcpy(funcstring, s) + 1;
  7662. return rtn;
  7663. }
  7664. /*
  7665. * Free a parse tree.
  7666. */
  7667. static void
  7668. freefunc(struct funcnode *f)
  7669. {
  7670. if (f && --f->count < 0)
  7671. ckfree(f);
  7672. }
  7673. static void options(int);
  7674. static void setoption(int, int);
  7675. /*
  7676. * Process the shell command line arguments.
  7677. */
  7678. void
  7679. procargs(int argc, char **argv)
  7680. {
  7681. int i;
  7682. const char *xminusc;
  7683. char **xargv;
  7684. xargv = argv;
  7685. arg0 = xargv[0];
  7686. if (argc > 0)
  7687. xargv++;
  7688. for (i = 0; i < NOPTS; i++)
  7689. optlist[i] = 2;
  7690. argptr = xargv;
  7691. options(1);
  7692. xargv = argptr;
  7693. xminusc = minusc;
  7694. if (*xargv == NULL) {
  7695. if (xminusc)
  7696. sh_error(bb_msg_requires_arg, "-c");
  7697. sflag = 1;
  7698. }
  7699. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  7700. iflag = 1;
  7701. if (mflag == 2)
  7702. mflag = iflag;
  7703. for (i = 0; i < NOPTS; i++)
  7704. if (optlist[i] == 2)
  7705. optlist[i] = 0;
  7706. #if DEBUG == 2
  7707. debug = 1;
  7708. #endif
  7709. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  7710. if (xminusc) {
  7711. minusc = *xargv++;
  7712. if (*xargv)
  7713. goto setarg0;
  7714. } else if (!sflag) {
  7715. setinputfile(*xargv, 0);
  7716. setarg0:
  7717. arg0 = *xargv++;
  7718. commandname = arg0;
  7719. }
  7720. shellparam.p = xargv;
  7721. #ifdef CONFIG_ASH_GETOPTS
  7722. shellparam.optind = 1;
  7723. shellparam.optoff = -1;
  7724. #endif
  7725. /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
  7726. while (*xargv) {
  7727. shellparam.nparam++;
  7728. xargv++;
  7729. }
  7730. optschanged();
  7731. }
  7732. void
  7733. optschanged(void)
  7734. {
  7735. #if DEBUG
  7736. opentrace();
  7737. #endif
  7738. setinteractive(iflag);
  7739. setjobctl(mflag);
  7740. setvimode(viflag);
  7741. }
  7742. static void minus_o(char *name, int val)
  7743. {
  7744. int i;
  7745. if (name == NULL) {
  7746. out1str("Current option settings\n");
  7747. for (i = 0; i < NOPTS; i++)
  7748. out1fmt("%-16s%s\n", optnames(i),
  7749. optlist[i] ? "on" : "off");
  7750. } else {
  7751. for (i = 0; i < NOPTS; i++)
  7752. if (equal(name, optnames(i))) {
  7753. optlist[i] = val;
  7754. return;
  7755. }
  7756. sh_error("Illegal option -o %s", name);
  7757. }
  7758. }
  7759. /*
  7760. * Process shell options. The global variable argptr contains a pointer
  7761. * to the argument list; we advance it past the options.
  7762. */
  7763. static void
  7764. options(int cmdline)
  7765. {
  7766. char *p;
  7767. int val;
  7768. int c;
  7769. if (cmdline)
  7770. minusc = NULL;
  7771. while ((p = *argptr) != NULL) {
  7772. argptr++;
  7773. if ((c = *p++) == '-') {
  7774. val = 1;
  7775. if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
  7776. if (!cmdline) {
  7777. /* "-" means turn off -x and -v */
  7778. if (p[0] == '\0')
  7779. xflag = vflag = 0;
  7780. /* "--" means reset params */
  7781. else if (*argptr == NULL)
  7782. setparam(argptr);
  7783. }
  7784. break; /* "-" or "--" terminates options */
  7785. }
  7786. } else if (c == '+') {
  7787. val = 0;
  7788. } else {
  7789. argptr--;
  7790. break;
  7791. }
  7792. while ((c = *p++) != '\0') {
  7793. if (c == 'c' && cmdline) {
  7794. minusc = p; /* command is after shell args*/
  7795. } else if (c == 'o') {
  7796. minus_o(*argptr, val);
  7797. if (*argptr)
  7798. argptr++;
  7799. } else if (cmdline && (c == '-')) { // long options
  7800. if (strcmp(p, "login") == 0)
  7801. isloginsh = 1;
  7802. break;
  7803. } else {
  7804. setoption(c, val);
  7805. }
  7806. }
  7807. }
  7808. }
  7809. static void
  7810. setoption(int flag, int val)
  7811. {
  7812. int i;
  7813. for (i = 0; i < NOPTS; i++)
  7814. if (optletters(i) == flag) {
  7815. optlist[i] = val;
  7816. return;
  7817. }
  7818. sh_error("Illegal option -%c", flag);
  7819. /* NOTREACHED */
  7820. }
  7821. /*
  7822. * Set the shell parameters.
  7823. */
  7824. void
  7825. setparam(char **argv)
  7826. {
  7827. char **newparam;
  7828. char **ap;
  7829. int nparam;
  7830. for (nparam = 0 ; argv[nparam] ; nparam++);
  7831. ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
  7832. while (*argv) {
  7833. *ap++ = savestr(*argv++);
  7834. }
  7835. *ap = NULL;
  7836. freeparam(&shellparam);
  7837. shellparam.malloc = 1;
  7838. shellparam.nparam = nparam;
  7839. shellparam.p = newparam;
  7840. #ifdef CONFIG_ASH_GETOPTS
  7841. shellparam.optind = 1;
  7842. shellparam.optoff = -1;
  7843. #endif
  7844. }
  7845. /*
  7846. * Free the list of positional parameters.
  7847. */
  7848. void
  7849. freeparam(volatile struct shparam *param)
  7850. {
  7851. char **ap;
  7852. if (param->malloc) {
  7853. for (ap = param->p ; *ap ; ap++)
  7854. ckfree(*ap);
  7855. ckfree(param->p);
  7856. }
  7857. }
  7858. /*
  7859. * The shift builtin command.
  7860. */
  7861. int
  7862. shiftcmd(int argc, char **argv)
  7863. {
  7864. int n;
  7865. char **ap1, **ap2;
  7866. n = 1;
  7867. if (argc > 1)
  7868. n = number(argv[1]);
  7869. if (n > shellparam.nparam)
  7870. sh_error("can't shift that many");
  7871. INTOFF;
  7872. shellparam.nparam -= n;
  7873. for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
  7874. if (shellparam.malloc)
  7875. ckfree(*ap1);
  7876. }
  7877. ap2 = shellparam.p;
  7878. while ((*ap2++ = *ap1++) != NULL);
  7879. #ifdef CONFIG_ASH_GETOPTS
  7880. shellparam.optind = 1;
  7881. shellparam.optoff = -1;
  7882. #endif
  7883. INTON;
  7884. return 0;
  7885. }
  7886. /*
  7887. * The set command builtin.
  7888. */
  7889. int
  7890. setcmd(int argc, char **argv)
  7891. {
  7892. if (argc == 1)
  7893. return showvars(nullstr, 0, VUNSET);
  7894. INTOFF;
  7895. options(0);
  7896. optschanged();
  7897. if (*argptr != NULL) {
  7898. setparam(argptr);
  7899. }
  7900. INTON;
  7901. return 0;
  7902. }
  7903. #ifdef CONFIG_ASH_GETOPTS
  7904. static void
  7905. getoptsreset(const char *value)
  7906. {
  7907. shellparam.optind = number(value);
  7908. shellparam.optoff = -1;
  7909. }
  7910. #endif
  7911. #ifdef CONFIG_LOCALE_SUPPORT
  7912. static void change_lc_all(const char *value)
  7913. {
  7914. if (value != 0 && *value != 0)
  7915. setlocale(LC_ALL, value);
  7916. }
  7917. static void change_lc_ctype(const char *value)
  7918. {
  7919. if (value != 0 && *value != 0)
  7920. setlocale(LC_CTYPE, value);
  7921. }
  7922. #endif
  7923. #ifdef CONFIG_ASH_RANDOM_SUPPORT
  7924. /* Roughly copied from bash.. */
  7925. static void change_random(const char *value)
  7926. {
  7927. if(value == NULL) {
  7928. /* "get", generate */
  7929. char buf[16];
  7930. rseed = rseed * 1103515245 + 12345;
  7931. sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
  7932. /* set without recursion */
  7933. setvar(vrandom.text, buf, VNOFUNC);
  7934. vrandom.flags &= ~VNOFUNC;
  7935. } else {
  7936. /* set/reset */
  7937. rseed = strtoul(value, (char **)NULL, 10);
  7938. }
  7939. }
  7940. #endif
  7941. #ifdef CONFIG_ASH_GETOPTS
  7942. static int
  7943. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  7944. {
  7945. char *p, *q;
  7946. char c = '?';
  7947. int done = 0;
  7948. int err = 0;
  7949. char s[12];
  7950. char **optnext;
  7951. if(*param_optind < 1)
  7952. return 1;
  7953. optnext = optfirst + *param_optind - 1;
  7954. if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
  7955. p = NULL;
  7956. else
  7957. p = optnext[-1] + *optoff;
  7958. if (p == NULL || *p == '\0') {
  7959. /* Current word is done, advance */
  7960. p = *optnext;
  7961. if (p == NULL || *p != '-' || *++p == '\0') {
  7962. atend:
  7963. p = NULL;
  7964. done = 1;
  7965. goto out;
  7966. }
  7967. optnext++;
  7968. if (p[0] == '-' && p[1] == '\0') /* check for "--" */
  7969. goto atend;
  7970. }
  7971. c = *p++;
  7972. for (q = optstr; *q != c; ) {
  7973. if (*q == '\0') {
  7974. if (optstr[0] == ':') {
  7975. s[0] = c;
  7976. s[1] = '\0';
  7977. err |= setvarsafe("OPTARG", s, 0);
  7978. } else {
  7979. fprintf(stderr, "Illegal option -%c\n", c);
  7980. (void) unsetvar("OPTARG");
  7981. }
  7982. c = '?';
  7983. goto out;
  7984. }
  7985. if (*++q == ':')
  7986. q++;
  7987. }
  7988. if (*++q == ':') {
  7989. if (*p == '\0' && (p = *optnext) == NULL) {
  7990. if (optstr[0] == ':') {
  7991. s[0] = c;
  7992. s[1] = '\0';
  7993. err |= setvarsafe("OPTARG", s, 0);
  7994. c = ':';
  7995. } else {
  7996. fprintf(stderr, "No arg for -%c option\n", c);
  7997. (void) unsetvar("OPTARG");
  7998. c = '?';
  7999. }
  8000. goto out;
  8001. }
  8002. if (p == *optnext)
  8003. optnext++;
  8004. err |= setvarsafe("OPTARG", p, 0);
  8005. p = NULL;
  8006. } else
  8007. err |= setvarsafe("OPTARG", nullstr, 0);
  8008. out:
  8009. *optoff = p ? p - *(optnext - 1) : -1;
  8010. *param_optind = optnext - optfirst + 1;
  8011. fmtstr(s, sizeof(s), "%d", *param_optind);
  8012. err |= setvarsafe("OPTIND", s, VNOFUNC);
  8013. s[0] = c;
  8014. s[1] = '\0';
  8015. err |= setvarsafe(optvar, s, 0);
  8016. if (err) {
  8017. *param_optind = 1;
  8018. *optoff = -1;
  8019. flushall();
  8020. exraise(EXERROR);
  8021. }
  8022. return done;
  8023. }
  8024. /*
  8025. * The getopts builtin. Shellparam.optnext points to the next argument
  8026. * to be processed. Shellparam.optptr points to the next character to
  8027. * be processed in the current argument. If shellparam.optnext is NULL,
  8028. * then it's the first time getopts has been called.
  8029. */
  8030. int
  8031. getoptscmd(int argc, char **argv)
  8032. {
  8033. char **optbase;
  8034. if (argc < 3)
  8035. sh_error("Usage: getopts optstring var [arg]");
  8036. else if (argc == 3) {
  8037. optbase = shellparam.p;
  8038. if (shellparam.optind > shellparam.nparam + 1) {
  8039. shellparam.optind = 1;
  8040. shellparam.optoff = -1;
  8041. }
  8042. }
  8043. else {
  8044. optbase = &argv[3];
  8045. if (shellparam.optind > argc - 2) {
  8046. shellparam.optind = 1;
  8047. shellparam.optoff = -1;
  8048. }
  8049. }
  8050. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  8051. &shellparam.optoff);
  8052. }
  8053. #endif /* CONFIG_ASH_GETOPTS */
  8054. /*
  8055. * XXX - should get rid of. have all builtins use getopt(3). the
  8056. * library getopt must have the BSD extension static variable "optreset"
  8057. * otherwise it can't be used within the shell safely.
  8058. *
  8059. * Standard option processing (a la getopt) for builtin routines. The
  8060. * only argument that is passed to nextopt is the option string; the
  8061. * other arguments are unnecessary. It return the character, or '\0' on
  8062. * end of input.
  8063. */
  8064. static int
  8065. nextopt(const char *optstring)
  8066. {
  8067. char *p;
  8068. const char *q;
  8069. char c;
  8070. if ((p = optptr) == NULL || *p == '\0') {
  8071. p = *argptr;
  8072. if (p == NULL || *p != '-' || *++p == '\0')
  8073. return '\0';
  8074. argptr++;
  8075. if (p[0] == '-' && p[1] == '\0') /* check for "--" */
  8076. return '\0';
  8077. }
  8078. c = *p++;
  8079. for (q = optstring ; *q != c ; ) {
  8080. if (*q == '\0')
  8081. sh_error("Illegal option -%c", c);
  8082. if (*++q == ':')
  8083. q++;
  8084. }
  8085. if (*++q == ':') {
  8086. if (*p == '\0' && (p = *argptr++) == NULL)
  8087. sh_error("No arg for -%c option", c);
  8088. optionarg = p;
  8089. p = NULL;
  8090. }
  8091. optptr = p;
  8092. return c;
  8093. }
  8094. /* output.c */
  8095. void
  8096. outstr(const char *p, FILE *file)
  8097. {
  8098. INTOFF;
  8099. fputs(p, file);
  8100. INTON;
  8101. }
  8102. void
  8103. flushall(void)
  8104. {
  8105. INTOFF;
  8106. fflush(stdout);
  8107. fflush(stderr);
  8108. INTON;
  8109. }
  8110. void
  8111. flusherr(void)
  8112. {
  8113. INTOFF;
  8114. fflush(stderr);
  8115. INTON;
  8116. }
  8117. static void
  8118. outcslow(int c, FILE *dest)
  8119. {
  8120. INTOFF;
  8121. putc(c, dest);
  8122. fflush(dest);
  8123. INTON;
  8124. }
  8125. static int
  8126. out1fmt(const char *fmt, ...)
  8127. {
  8128. va_list ap;
  8129. int r;
  8130. INTOFF;
  8131. va_start(ap, fmt);
  8132. r = vprintf(fmt, ap);
  8133. va_end(ap);
  8134. INTON;
  8135. return r;
  8136. }
  8137. int
  8138. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  8139. {
  8140. va_list ap;
  8141. int ret;
  8142. va_start(ap, fmt);
  8143. INTOFF;
  8144. ret = vsnprintf(outbuf, length, fmt, ap);
  8145. va_end(ap);
  8146. INTON;
  8147. return ret;
  8148. }
  8149. /* parser.c */
  8150. /*
  8151. * Shell command parser.
  8152. */
  8153. #define EOFMARKLEN 79
  8154. struct heredoc {
  8155. struct heredoc *next; /* next here document in list */
  8156. union node *here; /* redirection node */
  8157. char *eofmark; /* string indicating end of input */
  8158. int striptabs; /* if set, strip leading tabs */
  8159. };
  8160. static struct heredoc *heredoclist; /* list of here documents to read */
  8161. static union node *list(int);
  8162. static union node *andor(void);
  8163. static union node *pipeline(void);
  8164. static union node *command(void);
  8165. static union node *simplecmd(void);
  8166. static union node *makename(void);
  8167. static void parsefname(void);
  8168. static void parseheredoc(void);
  8169. static char peektoken(void);
  8170. static int readtoken(void);
  8171. static int xxreadtoken(void);
  8172. static int readtoken1(int firstc, int syntax, char *eofmark, int striptabs);
  8173. static int noexpand(char *);
  8174. static void synexpect(int) ATTRIBUTE_NORETURN;
  8175. static void synerror(const char *) ATTRIBUTE_NORETURN;
  8176. static void setprompt(int);
  8177. /*
  8178. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  8179. * valid parse tree indicating a blank line.)
  8180. */
  8181. union node *
  8182. parsecmd(int interact)
  8183. {
  8184. int t;
  8185. tokpushback = 0;
  8186. doprompt = interact;
  8187. if (doprompt)
  8188. setprompt(doprompt);
  8189. needprompt = 0;
  8190. t = readtoken();
  8191. if (t == TEOF)
  8192. return NEOF;
  8193. if (t == TNL)
  8194. return NULL;
  8195. tokpushback++;
  8196. return list(1);
  8197. }
  8198. static union node *
  8199. list(int nlflag)
  8200. {
  8201. union node *n1, *n2, *n3;
  8202. int tok;
  8203. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8204. if (nlflag == 2 && peektoken())
  8205. return NULL;
  8206. n1 = NULL;
  8207. for (;;) {
  8208. n2 = andor();
  8209. tok = readtoken();
  8210. if (tok == TBACKGND) {
  8211. if (n2->type == NPIPE) {
  8212. n2->npipe.backgnd = 1;
  8213. } else {
  8214. if (n2->type != NREDIR) {
  8215. n3 = stalloc(sizeof(struct nredir));
  8216. n3->nredir.n = n2;
  8217. n3->nredir.redirect = NULL;
  8218. n2 = n3;
  8219. }
  8220. n2->type = NBACKGND;
  8221. }
  8222. }
  8223. if (n1 == NULL) {
  8224. n1 = n2;
  8225. }
  8226. else {
  8227. n3 = (union node *)stalloc(sizeof (struct nbinary));
  8228. n3->type = NSEMI;
  8229. n3->nbinary.ch1 = n1;
  8230. n3->nbinary.ch2 = n2;
  8231. n1 = n3;
  8232. }
  8233. switch (tok) {
  8234. case TBACKGND:
  8235. case TSEMI:
  8236. tok = readtoken();
  8237. /* fall through */
  8238. case TNL:
  8239. if (tok == TNL) {
  8240. parseheredoc();
  8241. if (nlflag == 1)
  8242. return n1;
  8243. } else {
  8244. tokpushback++;
  8245. }
  8246. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8247. if (peektoken())
  8248. return n1;
  8249. break;
  8250. case TEOF:
  8251. if (heredoclist)
  8252. parseheredoc();
  8253. else
  8254. pungetc(); /* push back EOF on input */
  8255. return n1;
  8256. default:
  8257. if (nlflag == 1)
  8258. synexpect(-1);
  8259. tokpushback++;
  8260. return n1;
  8261. }
  8262. }
  8263. }
  8264. static union node *
  8265. andor(void)
  8266. {
  8267. union node *n1, *n2, *n3;
  8268. int t;
  8269. n1 = pipeline();
  8270. for (;;) {
  8271. if ((t = readtoken()) == TAND) {
  8272. t = NAND;
  8273. } else if (t == TOR) {
  8274. t = NOR;
  8275. } else {
  8276. tokpushback++;
  8277. return n1;
  8278. }
  8279. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8280. n2 = pipeline();
  8281. n3 = (union node *)stalloc(sizeof (struct nbinary));
  8282. n3->type = t;
  8283. n3->nbinary.ch1 = n1;
  8284. n3->nbinary.ch2 = n2;
  8285. n1 = n3;
  8286. }
  8287. }
  8288. static union node *
  8289. pipeline(void)
  8290. {
  8291. union node *n1, *n2, *pipenode;
  8292. struct nodelist *lp, *prev;
  8293. int negate;
  8294. negate = 0;
  8295. TRACE(("pipeline: entered\n"));
  8296. if (readtoken() == TNOT) {
  8297. negate = !negate;
  8298. checkkwd = CHKKWD | CHKALIAS;
  8299. } else
  8300. tokpushback++;
  8301. n1 = command();
  8302. if (readtoken() == TPIPE) {
  8303. pipenode = (union node *)stalloc(sizeof (struct npipe));
  8304. pipenode->type = NPIPE;
  8305. pipenode->npipe.backgnd = 0;
  8306. lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  8307. pipenode->npipe.cmdlist = lp;
  8308. lp->n = n1;
  8309. do {
  8310. prev = lp;
  8311. lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  8312. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8313. lp->n = command();
  8314. prev->next = lp;
  8315. } while (readtoken() == TPIPE);
  8316. lp->next = NULL;
  8317. n1 = pipenode;
  8318. }
  8319. tokpushback++;
  8320. if (negate) {
  8321. n2 = (union node *)stalloc(sizeof (struct nnot));
  8322. n2->type = NNOT;
  8323. n2->nnot.com = n1;
  8324. return n2;
  8325. } else
  8326. return n1;
  8327. }
  8328. static union node *
  8329. command(void)
  8330. {
  8331. union node *n1, *n2;
  8332. union node *ap, **app;
  8333. union node *cp, **cpp;
  8334. union node *redir, **rpp;
  8335. union node **rpp2;
  8336. int t;
  8337. redir = NULL;
  8338. rpp2 = &redir;
  8339. switch (readtoken()) {
  8340. default:
  8341. synexpect(-1);
  8342. /* NOTREACHED */
  8343. case TIF:
  8344. n1 = (union node *)stalloc(sizeof (struct nif));
  8345. n1->type = NIF;
  8346. n1->nif.test = list(0);
  8347. if (readtoken() != TTHEN)
  8348. synexpect(TTHEN);
  8349. n1->nif.ifpart = list(0);
  8350. n2 = n1;
  8351. while (readtoken() == TELIF) {
  8352. n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
  8353. n2 = n2->nif.elsepart;
  8354. n2->type = NIF;
  8355. n2->nif.test = list(0);
  8356. if (readtoken() != TTHEN)
  8357. synexpect(TTHEN);
  8358. n2->nif.ifpart = list(0);
  8359. }
  8360. if (lasttoken == TELSE)
  8361. n2->nif.elsepart = list(0);
  8362. else {
  8363. n2->nif.elsepart = NULL;
  8364. tokpushback++;
  8365. }
  8366. t = TFI;
  8367. break;
  8368. case TWHILE:
  8369. case TUNTIL: {
  8370. int got;
  8371. n1 = (union node *)stalloc(sizeof (struct nbinary));
  8372. n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
  8373. n1->nbinary.ch1 = list(0);
  8374. if ((got=readtoken()) != TDO) {
  8375. TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
  8376. synexpect(TDO);
  8377. }
  8378. n1->nbinary.ch2 = list(0);
  8379. t = TDONE;
  8380. break;
  8381. }
  8382. case TFOR:
  8383. if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
  8384. synerror("Bad for loop variable");
  8385. n1 = (union node *)stalloc(sizeof (struct nfor));
  8386. n1->type = NFOR;
  8387. n1->nfor.var = wordtext;
  8388. checkkwd = CHKKWD | CHKALIAS;
  8389. if (readtoken() == TIN) {
  8390. app = &ap;
  8391. while (readtoken() == TWORD) {
  8392. n2 = (union node *)stalloc(sizeof (struct narg));
  8393. n2->type = NARG;
  8394. n2->narg.text = wordtext;
  8395. n2->narg.backquote = backquotelist;
  8396. *app = n2;
  8397. app = &n2->narg.next;
  8398. }
  8399. *app = NULL;
  8400. n1->nfor.args = ap;
  8401. if (lasttoken != TNL && lasttoken != TSEMI)
  8402. synexpect(-1);
  8403. } else {
  8404. n2 = (union node *)stalloc(sizeof (struct narg));
  8405. n2->type = NARG;
  8406. n2->narg.text = (char *)dolatstr;
  8407. n2->narg.backquote = NULL;
  8408. n2->narg.next = NULL;
  8409. n1->nfor.args = n2;
  8410. /*
  8411. * Newline or semicolon here is optional (but note
  8412. * that the original Bourne shell only allowed NL).
  8413. */
  8414. if (lasttoken != TNL && lasttoken != TSEMI)
  8415. tokpushback++;
  8416. }
  8417. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8418. if (readtoken() != TDO)
  8419. synexpect(TDO);
  8420. n1->nfor.body = list(0);
  8421. t = TDONE;
  8422. break;
  8423. case TCASE:
  8424. n1 = (union node *)stalloc(sizeof (struct ncase));
  8425. n1->type = NCASE;
  8426. if (readtoken() != TWORD)
  8427. synexpect(TWORD);
  8428. n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
  8429. n2->type = NARG;
  8430. n2->narg.text = wordtext;
  8431. n2->narg.backquote = backquotelist;
  8432. n2->narg.next = NULL;
  8433. do {
  8434. checkkwd = CHKKWD | CHKALIAS;
  8435. } while (readtoken() == TNL);
  8436. if (lasttoken != TIN)
  8437. synexpect(TIN);
  8438. cpp = &n1->ncase.cases;
  8439. next_case:
  8440. checkkwd = CHKNL | CHKKWD;
  8441. t = readtoken();
  8442. while(t != TESAC) {
  8443. if (lasttoken == TLP)
  8444. readtoken();
  8445. *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
  8446. cp->type = NCLIST;
  8447. app = &cp->nclist.pattern;
  8448. for (;;) {
  8449. *app = ap = (union node *)stalloc(sizeof (struct narg));
  8450. ap->type = NARG;
  8451. ap->narg.text = wordtext;
  8452. ap->narg.backquote = backquotelist;
  8453. if (readtoken() != TPIPE)
  8454. break;
  8455. app = &ap->narg.next;
  8456. readtoken();
  8457. }
  8458. ap->narg.next = NULL;
  8459. if (lasttoken != TRP)
  8460. synexpect(TRP);
  8461. cp->nclist.body = list(2);
  8462. cpp = &cp->nclist.next;
  8463. checkkwd = CHKNL | CHKKWD;
  8464. if ((t = readtoken()) != TESAC) {
  8465. if (t != TENDCASE)
  8466. synexpect(TENDCASE);
  8467. else
  8468. goto next_case;
  8469. }
  8470. }
  8471. *cpp = NULL;
  8472. goto redir;
  8473. case TLP:
  8474. n1 = (union node *)stalloc(sizeof (struct nredir));
  8475. n1->type = NSUBSHELL;
  8476. n1->nredir.n = list(0);
  8477. n1->nredir.redirect = NULL;
  8478. t = TRP;
  8479. break;
  8480. case TBEGIN:
  8481. n1 = list(0);
  8482. t = TEND;
  8483. break;
  8484. case TWORD:
  8485. case TREDIR:
  8486. tokpushback++;
  8487. return simplecmd();
  8488. }
  8489. if (readtoken() != t)
  8490. synexpect(t);
  8491. redir:
  8492. /* Now check for redirection which may follow command */
  8493. checkkwd = CHKKWD | CHKALIAS;
  8494. rpp = rpp2;
  8495. while (readtoken() == TREDIR) {
  8496. *rpp = n2 = redirnode;
  8497. rpp = &n2->nfile.next;
  8498. parsefname();
  8499. }
  8500. tokpushback++;
  8501. *rpp = NULL;
  8502. if (redir) {
  8503. if (n1->type != NSUBSHELL) {
  8504. n2 = (union node *)stalloc(sizeof (struct nredir));
  8505. n2->type = NREDIR;
  8506. n2->nredir.n = n1;
  8507. n1 = n2;
  8508. }
  8509. n1->nredir.redirect = redir;
  8510. }
  8511. return n1;
  8512. }
  8513. static union node *
  8514. simplecmd(void) {
  8515. union node *args, **app;
  8516. union node *n = NULL;
  8517. union node *vars, **vpp;
  8518. union node **rpp, *redir;
  8519. int savecheckkwd;
  8520. args = NULL;
  8521. app = &args;
  8522. vars = NULL;
  8523. vpp = &vars;
  8524. redir = NULL;
  8525. rpp = &redir;
  8526. savecheckkwd = CHKALIAS;
  8527. for (;;) {
  8528. checkkwd = savecheckkwd;
  8529. switch (readtoken()) {
  8530. case TWORD:
  8531. n = (union node *)stalloc(sizeof (struct narg));
  8532. n->type = NARG;
  8533. n->narg.text = wordtext;
  8534. n->narg.backquote = backquotelist;
  8535. if (savecheckkwd && isassignment(wordtext)) {
  8536. *vpp = n;
  8537. vpp = &n->narg.next;
  8538. } else {
  8539. *app = n;
  8540. app = &n->narg.next;
  8541. savecheckkwd = 0;
  8542. }
  8543. break;
  8544. case TREDIR:
  8545. *rpp = n = redirnode;
  8546. rpp = &n->nfile.next;
  8547. parsefname(); /* read name of redirection file */
  8548. break;
  8549. case TLP:
  8550. if (
  8551. args && app == &args->narg.next &&
  8552. !vars && !redir
  8553. ) {
  8554. struct builtincmd *bcmd;
  8555. const char *name;
  8556. /* We have a function */
  8557. if (readtoken() != TRP)
  8558. synexpect(TRP);
  8559. name = n->narg.text;
  8560. if (
  8561. !goodname(name) || (
  8562. (bcmd = find_builtin(name)) &&
  8563. IS_BUILTIN_SPECIAL(bcmd)
  8564. )
  8565. )
  8566. synerror("Bad function name");
  8567. n->type = NDEFUN;
  8568. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8569. n->narg.next = command();
  8570. return n;
  8571. }
  8572. /* fall through */
  8573. default:
  8574. tokpushback++;
  8575. goto out;
  8576. }
  8577. }
  8578. out:
  8579. *app = NULL;
  8580. *vpp = NULL;
  8581. *rpp = NULL;
  8582. n = (union node *)stalloc(sizeof (struct ncmd));
  8583. n->type = NCMD;
  8584. n->ncmd.args = args;
  8585. n->ncmd.assign = vars;
  8586. n->ncmd.redirect = redir;
  8587. return n;
  8588. }
  8589. static union node *
  8590. makename(void)
  8591. {
  8592. union node *n;
  8593. n = (union node *)stalloc(sizeof (struct narg));
  8594. n->type = NARG;
  8595. n->narg.next = NULL;
  8596. n->narg.text = wordtext;
  8597. n->narg.backquote = backquotelist;
  8598. return n;
  8599. }
  8600. void fixredir(union node *n, const char *text, int err)
  8601. {
  8602. TRACE(("Fix redir %s %d\n", text, err));
  8603. if (!err)
  8604. n->ndup.vname = NULL;
  8605. if (is_digit(text[0]) && text[1] == '\0')
  8606. n->ndup.dupfd = digit_val(text[0]);
  8607. else if (text[0] == '-' && text[1] == '\0')
  8608. n->ndup.dupfd = -1;
  8609. else {
  8610. if (err)
  8611. synerror("Bad fd number");
  8612. else
  8613. n->ndup.vname = makename();
  8614. }
  8615. }
  8616. static void
  8617. parsefname(void)
  8618. {
  8619. union node *n = redirnode;
  8620. if (readtoken() != TWORD)
  8621. synexpect(-1);
  8622. if (n->type == NHERE) {
  8623. struct heredoc *here = heredoc;
  8624. struct heredoc *p;
  8625. int i;
  8626. if (quoteflag == 0)
  8627. n->type = NXHERE;
  8628. TRACE(("Here document %d\n", n->type));
  8629. if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  8630. synerror("Illegal eof marker for << redirection");
  8631. rmescapes(wordtext);
  8632. here->eofmark = wordtext;
  8633. here->next = NULL;
  8634. if (heredoclist == NULL)
  8635. heredoclist = here;
  8636. else {
  8637. for (p = heredoclist ; p->next ; p = p->next);
  8638. p->next = here;
  8639. }
  8640. } else if (n->type == NTOFD || n->type == NFROMFD) {
  8641. fixredir(n, wordtext, 0);
  8642. } else {
  8643. n->nfile.fname = makename();
  8644. }
  8645. }
  8646. /*
  8647. * Input any here documents.
  8648. */
  8649. static void
  8650. parseheredoc(void)
  8651. {
  8652. struct heredoc *here;
  8653. union node *n;
  8654. here = heredoclist;
  8655. heredoclist = 0;
  8656. while (here) {
  8657. if (needprompt) {
  8658. setprompt(2);
  8659. }
  8660. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  8661. here->eofmark, here->striptabs);
  8662. n = (union node *)stalloc(sizeof (struct narg));
  8663. n->narg.type = NARG;
  8664. n->narg.next = NULL;
  8665. n->narg.text = wordtext;
  8666. n->narg.backquote = backquotelist;
  8667. here->here->nhere.doc = n;
  8668. here = here->next;
  8669. }
  8670. }
  8671. static char peektoken(void)
  8672. {
  8673. int t;
  8674. t = readtoken();
  8675. tokpushback++;
  8676. return tokname_array[t][0];
  8677. }
  8678. static int
  8679. readtoken(void)
  8680. {
  8681. int t;
  8682. #if DEBUG
  8683. int alreadyseen = tokpushback;
  8684. #endif
  8685. #ifdef CONFIG_ASH_ALIAS
  8686. top:
  8687. #endif
  8688. t = xxreadtoken();
  8689. /*
  8690. * eat newlines
  8691. */
  8692. if (checkkwd & CHKNL) {
  8693. while (t == TNL) {
  8694. parseheredoc();
  8695. t = xxreadtoken();
  8696. }
  8697. }
  8698. if (t != TWORD || quoteflag) {
  8699. goto out;
  8700. }
  8701. /*
  8702. * check for keywords
  8703. */
  8704. if (checkkwd & CHKKWD) {
  8705. const char *const *pp;
  8706. if ((pp = findkwd(wordtext))) {
  8707. lasttoken = t = pp - tokname_array;
  8708. TRACE(("keyword %s recognized\n", tokname(t)));
  8709. goto out;
  8710. }
  8711. }
  8712. if (checkkwd & CHKALIAS) {
  8713. #ifdef CONFIG_ASH_ALIAS
  8714. struct alias *ap;
  8715. if ((ap = lookupalias(wordtext, 1)) != NULL) {
  8716. if (*ap->val) {
  8717. pushstring(ap->val, ap);
  8718. }
  8719. goto top;
  8720. }
  8721. #endif
  8722. }
  8723. out:
  8724. checkkwd = 0;
  8725. #if DEBUG
  8726. if (!alreadyseen)
  8727. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  8728. else
  8729. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  8730. #endif
  8731. return t;
  8732. }
  8733. /*
  8734. * Read the next input token.
  8735. * If the token is a word, we set backquotelist to the list of cmds in
  8736. * backquotes. We set quoteflag to true if any part of the word was
  8737. * quoted.
  8738. * If the token is TREDIR, then we set redirnode to a structure containing
  8739. * the redirection.
  8740. * In all cases, the variable startlinno is set to the number of the line
  8741. * on which the token starts.
  8742. *
  8743. * [Change comment: here documents and internal procedures]
  8744. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  8745. * word parsing code into a separate routine. In this case, readtoken
  8746. * doesn't need to have any internal procedures, but parseword does.
  8747. * We could also make parseoperator in essence the main routine, and
  8748. * have parseword (readtoken1?) handle both words and redirection.]
  8749. */
  8750. #define NEW_xxreadtoken
  8751. #ifdef NEW_xxreadtoken
  8752. /* singles must be first! */
  8753. static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
  8754. static const char xxreadtoken_tokens[] = {
  8755. TNL, TLP, TRP, /* only single occurrence allowed */
  8756. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  8757. TEOF, /* corresponds to trailing nul */
  8758. TAND, TOR, TENDCASE, /* if double occurrence */
  8759. };
  8760. #define xxreadtoken_doubles \
  8761. (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
  8762. #define xxreadtoken_singles \
  8763. (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
  8764. static int xxreadtoken(void)
  8765. {
  8766. int c;
  8767. if (tokpushback) {
  8768. tokpushback = 0;
  8769. return lasttoken;
  8770. }
  8771. if (needprompt) {
  8772. setprompt(2);
  8773. }
  8774. startlinno = plinno;
  8775. for (;;) { /* until token or start of word found */
  8776. c = pgetc_macro();
  8777. if ((c != ' ') && (c != '\t')
  8778. #ifdef CONFIG_ASH_ALIAS
  8779. && (c != PEOA)
  8780. #endif
  8781. ) {
  8782. if (c == '#') {
  8783. while ((c = pgetc()) != '\n' && c != PEOF);
  8784. pungetc();
  8785. } else if (c == '\\') {
  8786. if (pgetc() != '\n') {
  8787. pungetc();
  8788. goto READTOKEN1;
  8789. }
  8790. startlinno = ++plinno;
  8791. if (doprompt)
  8792. setprompt(2);
  8793. } else {
  8794. const char *p
  8795. = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  8796. if (c != PEOF) {
  8797. if (c == '\n') {
  8798. plinno++;
  8799. needprompt = doprompt;
  8800. }
  8801. p = strchr(xxreadtoken_chars, c);
  8802. if (p == NULL) {
  8803. READTOKEN1:
  8804. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  8805. }
  8806. if (p - xxreadtoken_chars >= xxreadtoken_singles) {
  8807. if (pgetc() == *p) { /* double occurrence? */
  8808. p += xxreadtoken_doubles + 1;
  8809. } else {
  8810. pungetc();
  8811. }
  8812. }
  8813. }
  8814. return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  8815. }
  8816. }
  8817. }
  8818. }
  8819. #else
  8820. #define RETURN(token) return lasttoken = token
  8821. static int
  8822. xxreadtoken(void)
  8823. {
  8824. int c;
  8825. if (tokpushback) {
  8826. tokpushback = 0;
  8827. return lasttoken;
  8828. }
  8829. if (needprompt) {
  8830. setprompt(2);
  8831. }
  8832. startlinno = plinno;
  8833. for (;;) { /* until token or start of word found */
  8834. c = pgetc_macro();
  8835. switch (c) {
  8836. case ' ': case '\t':
  8837. #ifdef CONFIG_ASH_ALIAS
  8838. case PEOA:
  8839. #endif
  8840. continue;
  8841. case '#':
  8842. while ((c = pgetc()) != '\n' && c != PEOF);
  8843. pungetc();
  8844. continue;
  8845. case '\\':
  8846. if (pgetc() == '\n') {
  8847. startlinno = ++plinno;
  8848. if (doprompt)
  8849. setprompt(2);
  8850. continue;
  8851. }
  8852. pungetc();
  8853. goto breakloop;
  8854. case '\n':
  8855. plinno++;
  8856. needprompt = doprompt;
  8857. RETURN(TNL);
  8858. case PEOF:
  8859. RETURN(TEOF);
  8860. case '&':
  8861. if (pgetc() == '&')
  8862. RETURN(TAND);
  8863. pungetc();
  8864. RETURN(TBACKGND);
  8865. case '|':
  8866. if (pgetc() == '|')
  8867. RETURN(TOR);
  8868. pungetc();
  8869. RETURN(TPIPE);
  8870. case ';':
  8871. if (pgetc() == ';')
  8872. RETURN(TENDCASE);
  8873. pungetc();
  8874. RETURN(TSEMI);
  8875. case '(':
  8876. RETURN(TLP);
  8877. case ')':
  8878. RETURN(TRP);
  8879. default:
  8880. goto breakloop;
  8881. }
  8882. }
  8883. breakloop:
  8884. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  8885. #undef RETURN
  8886. }
  8887. #endif /* NEW_xxreadtoken */
  8888. /*
  8889. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  8890. * is not NULL, read a here document. In the latter case, eofmark is the
  8891. * word which marks the end of the document and striptabs is true if
  8892. * leading tabs should be stripped from the document. The argument firstc
  8893. * is the first character of the input token or document.
  8894. *
  8895. * Because C does not have internal subroutines, I have simulated them
  8896. * using goto's to implement the subroutine linkage. The following macros
  8897. * will run code that appears at the end of readtoken1.
  8898. */
  8899. #define CHECKEND() {goto checkend; checkend_return:;}
  8900. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  8901. #define PARSESUB() {goto parsesub; parsesub_return:;}
  8902. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  8903. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  8904. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  8905. static int
  8906. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  8907. {
  8908. int c = firstc;
  8909. char *out;
  8910. int len;
  8911. char line[EOFMARKLEN + 1];
  8912. struct nodelist *bqlist = 0;
  8913. int quotef = 0;
  8914. int dblquote = 0;
  8915. int varnest = 0; /* levels of variables expansion */
  8916. int arinest = 0; /* levels of arithmetic expansion */
  8917. int parenlevel = 0; /* levels of parens in arithmetic */
  8918. int dqvarnest = 0; /* levels of variables expansion within double quotes */
  8919. int oldstyle = 0;
  8920. int prevsyntax = 0; /* syntax before arithmetic */
  8921. #if __GNUC__
  8922. /* Avoid longjmp clobbering */
  8923. (void) &out;
  8924. (void) &quotef;
  8925. (void) &dblquote;
  8926. (void) &varnest;
  8927. (void) &arinest;
  8928. (void) &parenlevel;
  8929. (void) &dqvarnest;
  8930. (void) &oldstyle;
  8931. (void) &prevsyntax;
  8932. (void) &syntax;
  8933. #endif
  8934. startlinno = plinno;
  8935. dblquote = 0;
  8936. if (syntax == DQSYNTAX)
  8937. dblquote = 1;
  8938. quotef = 0;
  8939. bqlist = NULL;
  8940. varnest = 0;
  8941. arinest = 0;
  8942. parenlevel = 0;
  8943. dqvarnest = 0;
  8944. STARTSTACKSTR(out);
  8945. loop: { /* for each line, until end of word */
  8946. CHECKEND(); /* set c to PEOF if at end of here document */
  8947. for (;;) { /* until end of line or end of word */
  8948. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  8949. switch(SIT(c, syntax)) {
  8950. case CNL: /* '\n' */
  8951. if (syntax == BASESYNTAX)
  8952. goto endword; /* exit outer loop */
  8953. USTPUTC(c, out);
  8954. plinno++;
  8955. if (doprompt)
  8956. setprompt(2);
  8957. c = pgetc();
  8958. goto loop; /* continue outer loop */
  8959. case CWORD:
  8960. USTPUTC(c, out);
  8961. break;
  8962. case CCTL:
  8963. if (eofmark == NULL || dblquote)
  8964. USTPUTC(CTLESC, out);
  8965. USTPUTC(c, out);
  8966. break;
  8967. case CBACK: /* backslash */
  8968. c = pgetc2();
  8969. if (c == PEOF) {
  8970. USTPUTC(CTLESC, out);
  8971. USTPUTC('\\', out);
  8972. pungetc();
  8973. } else if (c == '\n') {
  8974. if (doprompt)
  8975. setprompt(2);
  8976. } else {
  8977. if (dblquote &&
  8978. c != '\\' && c != '`' &&
  8979. c != '$' && (
  8980. c != '"' ||
  8981. eofmark != NULL)
  8982. ) {
  8983. USTPUTC(CTLESC, out);
  8984. USTPUTC('\\', out);
  8985. }
  8986. if (SIT(c, SQSYNTAX) == CCTL)
  8987. USTPUTC(CTLESC, out);
  8988. USTPUTC(c, out);
  8989. quotef++;
  8990. }
  8991. break;
  8992. case CSQUOTE:
  8993. syntax = SQSYNTAX;
  8994. quotemark:
  8995. if (eofmark == NULL) {
  8996. USTPUTC(CTLQUOTEMARK, out);
  8997. }
  8998. break;
  8999. case CDQUOTE:
  9000. syntax = DQSYNTAX;
  9001. dblquote = 1;
  9002. goto quotemark;
  9003. case CENDQUOTE:
  9004. if (eofmark != NULL && arinest == 0 &&
  9005. varnest == 0) {
  9006. USTPUTC(c, out);
  9007. } else {
  9008. if (dqvarnest == 0) {
  9009. syntax = BASESYNTAX;
  9010. dblquote = 0;
  9011. }
  9012. quotef++;
  9013. goto quotemark;
  9014. }
  9015. break;
  9016. case CVAR: /* '$' */
  9017. PARSESUB(); /* parse substitution */
  9018. break;
  9019. case CENDVAR: /* '}' */
  9020. if (varnest > 0) {
  9021. varnest--;
  9022. if (dqvarnest > 0) {
  9023. dqvarnest--;
  9024. }
  9025. USTPUTC(CTLENDVAR, out);
  9026. } else {
  9027. USTPUTC(c, out);
  9028. }
  9029. break;
  9030. #ifdef CONFIG_ASH_MATH_SUPPORT
  9031. case CLP: /* '(' in arithmetic */
  9032. parenlevel++;
  9033. USTPUTC(c, out);
  9034. break;
  9035. case CRP: /* ')' in arithmetic */
  9036. if (parenlevel > 0) {
  9037. USTPUTC(c, out);
  9038. --parenlevel;
  9039. } else {
  9040. if (pgetc() == ')') {
  9041. if (--arinest == 0) {
  9042. USTPUTC(CTLENDARI, out);
  9043. syntax = prevsyntax;
  9044. if (syntax == DQSYNTAX)
  9045. dblquote = 1;
  9046. else
  9047. dblquote = 0;
  9048. } else
  9049. USTPUTC(')', out);
  9050. } else {
  9051. /*
  9052. * unbalanced parens
  9053. * (don't 2nd guess - no error)
  9054. */
  9055. pungetc();
  9056. USTPUTC(')', out);
  9057. }
  9058. }
  9059. break;
  9060. #endif
  9061. case CBQUOTE: /* '`' */
  9062. PARSEBACKQOLD();
  9063. break;
  9064. case CENDFILE:
  9065. goto endword; /* exit outer loop */
  9066. case CIGN:
  9067. break;
  9068. default:
  9069. if (varnest == 0)
  9070. goto endword; /* exit outer loop */
  9071. #ifdef CONFIG_ASH_ALIAS
  9072. if (c != PEOA)
  9073. #endif
  9074. USTPUTC(c, out);
  9075. }
  9076. c = pgetc_macro();
  9077. }
  9078. }
  9079. endword:
  9080. #ifdef CONFIG_ASH_MATH_SUPPORT
  9081. if (syntax == ARISYNTAX)
  9082. synerror("Missing '))'");
  9083. #endif
  9084. if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
  9085. synerror("Unterminated quoted string");
  9086. if (varnest != 0) {
  9087. startlinno = plinno;
  9088. /* { */
  9089. synerror("Missing '}'");
  9090. }
  9091. USTPUTC('\0', out);
  9092. len = out - (char *)stackblock();
  9093. out = stackblock();
  9094. if (eofmark == NULL) {
  9095. if ((c == '>' || c == '<')
  9096. && quotef == 0
  9097. && len <= 2
  9098. && (*out == '\0' || is_digit(*out))) {
  9099. PARSEREDIR();
  9100. return lasttoken = TREDIR;
  9101. } else {
  9102. pungetc();
  9103. }
  9104. }
  9105. quoteflag = quotef;
  9106. backquotelist = bqlist;
  9107. grabstackblock(len);
  9108. wordtext = out;
  9109. return lasttoken = TWORD;
  9110. /* end of readtoken routine */
  9111. /*
  9112. * Check to see whether we are at the end of the here document. When this
  9113. * is called, c is set to the first character of the next input line. If
  9114. * we are at the end of the here document, this routine sets the c to PEOF.
  9115. */
  9116. checkend: {
  9117. if (eofmark) {
  9118. #ifdef CONFIG_ASH_ALIAS
  9119. if (c == PEOA) {
  9120. c = pgetc2();
  9121. }
  9122. #endif
  9123. if (striptabs) {
  9124. while (c == '\t') {
  9125. c = pgetc2();
  9126. }
  9127. }
  9128. if (c == *eofmark) {
  9129. if (pfgets(line, sizeof line) != NULL) {
  9130. char *p, *q;
  9131. p = line;
  9132. for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
  9133. if (*p == '\n' && *q == '\0') {
  9134. c = PEOF;
  9135. plinno++;
  9136. needprompt = doprompt;
  9137. } else {
  9138. pushstring(line, NULL);
  9139. }
  9140. }
  9141. }
  9142. }
  9143. goto checkend_return;
  9144. }
  9145. /*
  9146. * Parse a redirection operator. The variable "out" points to a string
  9147. * specifying the fd to be redirected. The variable "c" contains the
  9148. * first character of the redirection operator.
  9149. */
  9150. parseredir: {
  9151. char fd = *out;
  9152. union node *np;
  9153. np = (union node *)stalloc(sizeof (struct nfile));
  9154. if (c == '>') {
  9155. np->nfile.fd = 1;
  9156. c = pgetc();
  9157. if (c == '>')
  9158. np->type = NAPPEND;
  9159. else if (c == '|')
  9160. np->type = NCLOBBER;
  9161. else if (c == '&')
  9162. np->type = NTOFD;
  9163. else {
  9164. np->type = NTO;
  9165. pungetc();
  9166. }
  9167. } else { /* c == '<' */
  9168. np->nfile.fd = 0;
  9169. switch (c = pgetc()) {
  9170. case '<':
  9171. if (sizeof (struct nfile) != sizeof (struct nhere)) {
  9172. np = (union node *)stalloc(sizeof (struct nhere));
  9173. np->nfile.fd = 0;
  9174. }
  9175. np->type = NHERE;
  9176. heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
  9177. heredoc->here = np;
  9178. if ((c = pgetc()) == '-') {
  9179. heredoc->striptabs = 1;
  9180. } else {
  9181. heredoc->striptabs = 0;
  9182. pungetc();
  9183. }
  9184. break;
  9185. case '&':
  9186. np->type = NFROMFD;
  9187. break;
  9188. case '>':
  9189. np->type = NFROMTO;
  9190. break;
  9191. default:
  9192. np->type = NFROM;
  9193. pungetc();
  9194. break;
  9195. }
  9196. }
  9197. if (fd != '\0')
  9198. np->nfile.fd = digit_val(fd);
  9199. redirnode = np;
  9200. goto parseredir_return;
  9201. }
  9202. /*
  9203. * Parse a substitution. At this point, we have read the dollar sign
  9204. * and nothing else.
  9205. */
  9206. parsesub: {
  9207. int subtype;
  9208. int typeloc;
  9209. int flags;
  9210. char *p;
  9211. static const char types[] = "}-+?=";
  9212. c = pgetc();
  9213. if (
  9214. c <= PEOA_OR_PEOF ||
  9215. (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  9216. ) {
  9217. USTPUTC('$', out);
  9218. pungetc();
  9219. } else if (c == '(') { /* $(command) or $((arith)) */
  9220. if (pgetc() == '(') {
  9221. #ifdef CONFIG_ASH_MATH_SUPPORT
  9222. PARSEARITH();
  9223. #else
  9224. synerror("We unsupport $((arith))");
  9225. #endif
  9226. } else {
  9227. pungetc();
  9228. PARSEBACKQNEW();
  9229. }
  9230. } else {
  9231. USTPUTC(CTLVAR, out);
  9232. typeloc = out - (char *)stackblock();
  9233. USTPUTC(VSNORMAL, out);
  9234. subtype = VSNORMAL;
  9235. if (c == '{') {
  9236. c = pgetc();
  9237. if (c == '#') {
  9238. if ((c = pgetc()) == '}')
  9239. c = '#';
  9240. else
  9241. subtype = VSLENGTH;
  9242. }
  9243. else
  9244. subtype = 0;
  9245. }
  9246. if (c > PEOA_OR_PEOF && is_name(c)) {
  9247. do {
  9248. STPUTC(c, out);
  9249. c = pgetc();
  9250. } while (c > PEOA_OR_PEOF && is_in_name(c));
  9251. } else if (is_digit(c)) {
  9252. do {
  9253. STPUTC(c, out);
  9254. c = pgetc();
  9255. } while (is_digit(c));
  9256. }
  9257. else if (is_special(c)) {
  9258. USTPUTC(c, out);
  9259. c = pgetc();
  9260. }
  9261. else
  9262. badsub: synerror("Bad substitution");
  9263. STPUTC('=', out);
  9264. flags = 0;
  9265. if (subtype == 0) {
  9266. switch (c) {
  9267. case ':':
  9268. flags = VSNUL;
  9269. c = pgetc();
  9270. /*FALLTHROUGH*/
  9271. default:
  9272. p = strchr(types, c);
  9273. if (p == NULL)
  9274. goto badsub;
  9275. subtype = p - types + VSNORMAL;
  9276. break;
  9277. case '%':
  9278. case '#':
  9279. {
  9280. int cc = c;
  9281. subtype = c == '#' ? VSTRIMLEFT :
  9282. VSTRIMRIGHT;
  9283. c = pgetc();
  9284. if (c == cc)
  9285. subtype++;
  9286. else
  9287. pungetc();
  9288. break;
  9289. }
  9290. }
  9291. } else {
  9292. pungetc();
  9293. }
  9294. if (dblquote || arinest)
  9295. flags |= VSQUOTE;
  9296. *((char *)stackblock() + typeloc) = subtype | flags;
  9297. if (subtype != VSNORMAL) {
  9298. varnest++;
  9299. if (dblquote || arinest) {
  9300. dqvarnest++;
  9301. }
  9302. }
  9303. }
  9304. goto parsesub_return;
  9305. }
  9306. /*
  9307. * Called to parse command substitutions. Newstyle is set if the command
  9308. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  9309. * list of commands (passed by reference), and savelen is the number of
  9310. * characters on the top of the stack which must be preserved.
  9311. */
  9312. parsebackq: {
  9313. struct nodelist **nlpp;
  9314. int savepbq;
  9315. union node *n;
  9316. char *volatile str;
  9317. struct jmploc jmploc;
  9318. struct jmploc *volatile savehandler;
  9319. size_t savelen;
  9320. int saveprompt = 0;
  9321. #ifdef __GNUC__
  9322. (void) &saveprompt;
  9323. #endif
  9324. savepbq = parsebackquote;
  9325. if (setjmp(jmploc.loc)) {
  9326. if (str)
  9327. ckfree(str);
  9328. parsebackquote = 0;
  9329. handler = savehandler;
  9330. longjmp(handler->loc, 1);
  9331. }
  9332. INTOFF;
  9333. str = NULL;
  9334. savelen = out - (char *)stackblock();
  9335. if (savelen > 0) {
  9336. str = ckmalloc(savelen);
  9337. memcpy(str, stackblock(), savelen);
  9338. }
  9339. savehandler = handler;
  9340. handler = &jmploc;
  9341. INTON;
  9342. if (oldstyle) {
  9343. /* We must read until the closing backquote, giving special
  9344. treatment to some slashes, and then push the string and
  9345. reread it as input, interpreting it normally. */
  9346. char *pout;
  9347. int pc;
  9348. size_t psavelen;
  9349. char *pstr;
  9350. STARTSTACKSTR(pout);
  9351. for (;;) {
  9352. if (needprompt) {
  9353. setprompt(2);
  9354. }
  9355. switch (pc = pgetc()) {
  9356. case '`':
  9357. goto done;
  9358. case '\\':
  9359. if ((pc = pgetc()) == '\n') {
  9360. plinno++;
  9361. if (doprompt)
  9362. setprompt(2);
  9363. /*
  9364. * If eating a newline, avoid putting
  9365. * the newline into the new character
  9366. * stream (via the STPUTC after the
  9367. * switch).
  9368. */
  9369. continue;
  9370. }
  9371. if (pc != '\\' && pc != '`' && pc != '$'
  9372. && (!dblquote || pc != '"'))
  9373. STPUTC('\\', pout);
  9374. if (pc > PEOA_OR_PEOF) {
  9375. break;
  9376. }
  9377. /* fall through */
  9378. case PEOF:
  9379. #ifdef CONFIG_ASH_ALIAS
  9380. case PEOA:
  9381. #endif
  9382. startlinno = plinno;
  9383. synerror("EOF in backquote substitution");
  9384. case '\n':
  9385. plinno++;
  9386. needprompt = doprompt;
  9387. break;
  9388. default:
  9389. break;
  9390. }
  9391. STPUTC(pc, pout);
  9392. }
  9393. done:
  9394. STPUTC('\0', pout);
  9395. psavelen = pout - (char *)stackblock();
  9396. if (psavelen > 0) {
  9397. pstr = grabstackstr(pout);
  9398. setinputstring(pstr);
  9399. }
  9400. }
  9401. nlpp = &bqlist;
  9402. while (*nlpp)
  9403. nlpp = &(*nlpp)->next;
  9404. *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  9405. (*nlpp)->next = NULL;
  9406. parsebackquote = oldstyle;
  9407. if (oldstyle) {
  9408. saveprompt = doprompt;
  9409. doprompt = 0;
  9410. }
  9411. n = list(2);
  9412. if (oldstyle)
  9413. doprompt = saveprompt;
  9414. else {
  9415. if (readtoken() != TRP)
  9416. synexpect(TRP);
  9417. }
  9418. (*nlpp)->n = n;
  9419. if (oldstyle) {
  9420. /*
  9421. * Start reading from old file again, ignoring any pushed back
  9422. * tokens left from the backquote parsing
  9423. */
  9424. popfile();
  9425. tokpushback = 0;
  9426. }
  9427. while (stackblocksize() <= savelen)
  9428. growstackblock();
  9429. STARTSTACKSTR(out);
  9430. if (str) {
  9431. memcpy(out, str, savelen);
  9432. STADJUST(savelen, out);
  9433. INTOFF;
  9434. ckfree(str);
  9435. str = NULL;
  9436. INTON;
  9437. }
  9438. parsebackquote = savepbq;
  9439. handler = savehandler;
  9440. if (arinest || dblquote)
  9441. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  9442. else
  9443. USTPUTC(CTLBACKQ, out);
  9444. if (oldstyle)
  9445. goto parsebackq_oldreturn;
  9446. else
  9447. goto parsebackq_newreturn;
  9448. }
  9449. #ifdef CONFIG_ASH_MATH_SUPPORT
  9450. /*
  9451. * Parse an arithmetic expansion (indicate start of one and set state)
  9452. */
  9453. parsearith: {
  9454. if (++arinest == 1) {
  9455. prevsyntax = syntax;
  9456. syntax = ARISYNTAX;
  9457. USTPUTC(CTLARI, out);
  9458. if (dblquote)
  9459. USTPUTC('"',out);
  9460. else
  9461. USTPUTC(' ',out);
  9462. } else {
  9463. /*
  9464. * we collapse embedded arithmetic expansion to
  9465. * parenthesis, which should be equivalent
  9466. */
  9467. USTPUTC('(', out);
  9468. }
  9469. goto parsearith_return;
  9470. }
  9471. #endif
  9472. } /* end of readtoken */
  9473. /*
  9474. * Returns true if the text contains nothing to expand (no dollar signs
  9475. * or backquotes).
  9476. */
  9477. static int
  9478. noexpand(char *text)
  9479. {
  9480. char *p;
  9481. char c;
  9482. p = text;
  9483. while ((c = *p++) != '\0') {
  9484. if (c == CTLQUOTEMARK)
  9485. continue;
  9486. if (c == CTLESC)
  9487. p++;
  9488. else if (SIT(c, BASESYNTAX) == CCTL)
  9489. return 0;
  9490. }
  9491. return 1;
  9492. }
  9493. /*
  9494. * Return of a legal variable name (a letter or underscore followed by zero or
  9495. * more letters, underscores, and digits).
  9496. */
  9497. static char *
  9498. endofname(const char *name)
  9499. {
  9500. char *p;
  9501. p = (char *) name;
  9502. if (! is_name(*p))
  9503. return p;
  9504. while (*++p) {
  9505. if (! is_in_name(*p))
  9506. break;
  9507. }
  9508. return p;
  9509. }
  9510. /*
  9511. * Called when an unexpected token is read during the parse. The argument
  9512. * is the token that is expected, or -1 if more than one type of token can
  9513. * occur at this point.
  9514. */
  9515. static void synexpect(int token)
  9516. {
  9517. char msg[64];
  9518. int l;
  9519. l = sprintf(msg, "%s unexpected", tokname(lasttoken));
  9520. if (token >= 0)
  9521. sprintf(msg + l, " (expecting %s)", tokname(token));
  9522. synerror(msg);
  9523. /* NOTREACHED */
  9524. }
  9525. static void
  9526. synerror(const char *msg)
  9527. {
  9528. sh_error("Syntax error: %s", msg);
  9529. /* NOTREACHED */
  9530. }
  9531. /*
  9532. * called by editline -- any expansions to the prompt
  9533. * should be added here.
  9534. */
  9535. #ifdef CONFIG_ASH_EXPAND_PRMT
  9536. static const char *
  9537. expandstr(const char *ps)
  9538. {
  9539. union node n;
  9540. /* XXX Fix (char *) cast. */
  9541. setinputstring((char *)ps);
  9542. readtoken1(pgetc(), DQSYNTAX, nullstr, 0);
  9543. popfile();
  9544. n.narg.type = NARG;
  9545. n.narg.next = NULL;
  9546. n.narg.text = wordtext;
  9547. n.narg.backquote = backquotelist;
  9548. expandarg(&n, NULL, 0);
  9549. return stackblock();
  9550. }
  9551. #endif
  9552. static void setprompt(int whichprompt)
  9553. {
  9554. const char *prompt;
  9555. #ifdef CONFIG_ASH_EXPAND_PRMT
  9556. struct stackmark smark;
  9557. #endif
  9558. needprompt = 0;
  9559. switch (whichprompt) {
  9560. case 1:
  9561. prompt = ps1val();
  9562. break;
  9563. case 2:
  9564. prompt = ps2val();
  9565. break;
  9566. default: /* 0 */
  9567. prompt = nullstr;
  9568. }
  9569. #ifdef CONFIG_ASH_EXPAND_PRMT
  9570. setstackmark(&smark);
  9571. stalloc(stackblocksize());
  9572. #endif
  9573. putprompt(expandstr(prompt));
  9574. #ifdef CONFIG_ASH_EXPAND_PRMT
  9575. popstackmark(&smark);
  9576. #endif
  9577. }
  9578. static const char *const *findkwd(const char *s)
  9579. {
  9580. return bsearch(s, tokname_array + KWDOFFSET,
  9581. (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
  9582. sizeof(const char *), pstrcmp);
  9583. }
  9584. /* redir.c */
  9585. /*
  9586. * Code for dealing with input/output redirection.
  9587. */
  9588. #define EMPTY -2 /* marks an unused slot in redirtab */
  9589. #ifndef PIPE_BUF
  9590. # define PIPESIZE 4096 /* amount of buffering in a pipe */
  9591. #else
  9592. # define PIPESIZE PIPE_BUF
  9593. #endif
  9594. /*
  9595. * Open a file in noclobber mode.
  9596. * The code was copied from bash.
  9597. */
  9598. static int noclobberopen(const char *fname)
  9599. {
  9600. int r, fd;
  9601. struct stat finfo, finfo2;
  9602. /*
  9603. * If the file exists and is a regular file, return an error
  9604. * immediately.
  9605. */
  9606. r = stat(fname, &finfo);
  9607. if (r == 0 && S_ISREG(finfo.st_mode)) {
  9608. errno = EEXIST;
  9609. return -1;
  9610. }
  9611. /*
  9612. * If the file was not present (r != 0), make sure we open it
  9613. * exclusively so that if it is created before we open it, our open
  9614. * will fail. Make sure that we do not truncate an existing file.
  9615. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  9616. * file was not a regular file, we leave O_EXCL off.
  9617. */
  9618. if (r != 0)
  9619. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  9620. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  9621. /* If the open failed, return the file descriptor right away. */
  9622. if (fd < 0)
  9623. return fd;
  9624. /*
  9625. * OK, the open succeeded, but the file may have been changed from a
  9626. * non-regular file to a regular file between the stat and the open.
  9627. * We are assuming that the O_EXCL open handles the case where FILENAME
  9628. * did not exist and is symlinked to an existing file between the stat
  9629. * and open.
  9630. */
  9631. /*
  9632. * If we can open it and fstat the file descriptor, and neither check
  9633. * revealed that it was a regular file, and the file has not been
  9634. * replaced, return the file descriptor.
  9635. */
  9636. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
  9637. finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  9638. return fd;
  9639. /* The file has been replaced. badness. */
  9640. close(fd);
  9641. errno = EEXIST;
  9642. return -1;
  9643. }
  9644. /*
  9645. * Handle here documents. Normally we fork off a process to write the
  9646. * data to a pipe. If the document is short, we can stuff the data in
  9647. * the pipe without forking.
  9648. */
  9649. static int openhere(union node *redir)
  9650. {
  9651. int pip[2];
  9652. size_t len = 0;
  9653. if (pipe(pip) < 0)
  9654. sh_error("Pipe call failed");
  9655. if (redir->type == NHERE) {
  9656. len = strlen(redir->nhere.doc->narg.text);
  9657. if (len <= PIPESIZE) {
  9658. full_write(pip[1], redir->nhere.doc->narg.text, len);
  9659. goto out;
  9660. }
  9661. }
  9662. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  9663. close(pip[0]);
  9664. signal(SIGINT, SIG_IGN);
  9665. signal(SIGQUIT, SIG_IGN);
  9666. signal(SIGHUP, SIG_IGN);
  9667. #ifdef SIGTSTP
  9668. signal(SIGTSTP, SIG_IGN);
  9669. #endif
  9670. signal(SIGPIPE, SIG_DFL);
  9671. if (redir->type == NHERE)
  9672. full_write(pip[1], redir->nhere.doc->narg.text, len);
  9673. else
  9674. expandhere(redir->nhere.doc, pip[1]);
  9675. _exit(0);
  9676. }
  9677. out:
  9678. close(pip[1]);
  9679. return pip[0];
  9680. }
  9681. static int
  9682. openredirect(union node *redir)
  9683. {
  9684. char *fname;
  9685. int f;
  9686. switch (redir->nfile.type) {
  9687. case NFROM:
  9688. fname = redir->nfile.expfname;
  9689. if ((f = open(fname, O_RDONLY)) < 0)
  9690. goto eopen;
  9691. break;
  9692. case NFROMTO:
  9693. fname = redir->nfile.expfname;
  9694. if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
  9695. goto ecreate;
  9696. break;
  9697. case NTO:
  9698. /* Take care of noclobber mode. */
  9699. if (Cflag) {
  9700. fname = redir->nfile.expfname;
  9701. if ((f = noclobberopen(fname)) < 0)
  9702. goto ecreate;
  9703. break;
  9704. }
  9705. /* FALLTHROUGH */
  9706. case NCLOBBER:
  9707. fname = redir->nfile.expfname;
  9708. if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
  9709. goto ecreate;
  9710. break;
  9711. case NAPPEND:
  9712. fname = redir->nfile.expfname;
  9713. if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
  9714. goto ecreate;
  9715. break;
  9716. default:
  9717. #if DEBUG
  9718. abort();
  9719. #endif
  9720. /* Fall through to eliminate warning. */
  9721. case NTOFD:
  9722. case NFROMFD:
  9723. f = -1;
  9724. break;
  9725. case NHERE:
  9726. case NXHERE:
  9727. f = openhere(redir);
  9728. break;
  9729. }
  9730. return f;
  9731. ecreate:
  9732. sh_error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  9733. eopen:
  9734. sh_error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
  9735. }
  9736. static void dupredirect(union node *redir, int f)
  9737. {
  9738. int fd = redir->nfile.fd;
  9739. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  9740. if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
  9741. copyfd(redir->ndup.dupfd, fd);
  9742. }
  9743. return;
  9744. }
  9745. if (f != fd) {
  9746. copyfd(f, fd);
  9747. close(f);
  9748. }
  9749. return;
  9750. }
  9751. /*
  9752. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  9753. * old file descriptors are stashed away so that the redirection can be
  9754. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  9755. * standard output, and the standard error if it becomes a duplicate of
  9756. * stdout, is saved in memory.
  9757. */
  9758. static void
  9759. redirect(union node *redir, int flags)
  9760. {
  9761. union node *n;
  9762. struct redirtab *sv;
  9763. int i;
  9764. int fd;
  9765. int newfd;
  9766. int *p;
  9767. nullredirs++;
  9768. if (!redir) {
  9769. return;
  9770. }
  9771. sv = NULL;
  9772. INTOFF;
  9773. if (flags & REDIR_PUSH) {
  9774. struct redirtab *q;
  9775. q = ckmalloc(sizeof (struct redirtab));
  9776. q->next = redirlist;
  9777. redirlist = q;
  9778. q->nullredirs = nullredirs - 1;
  9779. for (i = 0 ; i < 10 ; i++)
  9780. q->renamed[i] = EMPTY;
  9781. nullredirs = 0;
  9782. sv = q;
  9783. }
  9784. n = redir;
  9785. do {
  9786. fd = n->nfile.fd;
  9787. if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
  9788. n->ndup.dupfd == fd)
  9789. continue; /* redirect from/to same file descriptor */
  9790. newfd = openredirect(n);
  9791. if (fd == newfd)
  9792. continue;
  9793. if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
  9794. i = fcntl(fd, F_DUPFD, 10);
  9795. if (i == -1) {
  9796. i = errno;
  9797. if (i != EBADF) {
  9798. close(newfd);
  9799. errno = i;
  9800. sh_error("%d: %m", fd);
  9801. /* NOTREACHED */
  9802. }
  9803. } else {
  9804. *p = i;
  9805. close(fd);
  9806. }
  9807. } else {
  9808. close(fd);
  9809. }
  9810. dupredirect(n, newfd);
  9811. } while ((n = n->nfile.next));
  9812. INTON;
  9813. if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
  9814. preverrout_fd = sv->renamed[2];
  9815. }
  9816. /*
  9817. * Undo the effects of the last redirection.
  9818. */
  9819. void
  9820. popredir(int drop)
  9821. {
  9822. struct redirtab *rp;
  9823. int i;
  9824. if (--nullredirs >= 0)
  9825. return;
  9826. INTOFF;
  9827. rp = redirlist;
  9828. for (i = 0 ; i < 10 ; i++) {
  9829. if (rp->renamed[i] != EMPTY) {
  9830. if (!drop) {
  9831. close(i);
  9832. copyfd(rp->renamed[i], i);
  9833. }
  9834. close(rp->renamed[i]);
  9835. }
  9836. }
  9837. redirlist = rp->next;
  9838. nullredirs = rp->nullredirs;
  9839. ckfree(rp);
  9840. INTON;
  9841. }
  9842. /*
  9843. * Undo all redirections. Called on error or interrupt.
  9844. */
  9845. /*
  9846. * Discard all saved file descriptors.
  9847. */
  9848. void
  9849. clearredir(int drop)
  9850. {
  9851. for (;;) {
  9852. nullredirs = 0;
  9853. if (!redirlist)
  9854. break;
  9855. popredir(drop);
  9856. }
  9857. }
  9858. /*
  9859. * Copy a file descriptor to be >= to. Returns -1
  9860. * if the source file descriptor is closed, EMPTY if there are no unused
  9861. * file descriptors left.
  9862. */
  9863. int
  9864. copyfd(int from, int to)
  9865. {
  9866. int newfd;
  9867. newfd = fcntl(from, F_DUPFD, to);
  9868. if (newfd < 0) {
  9869. if (errno == EMFILE)
  9870. return EMPTY;
  9871. else
  9872. sh_error("%d: %m", from);
  9873. }
  9874. return newfd;
  9875. }
  9876. int
  9877. redirectsafe(union node *redir, int flags)
  9878. {
  9879. int err;
  9880. volatile int saveint;
  9881. struct jmploc *volatile savehandler = handler;
  9882. struct jmploc jmploc;
  9883. SAVEINT(saveint);
  9884. if (!(err = setjmp(jmploc.loc) * 2)) {
  9885. handler = &jmploc;
  9886. redirect(redir, flags);
  9887. }
  9888. handler = savehandler;
  9889. if (err && exception != EXERROR)
  9890. longjmp(handler->loc, 1);
  9891. RESTOREINT(saveint);
  9892. return err;
  9893. }
  9894. /* show.c */
  9895. #if DEBUG
  9896. static void shtree(union node *, int, char *, FILE*);
  9897. static void shcmd(union node *, FILE *);
  9898. static void sharg(union node *, FILE *);
  9899. static void indent(int, char *, FILE *);
  9900. static void trstring(char *);
  9901. void
  9902. showtree(union node *n)
  9903. {
  9904. trputs("showtree called\n");
  9905. shtree(n, 1, NULL, stdout);
  9906. }
  9907. static void
  9908. shtree(union node *n, int ind, char *pfx, FILE *fp)
  9909. {
  9910. struct nodelist *lp;
  9911. const char *s;
  9912. if (n == NULL)
  9913. return;
  9914. indent(ind, pfx, fp);
  9915. switch(n->type) {
  9916. case NSEMI:
  9917. s = "; ";
  9918. goto binop;
  9919. case NAND:
  9920. s = " && ";
  9921. goto binop;
  9922. case NOR:
  9923. s = " || ";
  9924. binop:
  9925. shtree(n->nbinary.ch1, ind, NULL, fp);
  9926. /* if (ind < 0) */
  9927. fputs(s, fp);
  9928. shtree(n->nbinary.ch2, ind, NULL, fp);
  9929. break;
  9930. case NCMD:
  9931. shcmd(n, fp);
  9932. if (ind >= 0)
  9933. putc('\n', fp);
  9934. break;
  9935. case NPIPE:
  9936. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
  9937. shcmd(lp->n, fp);
  9938. if (lp->next)
  9939. fputs(" | ", fp);
  9940. }
  9941. if (n->npipe.backgnd)
  9942. fputs(" &", fp);
  9943. if (ind >= 0)
  9944. putc('\n', fp);
  9945. break;
  9946. default:
  9947. fprintf(fp, "<node type %d>", n->type);
  9948. if (ind >= 0)
  9949. putc('\n', fp);
  9950. break;
  9951. }
  9952. }
  9953. static void
  9954. shcmd(union node *cmd, FILE *fp)
  9955. {
  9956. union node *np;
  9957. int first;
  9958. const char *s;
  9959. int dftfd;
  9960. first = 1;
  9961. for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
  9962. if (! first)
  9963. putchar(' ');
  9964. sharg(np, fp);
  9965. first = 0;
  9966. }
  9967. for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
  9968. if (! first)
  9969. putchar(' ');
  9970. switch (np->nfile.type) {
  9971. case NTO: s = ">"; dftfd = 1; break;
  9972. case NCLOBBER: s = ">|"; dftfd = 1; break;
  9973. case NAPPEND: s = ">>"; dftfd = 1; break;
  9974. case NTOFD: s = ">&"; dftfd = 1; break;
  9975. case NFROM: s = "<"; dftfd = 0; break;
  9976. case NFROMFD: s = "<&"; dftfd = 0; break;
  9977. case NFROMTO: s = "<>"; dftfd = 0; break;
  9978. default: s = "*error*"; dftfd = 0; break;
  9979. }
  9980. if (np->nfile.fd != dftfd)
  9981. fprintf(fp, "%d", np->nfile.fd);
  9982. fputs(s, fp);
  9983. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  9984. fprintf(fp, "%d", np->ndup.dupfd);
  9985. } else {
  9986. sharg(np->nfile.fname, fp);
  9987. }
  9988. first = 0;
  9989. }
  9990. }
  9991. static void
  9992. sharg(union node *arg, FILE *fp)
  9993. {
  9994. char *p;
  9995. struct nodelist *bqlist;
  9996. int subtype;
  9997. if (arg->type != NARG) {
  9998. out1fmt("<node type %d>\n", arg->type);
  9999. abort();
  10000. }
  10001. bqlist = arg->narg.backquote;
  10002. for (p = arg->narg.text ; *p ; p++) {
  10003. switch (*p) {
  10004. case CTLESC:
  10005. putc(*++p, fp);
  10006. break;
  10007. case CTLVAR:
  10008. putc('$', fp);
  10009. putc('{', fp);
  10010. subtype = *++p;
  10011. if (subtype == VSLENGTH)
  10012. putc('#', fp);
  10013. while (*p != '=')
  10014. putc(*p++, fp);
  10015. if (subtype & VSNUL)
  10016. putc(':', fp);
  10017. switch (subtype & VSTYPE) {
  10018. case VSNORMAL:
  10019. putc('}', fp);
  10020. break;
  10021. case VSMINUS:
  10022. putc('-', fp);
  10023. break;
  10024. case VSPLUS:
  10025. putc('+', fp);
  10026. break;
  10027. case VSQUESTION:
  10028. putc('?', fp);
  10029. break;
  10030. case VSASSIGN:
  10031. putc('=', fp);
  10032. break;
  10033. case VSTRIMLEFT:
  10034. putc('#', fp);
  10035. break;
  10036. case VSTRIMLEFTMAX:
  10037. putc('#', fp);
  10038. putc('#', fp);
  10039. break;
  10040. case VSTRIMRIGHT:
  10041. putc('%', fp);
  10042. break;
  10043. case VSTRIMRIGHTMAX:
  10044. putc('%', fp);
  10045. putc('%', fp);
  10046. break;
  10047. case VSLENGTH:
  10048. break;
  10049. default:
  10050. out1fmt("<subtype %d>", subtype);
  10051. }
  10052. break;
  10053. case CTLENDVAR:
  10054. putc('}', fp);
  10055. break;
  10056. case CTLBACKQ:
  10057. case CTLBACKQ|CTLQUOTE:
  10058. putc('$', fp);
  10059. putc('(', fp);
  10060. shtree(bqlist->n, -1, NULL, fp);
  10061. putc(')', fp);
  10062. break;
  10063. default:
  10064. putc(*p, fp);
  10065. break;
  10066. }
  10067. }
  10068. }
  10069. static void
  10070. indent(int amount, char *pfx, FILE *fp)
  10071. {
  10072. int i;
  10073. for (i = 0 ; i < amount ; i++) {
  10074. if (pfx && i == amount - 1)
  10075. fputs(pfx, fp);
  10076. putc('\t', fp);
  10077. }
  10078. }
  10079. /*
  10080. * Debugging stuff.
  10081. */
  10082. FILE *tracefile;
  10083. void
  10084. trputc(int c)
  10085. {
  10086. if (debug != 1)
  10087. return;
  10088. putc(c, tracefile);
  10089. }
  10090. void
  10091. trace(const char *fmt, ...)
  10092. {
  10093. va_list va;
  10094. if (debug != 1)
  10095. return;
  10096. va_start(va, fmt);
  10097. (void) vfprintf(tracefile, fmt, va);
  10098. va_end(va);
  10099. }
  10100. void
  10101. tracev(const char *fmt, va_list va)
  10102. {
  10103. if (debug != 1)
  10104. return;
  10105. (void) vfprintf(tracefile, fmt, va);
  10106. }
  10107. void
  10108. trputs(const char *s)
  10109. {
  10110. if (debug != 1)
  10111. return;
  10112. fputs(s, tracefile);
  10113. }
  10114. static void
  10115. trstring(char *s)
  10116. {
  10117. char *p;
  10118. char c;
  10119. if (debug != 1)
  10120. return;
  10121. putc('"', tracefile);
  10122. for (p = s ; *p ; p++) {
  10123. switch (*p) {
  10124. case '\n': c = 'n'; goto backslash;
  10125. case '\t': c = 't'; goto backslash;
  10126. case '\r': c = 'r'; goto backslash;
  10127. case '"': c = '"'; goto backslash;
  10128. case '\\': c = '\\'; goto backslash;
  10129. case CTLESC: c = 'e'; goto backslash;
  10130. case CTLVAR: c = 'v'; goto backslash;
  10131. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  10132. case CTLBACKQ: c = 'q'; goto backslash;
  10133. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  10134. backslash: putc('\\', tracefile);
  10135. putc(c, tracefile);
  10136. break;
  10137. default:
  10138. if (*p >= ' ' && *p <= '~')
  10139. putc(*p, tracefile);
  10140. else {
  10141. putc('\\', tracefile);
  10142. putc(*p >> 6 & 03, tracefile);
  10143. putc(*p >> 3 & 07, tracefile);
  10144. putc(*p & 07, tracefile);
  10145. }
  10146. break;
  10147. }
  10148. }
  10149. putc('"', tracefile);
  10150. }
  10151. void
  10152. trargs(char **ap)
  10153. {
  10154. if (debug != 1)
  10155. return;
  10156. while (*ap) {
  10157. trstring(*ap++);
  10158. if (*ap)
  10159. putc(' ', tracefile);
  10160. else
  10161. putc('\n', tracefile);
  10162. }
  10163. }
  10164. void
  10165. opentrace(void)
  10166. {
  10167. char s[100];
  10168. #ifdef O_APPEND
  10169. int flags;
  10170. #endif
  10171. if (debug != 1) {
  10172. if (tracefile)
  10173. fflush(tracefile);
  10174. /* leave open because libedit might be using it */
  10175. return;
  10176. }
  10177. scopy("./trace", s);
  10178. if (tracefile) {
  10179. if (!freopen(s, "a", tracefile)) {
  10180. fprintf(stderr, "Can't re-open %s\n", s);
  10181. debug = 0;
  10182. return;
  10183. }
  10184. } else {
  10185. if ((tracefile = fopen(s, "a")) == NULL) {
  10186. fprintf(stderr, "Can't open %s\n", s);
  10187. debug = 0;
  10188. return;
  10189. }
  10190. }
  10191. #ifdef O_APPEND
  10192. if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
  10193. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  10194. #endif
  10195. setlinebuf(tracefile);
  10196. fputs("\nTracing started.\n", tracefile);
  10197. }
  10198. #endif /* DEBUG */
  10199. /* trap.c */
  10200. /*
  10201. * Sigmode records the current value of the signal handlers for the various
  10202. * modes. A value of zero means that the current handler is not known.
  10203. * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  10204. */
  10205. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  10206. #define S_CATCH 2 /* signal is caught */
  10207. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  10208. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  10209. #define S_RESET 5 /* temporary - to reset a hard ignored sig */
  10210. /*
  10211. * The trap builtin.
  10212. */
  10213. int
  10214. trapcmd(int argc, char **argv)
  10215. {
  10216. char *action;
  10217. char **ap;
  10218. int signo;
  10219. nextopt(nullstr);
  10220. ap = argptr;
  10221. if (!*ap) {
  10222. for (signo = 0 ; signo < NSIG ; signo++) {
  10223. if (trap[signo] != NULL) {
  10224. const char *sn;
  10225. sn = get_signame(signo);
  10226. out1fmt("trap -- %s %s\n",
  10227. single_quote(trap[signo]), sn);
  10228. }
  10229. }
  10230. return 0;
  10231. }
  10232. if (!ap[1])
  10233. action = NULL;
  10234. else
  10235. action = *ap++;
  10236. while (*ap) {
  10237. if ((signo = get_signum(*ap)) < 0)
  10238. sh_error("%s: bad trap", *ap);
  10239. INTOFF;
  10240. if (action) {
  10241. if (action[0] == '-' && action[1] == '\0')
  10242. action = NULL;
  10243. else
  10244. action = savestr(action);
  10245. }
  10246. if (trap[signo])
  10247. ckfree(trap[signo]);
  10248. trap[signo] = action;
  10249. if (signo != 0)
  10250. setsignal(signo);
  10251. INTON;
  10252. ap++;
  10253. }
  10254. return 0;
  10255. }
  10256. /*
  10257. * Clear traps on a fork.
  10258. */
  10259. void
  10260. clear_traps(void)
  10261. {
  10262. char **tp;
  10263. for (tp = trap ; tp < &trap[NSIG] ; tp++) {
  10264. if (*tp && **tp) { /* trap not NULL or SIG_IGN */
  10265. INTOFF;
  10266. ckfree(*tp);
  10267. *tp = NULL;
  10268. if (tp != &trap[0])
  10269. setsignal(tp - trap);
  10270. INTON;
  10271. }
  10272. }
  10273. }
  10274. /*
  10275. * Set the signal handler for the specified signal. The routine figures
  10276. * out what it should be set to.
  10277. */
  10278. void
  10279. setsignal(int signo)
  10280. {
  10281. int action;
  10282. char *t, tsig;
  10283. struct sigaction act;
  10284. if ((t = trap[signo]) == NULL)
  10285. action = S_DFL;
  10286. else if (*t != '\0')
  10287. action = S_CATCH;
  10288. else
  10289. action = S_IGN;
  10290. if (rootshell && action == S_DFL) {
  10291. switch (signo) {
  10292. case SIGINT:
  10293. if (iflag || minusc || sflag == 0)
  10294. action = S_CATCH;
  10295. break;
  10296. case SIGQUIT:
  10297. #if DEBUG
  10298. if (debug)
  10299. break;
  10300. #endif
  10301. /* FALLTHROUGH */
  10302. case SIGTERM:
  10303. if (iflag)
  10304. action = S_IGN;
  10305. break;
  10306. #if JOBS
  10307. case SIGTSTP:
  10308. case SIGTTOU:
  10309. if (mflag)
  10310. action = S_IGN;
  10311. break;
  10312. #endif
  10313. }
  10314. }
  10315. t = &sigmode[signo - 1];
  10316. tsig = *t;
  10317. if (tsig == 0) {
  10318. /*
  10319. * current setting unknown
  10320. */
  10321. if (sigaction(signo, 0, &act) == -1) {
  10322. /*
  10323. * Pretend it worked; maybe we should give a warning
  10324. * here, but other shells don't. We don't alter
  10325. * sigmode, so that we retry every time.
  10326. */
  10327. return;
  10328. }
  10329. if (act.sa_handler == SIG_IGN) {
  10330. if (mflag && (signo == SIGTSTP ||
  10331. signo == SIGTTIN || signo == SIGTTOU)) {
  10332. tsig = S_IGN; /* don't hard ignore these */
  10333. } else
  10334. tsig = S_HARD_IGN;
  10335. } else {
  10336. tsig = S_RESET; /* force to be set */
  10337. }
  10338. }
  10339. if (tsig == S_HARD_IGN || tsig == action)
  10340. return;
  10341. switch (action) {
  10342. case S_CATCH:
  10343. act.sa_handler = onsig;
  10344. break;
  10345. case S_IGN:
  10346. act.sa_handler = SIG_IGN;
  10347. break;
  10348. default:
  10349. act.sa_handler = SIG_DFL;
  10350. }
  10351. *t = action;
  10352. act.sa_flags = 0;
  10353. sigfillset(&act.sa_mask);
  10354. sigaction(signo, &act, 0);
  10355. }
  10356. /*
  10357. * Ignore a signal.
  10358. */
  10359. void
  10360. ignoresig(int signo)
  10361. {
  10362. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  10363. signal(signo, SIG_IGN);
  10364. }
  10365. sigmode[signo - 1] = S_HARD_IGN;
  10366. }
  10367. /*
  10368. * Signal handler.
  10369. */
  10370. void
  10371. onsig(int signo)
  10372. {
  10373. gotsig[signo - 1] = 1;
  10374. pendingsigs = signo;
  10375. if (exsig || (signo == SIGINT && !trap[SIGINT])) {
  10376. if (!suppressint)
  10377. onint();
  10378. intpending = 1;
  10379. }
  10380. }
  10381. /*
  10382. * Called to execute a trap. Perhaps we should avoid entering new trap
  10383. * handlers while we are executing a trap handler.
  10384. */
  10385. int
  10386. dotrap(void)
  10387. {
  10388. char *p;
  10389. char *q;
  10390. int i;
  10391. int savestatus;
  10392. int skip = 0;
  10393. savestatus = exitstatus;
  10394. pendingsigs = 0;
  10395. xbarrier();
  10396. for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
  10397. if (!*q)
  10398. continue;
  10399. *q = 0;
  10400. p = trap[i + 1];
  10401. if (!p)
  10402. continue;
  10403. skip = evalstring(p, SKIPEVAL);
  10404. exitstatus = savestatus;
  10405. if (skip)
  10406. break;
  10407. }
  10408. return skip;
  10409. }
  10410. /*
  10411. * Controls whether the shell is interactive or not.
  10412. */
  10413. void
  10414. setinteractive(int on)
  10415. {
  10416. static int is_interactive;
  10417. if (++on == is_interactive)
  10418. return;
  10419. is_interactive = on;
  10420. setsignal(SIGINT);
  10421. setsignal(SIGQUIT);
  10422. setsignal(SIGTERM);
  10423. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  10424. if(is_interactive > 1) {
  10425. /* Looks like they want an interactive shell */
  10426. static int do_banner;
  10427. if(!do_banner) {
  10428. out1fmt(
  10429. "\n\n%s Built-in shell (ash)\n"
  10430. "Enter 'help' for a list of built-in commands.\n\n",
  10431. BB_BANNER);
  10432. do_banner++;
  10433. }
  10434. }
  10435. #endif
  10436. }
  10437. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  10438. /*** List the available builtins ***/
  10439. static int helpcmd(int argc, char **argv)
  10440. {
  10441. int col, i;
  10442. out1fmt("\nBuilt-in commands:\n-------------------\n");
  10443. for (col = 0, i = 0; i < NUMBUILTINS; i++) {
  10444. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  10445. builtincmd[i].name + 1);
  10446. if (col > 60) {
  10447. out1fmt("\n");
  10448. col = 0;
  10449. }
  10450. }
  10451. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  10452. {
  10453. extern const struct BB_applet applets[];
  10454. extern const size_t NUM_APPLETS;
  10455. for (i = 0; i < NUM_APPLETS; i++) {
  10456. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
  10457. if (col > 60) {
  10458. out1fmt("\n");
  10459. col = 0;
  10460. }
  10461. }
  10462. }
  10463. #endif
  10464. out1fmt("\n\n");
  10465. return EXIT_SUCCESS;
  10466. }
  10467. #endif /* CONFIG_FEATURE_SH_EXTRA_QUIET */
  10468. /*
  10469. * Called to exit the shell.
  10470. */
  10471. void
  10472. exitshell(void)
  10473. {
  10474. struct jmploc loc;
  10475. char *p;
  10476. int status;
  10477. status = exitstatus;
  10478. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  10479. if (setjmp(loc.loc)) {
  10480. if (exception == EXEXIT)
  10481. _exit(exitstatus);
  10482. goto out;
  10483. }
  10484. handler = &loc;
  10485. if ((p = trap[0])) {
  10486. trap[0] = NULL;
  10487. evalstring(p, 0);
  10488. }
  10489. flushall();
  10490. setjobctl(0);
  10491. #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
  10492. if (iflag && rootshell) {
  10493. const char *hp = lookupvar("HISTFILE");
  10494. if(hp != NULL )
  10495. save_history ( hp );
  10496. }
  10497. #endif
  10498. out:
  10499. _exit(status);
  10500. /* NOTREACHED */
  10501. }
  10502. /* var.c */
  10503. static struct var *vartab[VTABSIZE];
  10504. static int vpcmp(const void *, const void *);
  10505. static struct var **findvar(struct var **, const char *);
  10506. /*
  10507. * Initialize the variable symbol tables and import the environment
  10508. */
  10509. #ifdef CONFIG_ASH_GETOPTS
  10510. /*
  10511. * Safe version of setvar, returns 1 on success 0 on failure.
  10512. */
  10513. int
  10514. setvarsafe(const char *name, const char *val, int flags)
  10515. {
  10516. int err;
  10517. volatile int saveint;
  10518. struct jmploc *volatile savehandler = handler;
  10519. struct jmploc jmploc;
  10520. SAVEINT(saveint);
  10521. if (setjmp(jmploc.loc))
  10522. err = 1;
  10523. else {
  10524. handler = &jmploc;
  10525. setvar(name, val, flags);
  10526. err = 0;
  10527. }
  10528. handler = savehandler;
  10529. RESTOREINT(saveint);
  10530. return err;
  10531. }
  10532. #endif
  10533. /*
  10534. * Set the value of a variable. The flags argument is ored with the
  10535. * flags of the variable. If val is NULL, the variable is unset.
  10536. */
  10537. static void
  10538. setvar(const char *name, const char *val, int flags)
  10539. {
  10540. char *p, *q;
  10541. size_t namelen;
  10542. char *nameeq;
  10543. size_t vallen;
  10544. q = endofname(name);
  10545. p = strchrnul(q, '=');
  10546. namelen = p - name;
  10547. if (!namelen || p != q)
  10548. sh_error("%.*s: bad variable name", namelen, name);
  10549. vallen = 0;
  10550. if (val == NULL) {
  10551. flags |= VUNSET;
  10552. } else {
  10553. vallen = strlen(val);
  10554. }
  10555. INTOFF;
  10556. p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen);
  10557. if (val) {
  10558. *p++ = '=';
  10559. p = mempcpy(p, val, vallen);
  10560. }
  10561. *p = '\0';
  10562. setvareq(nameeq, flags | VNOSAVE);
  10563. INTON;
  10564. }
  10565. /*
  10566. * Same as setvar except that the variable and value are passed in
  10567. * the first argument as name=value. Since the first argument will
  10568. * be actually stored in the table, it should not be a string that
  10569. * will go away.
  10570. * Called with interrupts off.
  10571. */
  10572. void
  10573. setvareq(char *s, int flags)
  10574. {
  10575. struct var *vp, **vpp;
  10576. vpp = hashvar(s);
  10577. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  10578. vp = *findvar(vpp, s);
  10579. if (vp) {
  10580. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  10581. const char *n;
  10582. if (flags & VNOSAVE)
  10583. free(s);
  10584. n = vp->text;
  10585. sh_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  10586. }
  10587. if (flags & VNOSET)
  10588. return;
  10589. if (vp->func && (flags & VNOFUNC) == 0)
  10590. (*vp->func)(strchrnul(s, '=') + 1);
  10591. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  10592. ckfree(vp->text);
  10593. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  10594. } else {
  10595. if (flags & VNOSET)
  10596. return;
  10597. /* not found */
  10598. vp = ckmalloc(sizeof (*vp));
  10599. vp->next = *vpp;
  10600. vp->func = NULL;
  10601. *vpp = vp;
  10602. }
  10603. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  10604. s = savestr(s);
  10605. vp->text = s;
  10606. vp->flags = flags;
  10607. }
  10608. /*
  10609. * Process a linked list of variable assignments.
  10610. */
  10611. static void
  10612. listsetvar(struct strlist *list_set_var, int flags)
  10613. {
  10614. struct strlist *lp = list_set_var;
  10615. if (!lp)
  10616. return;
  10617. INTOFF;
  10618. do {
  10619. setvareq(lp->text, flags);
  10620. } while ((lp = lp->next));
  10621. INTON;
  10622. }
  10623. /*
  10624. * Find the value of a variable. Returns NULL if not set.
  10625. */
  10626. static char *
  10627. lookupvar(const char *name)
  10628. {
  10629. struct var *v;
  10630. if ((v = *findvar(hashvar(name), name))) {
  10631. #ifdef DYNAMIC_VAR
  10632. /*
  10633. * Dynamic variables are implemented roughly the same way they are
  10634. * in bash. Namely, they're "special" so long as they aren't unset.
  10635. * As soon as they're unset, they're no longer dynamic, and dynamic
  10636. * lookup will no longer happen at that point. -- PFM.
  10637. */
  10638. if((v->flags & VDYNAMIC))
  10639. (*v->func)(NULL);
  10640. #endif
  10641. if(!(v->flags & VUNSET))
  10642. return strchrnul(v->text, '=') + 1;
  10643. }
  10644. return NULL;
  10645. }
  10646. /*
  10647. * Search the environment of a builtin command.
  10648. */
  10649. static char *
  10650. bltinlookup(const char *name)
  10651. {
  10652. struct strlist *sp;
  10653. for (sp = cmdenviron ; sp ; sp = sp->next) {
  10654. if (varequal(sp->text, name))
  10655. return strchrnul(sp->text, '=') + 1;
  10656. }
  10657. return lookupvar(name);
  10658. }
  10659. /*
  10660. * Generate a list of variables satisfying the given conditions.
  10661. */
  10662. static char **
  10663. listvars(int on, int off, char ***end)
  10664. {
  10665. struct var **vpp;
  10666. struct var *vp;
  10667. char **ep;
  10668. int mask;
  10669. STARTSTACKSTR(ep);
  10670. vpp = vartab;
  10671. mask = on | off;
  10672. do {
  10673. for (vp = *vpp ; vp ; vp = vp->next)
  10674. if ((vp->flags & mask) == on) {
  10675. if (ep == stackstrend())
  10676. ep = growstackstr();
  10677. *ep++ = (char *) vp->text;
  10678. }
  10679. } while (++vpp < vartab + VTABSIZE);
  10680. if (ep == stackstrend())
  10681. ep = growstackstr();
  10682. if (end)
  10683. *end = ep;
  10684. *ep++ = NULL;
  10685. return grabstackstr(ep);
  10686. }
  10687. /*
  10688. * POSIX requires that 'set' (but not export or readonly) output the
  10689. * variables in lexicographic order - by the locale's collating order (sigh).
  10690. * Maybe we could keep them in an ordered balanced binary tree
  10691. * instead of hashed lists.
  10692. * For now just roll 'em through qsort for printing...
  10693. */
  10694. static int
  10695. showvars(const char *sep_prefix, int on, int off)
  10696. {
  10697. const char *sep;
  10698. char **ep, **epend;
  10699. ep = listvars(on, off, &epend);
  10700. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10701. sep = *sep_prefix ? spcstr : sep_prefix;
  10702. for (; ep < epend; ep++) {
  10703. const char *p;
  10704. const char *q;
  10705. p = strchrnul(*ep, '=');
  10706. q = nullstr;
  10707. if (*p)
  10708. q = single_quote(++p);
  10709. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10710. }
  10711. return 0;
  10712. }
  10713. /*
  10714. * The export and readonly commands.
  10715. */
  10716. static int
  10717. exportcmd(int argc, char **argv)
  10718. {
  10719. struct var *vp;
  10720. char *name;
  10721. const char *p;
  10722. char **aptr;
  10723. int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
  10724. int notp;
  10725. notp = nextopt("p") - 'p';
  10726. if (notp && ((name = *(aptr = argptr)))) {
  10727. do {
  10728. if ((p = strchr(name, '=')) != NULL) {
  10729. p++;
  10730. } else {
  10731. if ((vp = *findvar(hashvar(name), name))) {
  10732. vp->flags |= flag;
  10733. continue;
  10734. }
  10735. }
  10736. setvar(name, p, flag);
  10737. } while ((name = *++aptr) != NULL);
  10738. } else {
  10739. showvars(argv[0], flag, 0);
  10740. }
  10741. return 0;
  10742. }
  10743. /*
  10744. * Make a variable a local variable. When a variable is made local, it's
  10745. * value and flags are saved in a localvar structure. The saved values
  10746. * will be restored when the shell function returns. We handle the name
  10747. * "-" as a special case.
  10748. */
  10749. static void mklocal(char *name)
  10750. {
  10751. struct localvar *lvp;
  10752. struct var **vpp;
  10753. struct var *vp;
  10754. INTOFF;
  10755. lvp = ckmalloc(sizeof (struct localvar));
  10756. if (name[0] == '-' && name[1] == '\0') {
  10757. char *p;
  10758. p = ckmalloc(sizeof(optlist));
  10759. lvp->text = memcpy(p, optlist, sizeof(optlist));
  10760. vp = NULL;
  10761. } else {
  10762. char *eq;
  10763. vpp = hashvar(name);
  10764. vp = *findvar(vpp, name);
  10765. eq = strchr(name, '=');
  10766. if (vp == NULL) {
  10767. if (eq)
  10768. setvareq(name, VSTRFIXED);
  10769. else
  10770. setvar(name, NULL, VSTRFIXED);
  10771. vp = *vpp; /* the new variable */
  10772. lvp->flags = VUNSET;
  10773. } else {
  10774. lvp->text = vp->text;
  10775. lvp->flags = vp->flags;
  10776. vp->flags |= VSTRFIXED|VTEXTFIXED;
  10777. if (eq)
  10778. setvareq(name, 0);
  10779. }
  10780. }
  10781. lvp->vp = vp;
  10782. lvp->next = localvars;
  10783. localvars = lvp;
  10784. INTON;
  10785. }
  10786. /*
  10787. * The "local" command.
  10788. */
  10789. static int
  10790. localcmd(int argc, char **argv)
  10791. {
  10792. char *name;
  10793. argv = argptr;
  10794. while ((name = *argv++) != NULL) {
  10795. mklocal(name);
  10796. }
  10797. return 0;
  10798. }
  10799. /*
  10800. * Called after a function returns.
  10801. * Interrupts must be off.
  10802. */
  10803. static void
  10804. poplocalvars(void)
  10805. {
  10806. struct localvar *lvp;
  10807. struct var *vp;
  10808. while ((lvp = localvars) != NULL) {
  10809. localvars = lvp->next;
  10810. vp = lvp->vp;
  10811. TRACE(("poplocalvar %s", vp ? vp->text : "-"));
  10812. if (vp == NULL) { /* $- saved */
  10813. memcpy(optlist, lvp->text, sizeof(optlist));
  10814. ckfree(lvp->text);
  10815. optschanged();
  10816. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  10817. unsetvar(vp->text);
  10818. } else {
  10819. if (vp->func)
  10820. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  10821. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  10822. ckfree(vp->text);
  10823. vp->flags = lvp->flags;
  10824. vp->text = lvp->text;
  10825. }
  10826. ckfree(lvp);
  10827. }
  10828. }
  10829. /*
  10830. * The unset builtin command. We unset the function before we unset the
  10831. * variable to allow a function to be unset when there is a readonly variable
  10832. * with the same name.
  10833. */
  10834. int
  10835. unsetcmd(int argc, char **argv)
  10836. {
  10837. char **ap;
  10838. int i;
  10839. int flag = 0;
  10840. int ret = 0;
  10841. while ((i = nextopt("vf")) != '\0') {
  10842. flag = i;
  10843. }
  10844. for (ap = argptr; *ap ; ap++) {
  10845. if (flag != 'f') {
  10846. i = unsetvar(*ap);
  10847. ret |= i;
  10848. if (!(i & 2))
  10849. continue;
  10850. }
  10851. if (flag != 'v')
  10852. unsetfunc(*ap);
  10853. }
  10854. return ret & 1;
  10855. }
  10856. /*
  10857. * Unset the specified variable.
  10858. */
  10859. int
  10860. unsetvar(const char *s)
  10861. {
  10862. struct var **vpp;
  10863. struct var *vp;
  10864. int retval;
  10865. vpp = findvar(hashvar(s), s);
  10866. vp = *vpp;
  10867. retval = 2;
  10868. if (vp) {
  10869. int flags = vp->flags;
  10870. retval = 1;
  10871. if (flags & VREADONLY)
  10872. goto out;
  10873. #ifdef DYNAMIC_VAR
  10874. vp->flags &= ~VDYNAMIC;
  10875. #endif
  10876. if (flags & VUNSET)
  10877. goto ok;
  10878. if ((flags & VSTRFIXED) == 0) {
  10879. INTOFF;
  10880. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  10881. ckfree(vp->text);
  10882. *vpp = vp->next;
  10883. ckfree(vp);
  10884. INTON;
  10885. } else {
  10886. setvar(s, 0, 0);
  10887. vp->flags &= ~VEXPORT;
  10888. }
  10889. ok:
  10890. retval = 0;
  10891. }
  10892. out:
  10893. return retval;
  10894. }
  10895. /*
  10896. * Find the appropriate entry in the hash table from the name.
  10897. */
  10898. static struct var **
  10899. hashvar(const char *p)
  10900. {
  10901. unsigned int hashval;
  10902. hashval = ((unsigned char) *p) << 4;
  10903. while (*p && *p != '=')
  10904. hashval += (unsigned char) *p++;
  10905. return &vartab[hashval % VTABSIZE];
  10906. }
  10907. /*
  10908. * Compares two strings up to the first = or '\0'. The first
  10909. * string must be terminated by '='; the second may be terminated by
  10910. * either '=' or '\0'.
  10911. */
  10912. int
  10913. varcmp(const char *p, const char *q)
  10914. {
  10915. int c, d;
  10916. while ((c = *p) == (d = *q)) {
  10917. if (!c || c == '=')
  10918. goto out;
  10919. p++;
  10920. q++;
  10921. }
  10922. if (c == '=')
  10923. c = 0;
  10924. if (d == '=')
  10925. d = 0;
  10926. out:
  10927. return c - d;
  10928. }
  10929. static int
  10930. vpcmp(const void *a, const void *b)
  10931. {
  10932. return varcmp(*(const char **)a, *(const char **)b);
  10933. }
  10934. static struct var **
  10935. findvar(struct var **vpp, const char *name)
  10936. {
  10937. for (; *vpp; vpp = &(*vpp)->next) {
  10938. if (varequal((*vpp)->text, name)) {
  10939. break;
  10940. }
  10941. }
  10942. return vpp;
  10943. }
  10944. /* setmode.c */
  10945. #include <sys/times.h>
  10946. static const unsigned char timescmd_str[] = {
  10947. ' ', offsetof(struct tms, tms_utime),
  10948. '\n', offsetof(struct tms, tms_stime),
  10949. ' ', offsetof(struct tms, tms_cutime),
  10950. '\n', offsetof(struct tms, tms_cstime),
  10951. 0
  10952. };
  10953. static int timescmd(int ac, char **av)
  10954. {
  10955. long int clk_tck, s, t;
  10956. const unsigned char *p;
  10957. struct tms buf;
  10958. clk_tck = sysconf(_SC_CLK_TCK);
  10959. times(&buf);
  10960. p = timescmd_str;
  10961. do {
  10962. t = *(clock_t *)(((char *) &buf) + p[1]);
  10963. s = t / clk_tck;
  10964. out1fmt("%ldm%ld.%.3lds%c",
  10965. s/60, s%60,
  10966. ((t - s * clk_tck) * 1000) / clk_tck,
  10967. p[0]);
  10968. } while (*(p += 2));
  10969. return 0;
  10970. }
  10971. #ifdef CONFIG_ASH_MATH_SUPPORT
  10972. static arith_t
  10973. dash_arith(const char *s)
  10974. {
  10975. arith_t result;
  10976. int errcode = 0;
  10977. INTOFF;
  10978. result = arith(s, &errcode);
  10979. if (errcode < 0) {
  10980. if (errcode == -3)
  10981. sh_error("exponent less than 0");
  10982. else if (errcode == -2)
  10983. sh_error("divide by zero");
  10984. else if (errcode == -5)
  10985. sh_error("expression recursion loop detected");
  10986. else
  10987. synerror(s);
  10988. }
  10989. INTON;
  10990. return result;
  10991. }
  10992. /*
  10993. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  10994. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  10995. *
  10996. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  10997. */
  10998. static int
  10999. letcmd(int argc, char **argv)
  11000. {
  11001. char **ap;
  11002. arith_t i = 0;
  11003. ap = argv + 1;
  11004. if(!*ap)
  11005. sh_error("expression expected");
  11006. for (ap = argv + 1; *ap; ap++) {
  11007. i = dash_arith(*ap);
  11008. }
  11009. return !i;
  11010. }
  11011. #endif /* CONFIG_ASH_MATH_SUPPORT */
  11012. /* miscbltin.c */
  11013. /*
  11014. * Miscellaneous builtins.
  11015. */
  11016. #undef rflag
  11017. #ifdef __GLIBC__
  11018. #if __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11019. typedef enum __rlimit_resource rlim_t;
  11020. #endif
  11021. #endif
  11022. /*
  11023. * The read builtin. The -e option causes backslashes to escape the
  11024. * following character.
  11025. *
  11026. * This uses unbuffered input, which may be avoidable in some cases.
  11027. */
  11028. static int
  11029. readcmd(int argc, char **argv)
  11030. {
  11031. char **ap;
  11032. int backslash;
  11033. char c;
  11034. int rflag;
  11035. char *prompt;
  11036. const char *ifs;
  11037. char *p;
  11038. int startword;
  11039. int status;
  11040. int i;
  11041. #if defined(CONFIG_ASH_READ_NCHARS)
  11042. int nch_flag = 0;
  11043. int nchars = 0;
  11044. int silent = 0;
  11045. struct termios tty, old_tty;
  11046. #endif
  11047. #if defined(CONFIG_ASH_READ_TIMEOUT)
  11048. fd_set set;
  11049. struct timeval ts;
  11050. ts.tv_sec = ts.tv_usec = 0;
  11051. #endif
  11052. rflag = 0;
  11053. prompt = NULL;
  11054. #if defined(CONFIG_ASH_READ_NCHARS) && defined(CONFIG_ASH_READ_TIMEOUT)
  11055. while ((i = nextopt("p:rt:n:s")) != '\0')
  11056. #elif defined(CONFIG_ASH_READ_NCHARS)
  11057. while ((i = nextopt("p:rn:s")) != '\0')
  11058. #elif defined(CONFIG_ASH_READ_TIMEOUT)
  11059. while ((i = nextopt("p:rt:")) != '\0')
  11060. #else
  11061. while ((i = nextopt("p:r")) != '\0')
  11062. #endif
  11063. {
  11064. switch(i) {
  11065. case 'p':
  11066. prompt = optionarg;
  11067. break;
  11068. #if defined(CONFIG_ASH_READ_NCHARS)
  11069. case 'n':
  11070. nchars = strtol(optionarg, &p, 10);
  11071. if (*p)
  11072. sh_error("invalid count");
  11073. nch_flag = (nchars > 0);
  11074. break;
  11075. case 's':
  11076. silent = 1;
  11077. break;
  11078. #endif
  11079. #if defined(CONFIG_ASH_READ_TIMEOUT)
  11080. case 't':
  11081. ts.tv_sec = strtol(optionarg, &p, 10);
  11082. ts.tv_usec = 0;
  11083. if (*p == '.') {
  11084. char *p2;
  11085. if (*++p) {
  11086. int scale;
  11087. ts.tv_usec = strtol(p, &p2, 10);
  11088. if (*p2)
  11089. sh_error("invalid timeout");
  11090. scale = p2 - p;
  11091. /* normalize to usec */
  11092. if (scale > 6)
  11093. sh_error("invalid timeout");
  11094. while (scale++ < 6)
  11095. ts.tv_usec *= 10;
  11096. }
  11097. } else if (*p) {
  11098. sh_error("invalid timeout");
  11099. }
  11100. if ( ! ts.tv_sec && ! ts.tv_usec)
  11101. sh_error("invalid timeout");
  11102. break;
  11103. #endif
  11104. case 'r':
  11105. rflag = 1;
  11106. break;
  11107. default:
  11108. break;
  11109. }
  11110. }
  11111. if (prompt && isatty(0)) {
  11112. out2str(prompt);
  11113. }
  11114. if (*(ap = argptr) == NULL)
  11115. sh_error("arg count");
  11116. if ((ifs = bltinlookup("IFS")) == NULL)
  11117. ifs = defifs;
  11118. #if defined(CONFIG_ASH_READ_NCHARS)
  11119. if (nch_flag || silent) {
  11120. tcgetattr(0, &tty);
  11121. old_tty = tty;
  11122. if (nch_flag) {
  11123. tty.c_lflag &= ~ICANON;
  11124. tty.c_cc[VMIN] = nchars;
  11125. }
  11126. if (silent) {
  11127. tty.c_lflag &= ~(ECHO|ECHOK|ECHONL);
  11128. }
  11129. tcsetattr(0, TCSANOW, &tty);
  11130. }
  11131. #endif
  11132. #if defined(CONFIG_ASH_READ_TIMEOUT)
  11133. if (ts.tv_sec || ts.tv_usec) {
  11134. FD_ZERO (&set);
  11135. FD_SET (0, &set);
  11136. i = select (FD_SETSIZE, &set, NULL, NULL, &ts);
  11137. if (!i) {
  11138. #if defined(CONFIG_ASH_READ_NCHARS)
  11139. if (nch_flag)
  11140. tcsetattr(0, TCSANOW, &old_tty);
  11141. #endif
  11142. return 1;
  11143. }
  11144. }
  11145. #endif
  11146. status = 0;
  11147. startword = 1;
  11148. backslash = 0;
  11149. STARTSTACKSTR(p);
  11150. #if defined(CONFIG_ASH_READ_NCHARS)
  11151. while (!nch_flag || nchars--)
  11152. #else
  11153. for (;;)
  11154. #endif
  11155. {
  11156. if (read(0, &c, 1) != 1) {
  11157. status = 1;
  11158. break;
  11159. }
  11160. if (c == '\0')
  11161. continue;
  11162. if (backslash) {
  11163. backslash = 0;
  11164. if (c != '\n')
  11165. goto put;
  11166. continue;
  11167. }
  11168. if (!rflag && c == '\\') {
  11169. backslash++;
  11170. continue;
  11171. }
  11172. if (c == '\n')
  11173. break;
  11174. if (startword && *ifs == ' ' && strchr(ifs, c)) {
  11175. continue;
  11176. }
  11177. startword = 0;
  11178. if (ap[1] != NULL && strchr(ifs, c) != NULL) {
  11179. STACKSTRNUL(p);
  11180. setvar(*ap, stackblock(), 0);
  11181. ap++;
  11182. startword = 1;
  11183. STARTSTACKSTR(p);
  11184. } else {
  11185. put:
  11186. STPUTC(c, p);
  11187. }
  11188. }
  11189. #if defined(CONFIG_ASH_READ_NCHARS)
  11190. if (nch_flag || silent)
  11191. tcsetattr(0, TCSANOW, &old_tty);
  11192. #endif
  11193. STACKSTRNUL(p);
  11194. /* Remove trailing blanks */
  11195. while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
  11196. *p = '\0';
  11197. setvar(*ap, stackblock(), 0);
  11198. while (*++ap != NULL)
  11199. setvar(*ap, nullstr, 0);
  11200. return status;
  11201. }
  11202. static int umaskcmd(int argc, char **argv)
  11203. {
  11204. static const char permuser[3] = "ugo";
  11205. static const char permmode[3] = "rwx";
  11206. static const short int permmask[] = {
  11207. S_IRUSR, S_IWUSR, S_IXUSR,
  11208. S_IRGRP, S_IWGRP, S_IXGRP,
  11209. S_IROTH, S_IWOTH, S_IXOTH
  11210. };
  11211. char *ap;
  11212. mode_t mask;
  11213. int i;
  11214. int symbolic_mode = 0;
  11215. while (nextopt("S") != '\0') {
  11216. symbolic_mode = 1;
  11217. }
  11218. INTOFF;
  11219. mask = umask(0);
  11220. umask(mask);
  11221. INTON;
  11222. if ((ap = *argptr) == NULL) {
  11223. if (symbolic_mode) {
  11224. char buf[18];
  11225. char *p = buf;
  11226. for (i = 0; i < 3; i++) {
  11227. int j;
  11228. *p++ = permuser[i];
  11229. *p++ = '=';
  11230. for (j = 0; j < 3; j++) {
  11231. if ((mask & permmask[3 * i + j]) == 0) {
  11232. *p++ = permmode[j];
  11233. }
  11234. }
  11235. *p++ = ',';
  11236. }
  11237. *--p = 0;
  11238. puts(buf);
  11239. } else {
  11240. out1fmt("%.4o\n", mask);
  11241. }
  11242. } else {
  11243. if (is_digit((unsigned char) *ap)) {
  11244. mask = 0;
  11245. do {
  11246. if (*ap >= '8' || *ap < '0')
  11247. sh_error(illnum, argv[1]);
  11248. mask = (mask << 3) + (*ap - '0');
  11249. } while (*++ap != '\0');
  11250. umask(mask);
  11251. } else {
  11252. mask = ~mask & 0777;
  11253. if (!bb_parse_mode(ap, &mask)) {
  11254. sh_error("Illegal mode: %s", ap);
  11255. }
  11256. umask(~mask & 0777);
  11257. }
  11258. }
  11259. return 0;
  11260. }
  11261. /*
  11262. * ulimit builtin
  11263. *
  11264. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11265. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11266. * ash by J.T. Conklin.
  11267. *
  11268. * Public domain.
  11269. */
  11270. struct limits {
  11271. const char *name;
  11272. int cmd;
  11273. int factor; /* multiply by to get rlim_{cur,max} values */
  11274. char option;
  11275. };
  11276. static const struct limits limits[] = {
  11277. #ifdef RLIMIT_CPU
  11278. { "time(seconds)", RLIMIT_CPU, 1, 't' },
  11279. #endif
  11280. #ifdef RLIMIT_FSIZE
  11281. { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
  11282. #endif
  11283. #ifdef RLIMIT_DATA
  11284. { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
  11285. #endif
  11286. #ifdef RLIMIT_STACK
  11287. { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
  11288. #endif
  11289. #ifdef RLIMIT_CORE
  11290. { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
  11291. #endif
  11292. #ifdef RLIMIT_RSS
  11293. { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
  11294. #endif
  11295. #ifdef RLIMIT_MEMLOCK
  11296. { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
  11297. #endif
  11298. #ifdef RLIMIT_NPROC
  11299. { "process", RLIMIT_NPROC, 1, 'p' },
  11300. #endif
  11301. #ifdef RLIMIT_NOFILE
  11302. { "nofiles", RLIMIT_NOFILE, 1, 'n' },
  11303. #endif
  11304. #ifdef RLIMIT_AS
  11305. { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
  11306. #endif
  11307. #ifdef RLIMIT_LOCKS
  11308. { "locks", RLIMIT_LOCKS, 1, 'w' },
  11309. #endif
  11310. { (char *) 0, 0, 0, '\0' }
  11311. };
  11312. enum limtype { SOFT = 0x1, HARD = 0x2 };
  11313. static void printlim(enum limtype how, const struct rlimit *limit,
  11314. const struct limits *l)
  11315. {
  11316. rlim_t val;
  11317. val = limit->rlim_max;
  11318. if (how & SOFT)
  11319. val = limit->rlim_cur;
  11320. if (val == RLIM_INFINITY)
  11321. out1fmt("unlimited\n");
  11322. else {
  11323. val /= l->factor;
  11324. out1fmt("%lld\n", (long long) val);
  11325. }
  11326. }
  11327. int
  11328. ulimitcmd(int argc, char **argv)
  11329. {
  11330. int c;
  11331. rlim_t val = 0;
  11332. enum limtype how = SOFT | HARD;
  11333. const struct limits *l;
  11334. int set, all = 0;
  11335. int optc, what;
  11336. struct rlimit limit;
  11337. what = 'f';
  11338. while ((optc = nextopt("HSa"
  11339. #ifdef RLIMIT_CPU
  11340. "t"
  11341. #endif
  11342. #ifdef RLIMIT_FSIZE
  11343. "f"
  11344. #endif
  11345. #ifdef RLIMIT_DATA
  11346. "d"
  11347. #endif
  11348. #ifdef RLIMIT_STACK
  11349. "s"
  11350. #endif
  11351. #ifdef RLIMIT_CORE
  11352. "c"
  11353. #endif
  11354. #ifdef RLIMIT_RSS
  11355. "m"
  11356. #endif
  11357. #ifdef RLIMIT_MEMLOCK
  11358. "l"
  11359. #endif
  11360. #ifdef RLIMIT_NPROC
  11361. "p"
  11362. #endif
  11363. #ifdef RLIMIT_NOFILE
  11364. "n"
  11365. #endif
  11366. #ifdef RLIMIT_AS
  11367. "v"
  11368. #endif
  11369. #ifdef RLIMIT_LOCKS
  11370. "w"
  11371. #endif
  11372. )) != '\0')
  11373. switch (optc) {
  11374. case 'H':
  11375. how = HARD;
  11376. break;
  11377. case 'S':
  11378. how = SOFT;
  11379. break;
  11380. case 'a':
  11381. all = 1;
  11382. break;
  11383. default:
  11384. what = optc;
  11385. }
  11386. for (l = limits; l->option != what; l++)
  11387. ;
  11388. set = *argptr ? 1 : 0;
  11389. if (set) {
  11390. char *p = *argptr;
  11391. if (all || argptr[1])
  11392. sh_error("too many arguments");
  11393. if (strncmp(p, "unlimited\n", 9) == 0)
  11394. val = RLIM_INFINITY;
  11395. else {
  11396. val = (rlim_t) 0;
  11397. while ((c = *p++) >= '0' && c <= '9')
  11398. {
  11399. val = (val * 10) + (long)(c - '0');
  11400. if (val < (rlim_t) 0)
  11401. break;
  11402. }
  11403. if (c)
  11404. sh_error("bad number");
  11405. val *= l->factor;
  11406. }
  11407. }
  11408. if (all) {
  11409. for (l = limits; l->name; l++) {
  11410. getrlimit(l->cmd, &limit);
  11411. out1fmt("%-20s ", l->name);
  11412. printlim(how, &limit, l);
  11413. }
  11414. return 0;
  11415. }
  11416. getrlimit(l->cmd, &limit);
  11417. if (set) {
  11418. if (how & HARD)
  11419. limit.rlim_max = val;
  11420. if (how & SOFT)
  11421. limit.rlim_cur = val;
  11422. if (setrlimit(l->cmd, &limit) < 0)
  11423. sh_error("error setting limit (%m)");
  11424. } else {
  11425. printlim(how, &limit, l);
  11426. }
  11427. return 0;
  11428. }
  11429. #ifdef CONFIG_ASH_MATH_SUPPORT
  11430. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  11431. Permission is hereby granted, free of charge, to any person obtaining
  11432. a copy of this software and associated documentation files (the
  11433. "Software"), to deal in the Software without restriction, including
  11434. without limitation the rights to use, copy, modify, merge, publish,
  11435. distribute, sublicense, and/or sell copies of the Software, and to
  11436. permit persons to whom the Software is furnished to do so, subject to
  11437. the following conditions:
  11438. The above copyright notice and this permission notice shall be
  11439. included in all copies or substantial portions of the Software.
  11440. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  11441. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11442. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  11443. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  11444. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  11445. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  11446. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11447. */
  11448. /* This is my infix parser/evaluator. It is optimized for size, intended
  11449. * as a replacement for yacc-based parsers. However, it may well be faster
  11450. * than a comparable parser written in yacc. The supported operators are
  11451. * listed in #defines below. Parens, order of operations, and error handling
  11452. * are supported. This code is thread safe. The exact expression format should
  11453. * be that which POSIX specifies for shells. */
  11454. /* The code uses a simple two-stack algorithm. See
  11455. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  11456. * for a detailed explanation of the infix-to-postfix algorithm on which
  11457. * this is based (this code differs in that it applies operators immediately
  11458. * to the stack instead of adding them to a queue to end up with an
  11459. * expression). */
  11460. /* To use the routine, call it with an expression string and error return
  11461. * pointer */
  11462. /*
  11463. * Aug 24, 2001 Manuel Novoa III
  11464. *
  11465. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  11466. *
  11467. * 1) In arith_apply():
  11468. * a) Cached values of *numptr and &(numptr[-1]).
  11469. * b) Removed redundant test for zero denominator.
  11470. *
  11471. * 2) In arith():
  11472. * a) Eliminated redundant code for processing operator tokens by moving
  11473. * to a table-based implementation. Also folded handling of parens
  11474. * into the table.
  11475. * b) Combined all 3 loops which called arith_apply to reduce generated
  11476. * code size at the cost of speed.
  11477. *
  11478. * 3) The following expressions were treated as valid by the original code:
  11479. * 1() , 0! , 1 ( *3 ) .
  11480. * These bugs have been fixed by internally enclosing the expression in
  11481. * parens and then checking that all binary ops and right parens are
  11482. * preceded by a valid expression (NUM_TOKEN).
  11483. *
  11484. * Note: It may be desirable to replace Aaron's test for whitespace with
  11485. * ctype's isspace() if it is used by another busybox applet or if additional
  11486. * whitespace chars should be considered. Look below the "#include"s for a
  11487. * precompiler test.
  11488. */
  11489. /*
  11490. * Aug 26, 2001 Manuel Novoa III
  11491. *
  11492. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  11493. *
  11494. * Merge in Aaron's comments previously posted to the busybox list,
  11495. * modified slightly to take account of my changes to the code.
  11496. *
  11497. */
  11498. /*
  11499. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11500. *
  11501. * - allow access to variable,
  11502. * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
  11503. * - realize assign syntax (VAR=expr, +=, *= etc)
  11504. * - realize exponentiation (** operator)
  11505. * - realize comma separated - expr, expr
  11506. * - realise ++expr --expr expr++ expr--
  11507. * - realise expr ? expr : expr (but, second expr calculate always)
  11508. * - allow hexadecimal and octal numbers
  11509. * - was restored loses XOR operator
  11510. * - remove one goto label, added three ;-)
  11511. * - protect $((num num)) as true zero expr (Manuel`s error)
  11512. * - always use special isspace(), see comment from bash ;-)
  11513. */
  11514. #define arith_isspace(arithval) \
  11515. (arithval == ' ' || arithval == '\n' || arithval == '\t')
  11516. typedef unsigned char operator;
  11517. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  11518. * precedence, and 3 high bits are an ID unique across operators of that
  11519. * precedence. The ID portion is so that multiple operators can have the
  11520. * same precedence, ensuring that the leftmost one is evaluated first.
  11521. * Consider * and /. */
  11522. #define tok_decl(prec,id) (((id)<<5)|(prec))
  11523. #define PREC(op) ((op) & 0x1F)
  11524. #define TOK_LPAREN tok_decl(0,0)
  11525. #define TOK_COMMA tok_decl(1,0)
  11526. #define TOK_ASSIGN tok_decl(2,0)
  11527. #define TOK_AND_ASSIGN tok_decl(2,1)
  11528. #define TOK_OR_ASSIGN tok_decl(2,2)
  11529. #define TOK_XOR_ASSIGN tok_decl(2,3)
  11530. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  11531. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  11532. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  11533. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  11534. #define TOK_MUL_ASSIGN tok_decl(3,0)
  11535. #define TOK_DIV_ASSIGN tok_decl(3,1)
  11536. #define TOK_REM_ASSIGN tok_decl(3,2)
  11537. /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
  11538. #define convert_prec_is_assing(prec) do { if(prec == 3) prec = 2; } while(0)
  11539. /* conditional is right associativity too */
  11540. #define TOK_CONDITIONAL tok_decl(4,0)
  11541. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  11542. #define TOK_OR tok_decl(5,0)
  11543. #define TOK_AND tok_decl(6,0)
  11544. #define TOK_BOR tok_decl(7,0)
  11545. #define TOK_BXOR tok_decl(8,0)
  11546. #define TOK_BAND tok_decl(9,0)
  11547. #define TOK_EQ tok_decl(10,0)
  11548. #define TOK_NE tok_decl(10,1)
  11549. #define TOK_LT tok_decl(11,0)
  11550. #define TOK_GT tok_decl(11,1)
  11551. #define TOK_GE tok_decl(11,2)
  11552. #define TOK_LE tok_decl(11,3)
  11553. #define TOK_LSHIFT tok_decl(12,0)
  11554. #define TOK_RSHIFT tok_decl(12,1)
  11555. #define TOK_ADD tok_decl(13,0)
  11556. #define TOK_SUB tok_decl(13,1)
  11557. #define TOK_MUL tok_decl(14,0)
  11558. #define TOK_DIV tok_decl(14,1)
  11559. #define TOK_REM tok_decl(14,2)
  11560. /* exponent is right associativity */
  11561. #define TOK_EXPONENT tok_decl(15,1)
  11562. /* For now unary operators. */
  11563. #define UNARYPREC 16
  11564. #define TOK_BNOT tok_decl(UNARYPREC,0)
  11565. #define TOK_NOT tok_decl(UNARYPREC,1)
  11566. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  11567. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  11568. #define PREC_PRE (UNARYPREC+2)
  11569. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  11570. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  11571. #define PREC_POST (UNARYPREC+3)
  11572. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  11573. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  11574. #define SPEC_PREC (UNARYPREC+4)
  11575. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  11576. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  11577. #define NUMPTR (*numstackptr)
  11578. static int tok_have_assign(operator op)
  11579. {
  11580. operator prec = PREC(op);
  11581. convert_prec_is_assing(prec);
  11582. return (prec == PREC(TOK_ASSIGN) ||
  11583. prec == PREC_PRE || prec == PREC_POST);
  11584. }
  11585. static int is_right_associativity(operator prec)
  11586. {
  11587. return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) ||
  11588. prec == PREC(TOK_CONDITIONAL));
  11589. }
  11590. typedef struct ARITCH_VAR_NUM {
  11591. arith_t val;
  11592. arith_t contidional_second_val;
  11593. char contidional_second_val_initialized;
  11594. char *var; /* if NULL then is regular number,
  11595. else is variable name */
  11596. } v_n_t;
  11597. typedef struct CHK_VAR_RECURSIVE_LOOPED {
  11598. const char *var;
  11599. struct CHK_VAR_RECURSIVE_LOOPED *next;
  11600. } chk_var_recursive_looped_t;
  11601. static chk_var_recursive_looped_t *prev_chk_var_recursive;
  11602. static int arith_lookup_val(v_n_t *t)
  11603. {
  11604. if(t->var) {
  11605. const char * p = lookupvar(t->var);
  11606. if(p) {
  11607. int errcode;
  11608. /* recursive try as expression */
  11609. chk_var_recursive_looped_t *cur;
  11610. chk_var_recursive_looped_t cur_save;
  11611. for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
  11612. if(strcmp(cur->var, t->var) == 0) {
  11613. /* expression recursion loop detected */
  11614. return -5;
  11615. }
  11616. }
  11617. /* save current lookuped var name */
  11618. cur = prev_chk_var_recursive;
  11619. cur_save.var = t->var;
  11620. cur_save.next = cur;
  11621. prev_chk_var_recursive = &cur_save;
  11622. t->val = arith (p, &errcode);
  11623. /* restore previous ptr after recursiving */
  11624. prev_chk_var_recursive = cur;
  11625. return errcode;
  11626. } else {
  11627. /* allow undefined var as 0 */
  11628. t->val = 0;
  11629. }
  11630. }
  11631. return 0;
  11632. }
  11633. /* "applying" a token means performing it on the top elements on the integer
  11634. * stack. For a unary operator it will only change the top element, but a
  11635. * binary operator will pop two arguments and push a result */
  11636. static int arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
  11637. {
  11638. v_n_t *numptr_m1;
  11639. arith_t numptr_val, rez;
  11640. int ret_arith_lookup_val;
  11641. if (NUMPTR == numstack) goto err; /* There is no operator that can work
  11642. without arguments */
  11643. numptr_m1 = NUMPTR - 1;
  11644. /* check operand is var with noninteger value */
  11645. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11646. if(ret_arith_lookup_val)
  11647. return ret_arith_lookup_val;
  11648. rez = numptr_m1->val;
  11649. if (op == TOK_UMINUS)
  11650. rez *= -1;
  11651. else if (op == TOK_NOT)
  11652. rez = !rez;
  11653. else if (op == TOK_BNOT)
  11654. rez = ~rez;
  11655. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  11656. rez++;
  11657. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  11658. rez--;
  11659. else if (op != TOK_UPLUS) {
  11660. /* Binary operators */
  11661. /* check and binary operators need two arguments */
  11662. if (numptr_m1 == numstack) goto err;
  11663. /* ... and they pop one */
  11664. --NUMPTR;
  11665. numptr_val = rez;
  11666. if (op == TOK_CONDITIONAL) {
  11667. if(! numptr_m1->contidional_second_val_initialized) {
  11668. /* protect $((expr1 ? expr2)) without ": expr" */
  11669. goto err;
  11670. }
  11671. rez = numptr_m1->contidional_second_val;
  11672. } else if(numptr_m1->contidional_second_val_initialized) {
  11673. /* protect $((expr1 : expr2)) without "expr ? " */
  11674. goto err;
  11675. }
  11676. numptr_m1 = NUMPTR - 1;
  11677. if(op != TOK_ASSIGN) {
  11678. /* check operand is var with noninteger value for not '=' */
  11679. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11680. if(ret_arith_lookup_val)
  11681. return ret_arith_lookup_val;
  11682. }
  11683. if (op == TOK_CONDITIONAL) {
  11684. numptr_m1->contidional_second_val = rez;
  11685. }
  11686. rez = numptr_m1->val;
  11687. if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  11688. rez |= numptr_val;
  11689. else if (op == TOK_OR)
  11690. rez = numptr_val || rez;
  11691. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  11692. rez &= numptr_val;
  11693. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  11694. rez ^= numptr_val;
  11695. else if (op == TOK_AND)
  11696. rez = rez && numptr_val;
  11697. else if (op == TOK_EQ)
  11698. rez = (rez == numptr_val);
  11699. else if (op == TOK_NE)
  11700. rez = (rez != numptr_val);
  11701. else if (op == TOK_GE)
  11702. rez = (rez >= numptr_val);
  11703. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  11704. rez >>= numptr_val;
  11705. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  11706. rez <<= numptr_val;
  11707. else if (op == TOK_GT)
  11708. rez = (rez > numptr_val);
  11709. else if (op == TOK_LT)
  11710. rez = (rez < numptr_val);
  11711. else if (op == TOK_LE)
  11712. rez = (rez <= numptr_val);
  11713. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  11714. rez *= numptr_val;
  11715. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  11716. rez += numptr_val;
  11717. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  11718. rez -= numptr_val;
  11719. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  11720. rez = numptr_val;
  11721. else if (op == TOK_CONDITIONAL_SEP) {
  11722. if (numptr_m1 == numstack) {
  11723. /* protect $((expr : expr)) without "expr ? " */
  11724. goto err;
  11725. }
  11726. numptr_m1->contidional_second_val_initialized = op;
  11727. numptr_m1->contidional_second_val = numptr_val;
  11728. }
  11729. else if (op == TOK_CONDITIONAL) {
  11730. rez = rez ?
  11731. numptr_val : numptr_m1->contidional_second_val;
  11732. }
  11733. else if(op == TOK_EXPONENT) {
  11734. if(numptr_val < 0)
  11735. return -3; /* exponent less than 0 */
  11736. else {
  11737. arith_t c = 1;
  11738. if(numptr_val)
  11739. while(numptr_val--)
  11740. c *= rez;
  11741. rez = c;
  11742. }
  11743. }
  11744. else if(numptr_val==0) /* zero divisor check */
  11745. return -2;
  11746. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  11747. rez /= numptr_val;
  11748. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  11749. rez %= numptr_val;
  11750. }
  11751. if(tok_have_assign(op)) {
  11752. char buf[32];
  11753. if(numptr_m1->var == NULL) {
  11754. /* Hmm, 1=2 ? */
  11755. goto err;
  11756. }
  11757. /* save to shell variable */
  11758. #ifdef CONFIG_ASH_MATH_SUPPORT_64
  11759. snprintf(buf, sizeof(buf), "%lld", arith_t_type rez);
  11760. #else
  11761. snprintf(buf, sizeof(buf), "%ld", arith_t_type rez);
  11762. #endif
  11763. setvar(numptr_m1->var, buf, 0);
  11764. /* after saving, make previous value for v++ or v-- */
  11765. if(op == TOK_POST_INC)
  11766. rez--;
  11767. else if(op == TOK_POST_DEC)
  11768. rez++;
  11769. }
  11770. numptr_m1->val = rez;
  11771. /* protect geting var value, is number now */
  11772. numptr_m1->var = NULL;
  11773. return 0;
  11774. err:
  11775. return -1;
  11776. }
  11777. /* longest must first */
  11778. static const char op_tokens[] = {
  11779. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  11780. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  11781. '<','<', 0, TOK_LSHIFT,
  11782. '>','>', 0, TOK_RSHIFT,
  11783. '|','|', 0, TOK_OR,
  11784. '&','&', 0, TOK_AND,
  11785. '!','=', 0, TOK_NE,
  11786. '<','=', 0, TOK_LE,
  11787. '>','=', 0, TOK_GE,
  11788. '=','=', 0, TOK_EQ,
  11789. '|','=', 0, TOK_OR_ASSIGN,
  11790. '&','=', 0, TOK_AND_ASSIGN,
  11791. '*','=', 0, TOK_MUL_ASSIGN,
  11792. '/','=', 0, TOK_DIV_ASSIGN,
  11793. '%','=', 0, TOK_REM_ASSIGN,
  11794. '+','=', 0, TOK_PLUS_ASSIGN,
  11795. '-','=', 0, TOK_MINUS_ASSIGN,
  11796. '-','-', 0, TOK_POST_DEC,
  11797. '^','=', 0, TOK_XOR_ASSIGN,
  11798. '+','+', 0, TOK_POST_INC,
  11799. '*','*', 0, TOK_EXPONENT,
  11800. '!', 0, TOK_NOT,
  11801. '<', 0, TOK_LT,
  11802. '>', 0, TOK_GT,
  11803. '=', 0, TOK_ASSIGN,
  11804. '|', 0, TOK_BOR,
  11805. '&', 0, TOK_BAND,
  11806. '*', 0, TOK_MUL,
  11807. '/', 0, TOK_DIV,
  11808. '%', 0, TOK_REM,
  11809. '+', 0, TOK_ADD,
  11810. '-', 0, TOK_SUB,
  11811. '^', 0, TOK_BXOR,
  11812. /* uniq */
  11813. '~', 0, TOK_BNOT,
  11814. ',', 0, TOK_COMMA,
  11815. '?', 0, TOK_CONDITIONAL,
  11816. ':', 0, TOK_CONDITIONAL_SEP,
  11817. ')', 0, TOK_RPAREN,
  11818. '(', 0, TOK_LPAREN,
  11819. 0
  11820. };
  11821. /* ptr to ")" */
  11822. #define endexpression &op_tokens[sizeof(op_tokens)-7]
  11823. static arith_t arith (const char *expr, int *perrcode)
  11824. {
  11825. char arithval; /* Current character under analysis */
  11826. operator lasttok, op;
  11827. operator prec;
  11828. const char *p = endexpression;
  11829. int errcode;
  11830. size_t datasizes = strlen(expr) + 2;
  11831. /* Stack of integers */
  11832. /* The proof that there can be no more than strlen(startbuf)/2+1 integers
  11833. * in any given correct or incorrect expression is left as an exercise to
  11834. * the reader. */
  11835. v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
  11836. *numstackptr = numstack;
  11837. /* Stack of operator tokens */
  11838. operator *stack = alloca((datasizes) * sizeof(operator)),
  11839. *stackptr = stack;
  11840. *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
  11841. *perrcode = errcode = 0;
  11842. while(1) {
  11843. if ((arithval = *expr) == 0) {
  11844. if (p == endexpression) {
  11845. /* Null expression. */
  11846. return 0;
  11847. }
  11848. /* This is only reached after all tokens have been extracted from the
  11849. * input stream. If there are still tokens on the operator stack, they
  11850. * are to be applied in order. At the end, there should be a final
  11851. * result on the integer stack */
  11852. if (expr != endexpression + 1) {
  11853. /* If we haven't done so already, */
  11854. /* append a closing right paren */
  11855. expr = endexpression;
  11856. /* and let the loop process it. */
  11857. continue;
  11858. }
  11859. /* At this point, we're done with the expression. */
  11860. if (numstackptr != numstack+1) {
  11861. /* ... but if there isn't, it's bad */
  11862. err:
  11863. return (*perrcode = -1);
  11864. }
  11865. if(numstack->var) {
  11866. /* expression is $((var)) only, lookup now */
  11867. errcode = arith_lookup_val(numstack);
  11868. }
  11869. ret:
  11870. *perrcode = errcode;
  11871. return numstack->val;
  11872. } else {
  11873. /* Continue processing the expression. */
  11874. if (arith_isspace(arithval)) {
  11875. /* Skip whitespace */
  11876. goto prologue;
  11877. }
  11878. if((p = endofname(expr)) != expr) {
  11879. size_t var_name_size = (p-expr) + 1; /* trailing zero */
  11880. numstackptr->var = alloca(var_name_size);
  11881. safe_strncpy(numstackptr->var, expr, var_name_size);
  11882. expr = p;
  11883. num:
  11884. numstackptr->contidional_second_val_initialized = 0;
  11885. numstackptr++;
  11886. lasttok = TOK_NUM;
  11887. continue;
  11888. } else if (is_digit(arithval)) {
  11889. numstackptr->var = NULL;
  11890. #ifdef CONFIG_ASH_MATH_SUPPORT_64
  11891. numstackptr->val = strtoll(expr, (char **) &expr, 0);
  11892. #else
  11893. numstackptr->val = strtol(expr, (char **) &expr, 0);
  11894. #endif
  11895. goto num;
  11896. }
  11897. for(p = op_tokens; ; p++) {
  11898. const char *o;
  11899. if(*p == 0) {
  11900. /* strange operator not found */
  11901. goto err;
  11902. }
  11903. for(o = expr; *p && *o == *p; p++)
  11904. o++;
  11905. if(! *p) {
  11906. /* found */
  11907. expr = o - 1;
  11908. break;
  11909. }
  11910. /* skip tail uncompared token */
  11911. while(*p)
  11912. p++;
  11913. /* skip zero delim */
  11914. p++;
  11915. }
  11916. op = p[1];
  11917. /* post grammar: a++ reduce to num */
  11918. if(lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  11919. lasttok = TOK_NUM;
  11920. /* Plus and minus are binary (not unary) _only_ if the last
  11921. * token was as number, or a right paren (which pretends to be
  11922. * a number, since it evaluates to one). Think about it.
  11923. * It makes sense. */
  11924. if (lasttok != TOK_NUM) {
  11925. switch(op) {
  11926. case TOK_ADD:
  11927. op = TOK_UPLUS;
  11928. break;
  11929. case TOK_SUB:
  11930. op = TOK_UMINUS;
  11931. break;
  11932. case TOK_POST_INC:
  11933. op = TOK_PRE_INC;
  11934. break;
  11935. case TOK_POST_DEC:
  11936. op = TOK_PRE_DEC;
  11937. break;
  11938. }
  11939. }
  11940. /* We don't want a unary operator to cause recursive descent on the
  11941. * stack, because there can be many in a row and it could cause an
  11942. * operator to be evaluated before its argument is pushed onto the
  11943. * integer stack. */
  11944. /* But for binary operators, "apply" everything on the operator
  11945. * stack until we find an operator with a lesser priority than the
  11946. * one we have just extracted. */
  11947. /* Left paren is given the lowest priority so it will never be
  11948. * "applied" in this way.
  11949. * if associativity is right and priority eq, applied also skip
  11950. */
  11951. prec = PREC(op);
  11952. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  11953. /* not left paren or unary */
  11954. if (lasttok != TOK_NUM) {
  11955. /* binary op must be preceded by a num */
  11956. goto err;
  11957. }
  11958. while (stackptr != stack) {
  11959. if (op == TOK_RPAREN) {
  11960. /* The algorithm employed here is simple: while we don't
  11961. * hit an open paren nor the bottom of the stack, pop
  11962. * tokens and apply them */
  11963. if (stackptr[-1] == TOK_LPAREN) {
  11964. --stackptr;
  11965. /* Any operator directly after a */
  11966. lasttok = TOK_NUM;
  11967. /* close paren should consider itself binary */
  11968. goto prologue;
  11969. }
  11970. } else {
  11971. operator prev_prec = PREC(stackptr[-1]);
  11972. convert_prec_is_assing(prec);
  11973. convert_prec_is_assing(prev_prec);
  11974. if (prev_prec < prec)
  11975. break;
  11976. /* check right assoc */
  11977. if(prev_prec == prec && is_right_associativity(prec))
  11978. break;
  11979. }
  11980. errcode = arith_apply(*--stackptr, numstack, &numstackptr);
  11981. if(errcode) goto ret;
  11982. }
  11983. if (op == TOK_RPAREN) {
  11984. goto err;
  11985. }
  11986. }
  11987. /* Push this operator to the stack and remember it. */
  11988. *stackptr++ = lasttok = op;
  11989. prologue:
  11990. ++expr;
  11991. }
  11992. }
  11993. }
  11994. #endif /* CONFIG_ASH_MATH_SUPPORT */
  11995. #if DEBUG
  11996. const char *applet_name = "debug stuff usage";
  11997. int main(int argc, char **argv)
  11998. {
  11999. return ash_main(argc, argv);
  12000. }
  12001. #endif
  12002. /*-
  12003. * Copyright (c) 1989, 1991, 1993, 1994
  12004. * The Regents of the University of California. All rights reserved.
  12005. *
  12006. * This code is derived from software contributed to Berkeley by
  12007. * Kenneth Almquist.
  12008. *
  12009. * Redistribution and use in source and binary forms, with or without
  12010. * modification, are permitted provided that the following conditions
  12011. * are met:
  12012. * 1. Redistributions of source code must retain the above copyright
  12013. * notice, this list of conditions and the following disclaimer.
  12014. * 2. Redistributions in binary form must reproduce the above copyright
  12015. * notice, this list of conditions and the following disclaimer in the
  12016. * documentation and/or other materials provided with the distribution.
  12017. * 3. Neither the name of the University nor the names of its contributors
  12018. * may be used to endorse or promote products derived from this software
  12019. * without specific prior written permission.
  12020. *
  12021. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12022. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12023. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12024. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12025. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12026. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12027. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12028. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12029. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12030. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12031. * SUCH DAMAGE.
  12032. */