ash.c 293 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. /*
  19. * The following should be set to reflect the type of system you have:
  20. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  21. * define SYSV if you are running under System V.
  22. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  23. * define DEBUG=2 to compile in and turn on debugging.
  24. *
  25. * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
  26. * debugging info will be written to ./trace and a quit signal
  27. * will generate a core dump.
  28. */
  29. #define DEBUG 0
  30. /* Tweak debug output verbosity here */
  31. #define DEBUG_TIME 0
  32. #define DEBUG_PID 1
  33. #define DEBUG_SIG 1
  34. #define PROFILE 0
  35. #define JOBS ENABLE_ASH_JOB_CONTROL
  36. #include <paths.h>
  37. #include <setjmp.h>
  38. #include <fnmatch.h>
  39. #include <sys/times.h>
  40. #include "busybox.h" /* for applet_names */
  41. #include "unicode.h"
  42. #include "shell_common.h"
  43. #if ENABLE_SH_MATH_SUPPORT
  44. # include "math.h"
  45. #endif
  46. #if ENABLE_ASH_RANDOM_SUPPORT
  47. # include "random.h"
  48. #else
  49. # define CLEAR_RANDOM_T(rnd) ((void)0)
  50. #endif
  51. #include "NUM_APPLETS.h"
  52. #if NUM_APPLETS == 1
  53. /* STANDALONE does not make sense, and won't compile */
  54. # undef CONFIG_FEATURE_SH_STANDALONE
  55. # undef ENABLE_FEATURE_SH_STANDALONE
  56. # undef IF_FEATURE_SH_STANDALONE
  57. # undef IF_NOT_FEATURE_SH_STANDALONE
  58. # define ENABLE_FEATURE_SH_STANDALONE 0
  59. # define IF_FEATURE_SH_STANDALONE(...)
  60. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  61. #endif
  62. #ifndef PIPE_BUF
  63. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  64. #endif
  65. #if !BB_MMU
  66. # error "Do not even bother, ash will not run on NOMMU machine"
  67. #endif
  68. //config:config ASH
  69. //config: bool "ash"
  70. //config: default y
  71. //config: depends on !NOMMU
  72. //config: help
  73. //config: Tha 'ash' shell adds about 60k in the default configuration and is
  74. //config: the most complete and most pedantically correct shell included with
  75. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  76. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  77. //config: (written by Kenneth Almquist) from NetBSD.
  78. //config:
  79. //config:config ASH_BASH_COMPAT
  80. //config: bool "bash-compatible extensions"
  81. //config: default y
  82. //config: depends on ASH
  83. //config: help
  84. //config: Enable bash-compatible extensions.
  85. //config:
  86. //config:config ASH_IDLE_TIMEOUT
  87. //config: bool "Idle timeout variable"
  88. //config: default n
  89. //config: depends on ASH
  90. //config: help
  91. //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
  92. //config:
  93. //config:config ASH_JOB_CONTROL
  94. //config: bool "Job control"
  95. //config: default y
  96. //config: depends on ASH
  97. //config: help
  98. //config: Enable job control in the ash shell.
  99. //config:
  100. //config:config ASH_ALIAS
  101. //config: bool "Alias support"
  102. //config: default y
  103. //config: depends on ASH
  104. //config: help
  105. //config: Enable alias support in the ash shell.
  106. //config:
  107. //config:config ASH_GETOPTS
  108. //config: bool "Builtin getopt to parse positional parameters"
  109. //config: default y
  110. //config: depends on ASH
  111. //config: help
  112. //config: Enable support for getopts builtin in ash.
  113. //config:
  114. //config:config ASH_BUILTIN_ECHO
  115. //config: bool "Builtin version of 'echo'"
  116. //config: default y
  117. //config: depends on ASH
  118. //config: help
  119. //config: Enable support for echo builtin in ash.
  120. //config:
  121. //config:config ASH_BUILTIN_PRINTF
  122. //config: bool "Builtin version of 'printf'"
  123. //config: default y
  124. //config: depends on ASH
  125. //config: help
  126. //config: Enable support for printf builtin in ash.
  127. //config:
  128. //config:config ASH_BUILTIN_TEST
  129. //config: bool "Builtin version of 'test'"
  130. //config: default y
  131. //config: depends on ASH
  132. //config: help
  133. //config: Enable support for test builtin in ash.
  134. //config:
  135. //config:config ASH_CMDCMD
  136. //config: bool "'command' command to override shell builtins"
  137. //config: default y
  138. //config: depends on ASH
  139. //config: help
  140. //config: Enable support for the ash 'command' builtin, which allows
  141. //config: you to run the specified command with the specified arguments,
  142. //config: even when there is an ash builtin command with the same name.
  143. //config:
  144. //config:config ASH_MAIL
  145. //config: bool "Check for new mail on interactive shells"
  146. //config: default n
  147. //config: depends on ASH
  148. //config: help
  149. //config: Enable "check for new mail" function in the ash shell.
  150. //config:
  151. //config:config ASH_OPTIMIZE_FOR_SIZE
  152. //config: bool "Optimize for size instead of speed"
  153. //config: default y
  154. //config: depends on ASH
  155. //config: help
  156. //config: Compile ash for reduced size at the price of speed.
  157. //config:
  158. //config:config ASH_RANDOM_SUPPORT
  159. //config: bool "Pseudorandom generator and $RANDOM variable"
  160. //config: default y
  161. //config: depends on ASH
  162. //config: help
  163. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  164. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  165. //config: You can reset the generator by using a specified start value.
  166. //config: After "unset RANDOM" the generator will switch off and this
  167. //config: variable will no longer have special treatment.
  168. //config:
  169. //config:config ASH_EXPAND_PRMT
  170. //config: bool "Expand prompt string"
  171. //config: default y
  172. //config: depends on ASH
  173. //config: help
  174. //config: "PS#" may contain volatile content, such as backquote commands.
  175. //config: This option recreates the prompt string from the environment
  176. //config: variable each time it is displayed.
  177. //config:
  178. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  179. //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
  180. //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
  181. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  182. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  183. /* ============ Hash table sizes. Configurable. */
  184. #define VTABSIZE 39
  185. #define ATABSIZE 39
  186. #define CMDTABLESIZE 31 /* should be prime */
  187. /* ============ Shell options */
  188. static const char *const optletters_optnames[] = {
  189. "e" "errexit",
  190. "f" "noglob",
  191. "I" "ignoreeof",
  192. "i" "interactive",
  193. "m" "monitor",
  194. "n" "noexec",
  195. "s" "stdin",
  196. "x" "xtrace",
  197. "v" "verbose",
  198. "C" "noclobber",
  199. "a" "allexport",
  200. "b" "notify",
  201. "u" "nounset",
  202. "\0" "vi"
  203. #if ENABLE_ASH_BASH_COMPAT
  204. ,"\0" "pipefail"
  205. #endif
  206. #if DEBUG
  207. ,"\0" "nolog"
  208. ,"\0" "debug"
  209. #endif
  210. };
  211. #define optletters(n) optletters_optnames[n][0]
  212. #define optnames(n) (optletters_optnames[n] + 1)
  213. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  214. /* ============ Misc data */
  215. #define msg_illnum "Illegal number: %s"
  216. /*
  217. * We enclose jmp_buf in a structure so that we can declare pointers to
  218. * jump locations. The global variable handler contains the location to
  219. * jump to when an exception occurs, and the global variable exception_type
  220. * contains a code identifying the exception. To implement nested
  221. * exception handlers, the user should save the value of handler on entry
  222. * to an inner scope, set handler to point to a jmploc structure for the
  223. * inner scope, and restore handler on exit from the scope.
  224. */
  225. struct jmploc {
  226. jmp_buf loc;
  227. };
  228. struct globals_misc {
  229. /* pid of main shell */
  230. int rootpid;
  231. /* shell level: 0 for the main shell, 1 for its children, and so on */
  232. int shlvl;
  233. #define rootshell (!shlvl)
  234. char *minusc; /* argument to -c option */
  235. char *curdir; // = nullstr; /* current working directory */
  236. char *physdir; // = nullstr; /* physical working directory */
  237. char *arg0; /* value of $0 */
  238. struct jmploc *exception_handler;
  239. volatile int suppress_int; /* counter */
  240. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  241. /* last pending signal */
  242. volatile /*sig_atomic_t*/ smallint pending_sig;
  243. smallint exception_type; /* kind of exception (0..5) */
  244. /* exceptions */
  245. #define EXINT 0 /* SIGINT received */
  246. #define EXERROR 1 /* a generic error */
  247. #define EXSHELLPROC 2 /* execute a shell procedure */
  248. #define EXEXEC 3 /* command execution failed */
  249. #define EXEXIT 4 /* exit the shell */
  250. #define EXSIG 5 /* trapped signal in wait(1) */
  251. smallint isloginsh;
  252. char nullstr[1]; /* zero length string */
  253. char optlist[NOPTS];
  254. #define eflag optlist[0]
  255. #define fflag optlist[1]
  256. #define Iflag optlist[2]
  257. #define iflag optlist[3]
  258. #define mflag optlist[4]
  259. #define nflag optlist[5]
  260. #define sflag optlist[6]
  261. #define xflag optlist[7]
  262. #define vflag optlist[8]
  263. #define Cflag optlist[9]
  264. #define aflag optlist[10]
  265. #define bflag optlist[11]
  266. #define uflag optlist[12]
  267. #define viflag optlist[13]
  268. #if ENABLE_ASH_BASH_COMPAT
  269. # define pipefail optlist[14]
  270. #else
  271. # define pipefail 0
  272. #endif
  273. #if DEBUG
  274. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  275. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  276. #endif
  277. /* trap handler commands */
  278. /*
  279. * Sigmode records the current value of the signal handlers for the various
  280. * modes. A value of zero means that the current handler is not known.
  281. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  282. */
  283. char sigmode[NSIG - 1];
  284. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  285. #define S_CATCH 2 /* signal is caught */
  286. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  287. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  288. /* indicates specified signal received */
  289. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  290. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  291. char *trap[NSIG];
  292. char **trap_ptr; /* used only by "trap hack" */
  293. /* Rarely referenced stuff */
  294. #if ENABLE_ASH_RANDOM_SUPPORT
  295. random_t random_gen;
  296. #endif
  297. pid_t backgndpid; /* pid of last background process */
  298. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  299. };
  300. extern struct globals_misc *const ash_ptr_to_globals_misc;
  301. #define G_misc (*ash_ptr_to_globals_misc)
  302. #define rootpid (G_misc.rootpid )
  303. #define shlvl (G_misc.shlvl )
  304. #define minusc (G_misc.minusc )
  305. #define curdir (G_misc.curdir )
  306. #define physdir (G_misc.physdir )
  307. #define arg0 (G_misc.arg0 )
  308. #define exception_handler (G_misc.exception_handler)
  309. #define exception_type (G_misc.exception_type )
  310. #define suppress_int (G_misc.suppress_int )
  311. #define pending_int (G_misc.pending_int )
  312. #define pending_sig (G_misc.pending_sig )
  313. #define isloginsh (G_misc.isloginsh )
  314. #define nullstr (G_misc.nullstr )
  315. #define optlist (G_misc.optlist )
  316. #define sigmode (G_misc.sigmode )
  317. #define gotsig (G_misc.gotsig )
  318. #define may_have_traps (G_misc.may_have_traps )
  319. #define trap (G_misc.trap )
  320. #define trap_ptr (G_misc.trap_ptr )
  321. #define random_gen (G_misc.random_gen )
  322. #define backgndpid (G_misc.backgndpid )
  323. #define job_warning (G_misc.job_warning)
  324. #define INIT_G_misc() do { \
  325. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  326. barrier(); \
  327. curdir = nullstr; \
  328. physdir = nullstr; \
  329. trap_ptr = trap; \
  330. } while (0)
  331. /* ============ DEBUG */
  332. #if DEBUG
  333. static void trace_printf(const char *fmt, ...);
  334. static void trace_vprintf(const char *fmt, va_list va);
  335. # define TRACE(param) trace_printf param
  336. # define TRACEV(param) trace_vprintf param
  337. # define close(fd) do { \
  338. int dfd = (fd); \
  339. if (close(dfd) < 0) \
  340. bb_error_msg("bug on %d: closing %d(0x%x)", \
  341. __LINE__, dfd, dfd); \
  342. } while (0)
  343. #else
  344. # define TRACE(param)
  345. # define TRACEV(param)
  346. #endif
  347. /* ============ Utility functions */
  348. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  349. static int isdigit_str9(const char *str)
  350. {
  351. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  352. while (--maxlen && isdigit(*str))
  353. str++;
  354. return (*str == '\0');
  355. }
  356. static const char *var_end(const char *var)
  357. {
  358. while (*var)
  359. if (*var++ == '=')
  360. break;
  361. return var;
  362. }
  363. /* ============ Interrupts / exceptions */
  364. static void exitshell(void) NORETURN;
  365. /*
  366. * These macros allow the user to suspend the handling of interrupt signals
  367. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  368. * much more efficient and portable. (But hacking the kernel is so much
  369. * more fun than worrying about efficiency and portability. :-))
  370. */
  371. #define INT_OFF do { \
  372. suppress_int++; \
  373. xbarrier(); \
  374. } while (0)
  375. /*
  376. * Called to raise an exception. Since C doesn't include exceptions, we
  377. * just do a longjmp to the exception handler. The type of exception is
  378. * stored in the global variable "exception_type".
  379. */
  380. static void raise_exception(int) NORETURN;
  381. static void
  382. raise_exception(int e)
  383. {
  384. #if DEBUG
  385. if (exception_handler == NULL)
  386. abort();
  387. #endif
  388. INT_OFF;
  389. exception_type = e;
  390. longjmp(exception_handler->loc, 1);
  391. }
  392. #if DEBUG
  393. #define raise_exception(e) do { \
  394. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  395. raise_exception(e); \
  396. } while (0)
  397. #endif
  398. /*
  399. * Called from trap.c when a SIGINT is received. (If the user specifies
  400. * that SIGINT is to be trapped or ignored using the trap builtin, then
  401. * this routine is not called.) Suppressint is nonzero when interrupts
  402. * are held using the INT_OFF macro. (The test for iflag is just
  403. * defensive programming.)
  404. */
  405. static void raise_interrupt(void) NORETURN;
  406. static void
  407. raise_interrupt(void)
  408. {
  409. int ex_type;
  410. pending_int = 0;
  411. /* Signal is not automatically unmasked after it is raised,
  412. * do it ourself - unmask all signals */
  413. sigprocmask_allsigs(SIG_UNBLOCK);
  414. /* pending_sig = 0; - now done in signal_handler() */
  415. ex_type = EXSIG;
  416. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  417. if (!(rootshell && iflag)) {
  418. /* Kill ourself with SIGINT */
  419. signal(SIGINT, SIG_DFL);
  420. raise(SIGINT);
  421. }
  422. ex_type = EXINT;
  423. }
  424. raise_exception(ex_type);
  425. /* NOTREACHED */
  426. }
  427. #if DEBUG
  428. #define raise_interrupt() do { \
  429. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  430. raise_interrupt(); \
  431. } while (0)
  432. #endif
  433. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  434. int_on(void)
  435. {
  436. xbarrier();
  437. if (--suppress_int == 0 && pending_int) {
  438. raise_interrupt();
  439. }
  440. }
  441. #define INT_ON int_on()
  442. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  443. force_int_on(void)
  444. {
  445. xbarrier();
  446. suppress_int = 0;
  447. if (pending_int)
  448. raise_interrupt();
  449. }
  450. #define FORCE_INT_ON force_int_on()
  451. #define SAVE_INT(v) ((v) = suppress_int)
  452. #define RESTORE_INT(v) do { \
  453. xbarrier(); \
  454. suppress_int = (v); \
  455. if (suppress_int == 0 && pending_int) \
  456. raise_interrupt(); \
  457. } while (0)
  458. /* ============ Stdout/stderr output */
  459. static void
  460. outstr(const char *p, FILE *file)
  461. {
  462. INT_OFF;
  463. fputs(p, file);
  464. INT_ON;
  465. }
  466. static void
  467. flush_stdout_stderr(void)
  468. {
  469. INT_OFF;
  470. fflush_all();
  471. INT_ON;
  472. }
  473. static void
  474. outcslow(int c, FILE *dest)
  475. {
  476. INT_OFF;
  477. putc(c, dest);
  478. fflush(dest);
  479. INT_ON;
  480. }
  481. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  482. static int
  483. out1fmt(const char *fmt, ...)
  484. {
  485. va_list ap;
  486. int r;
  487. INT_OFF;
  488. va_start(ap, fmt);
  489. r = vprintf(fmt, ap);
  490. va_end(ap);
  491. INT_ON;
  492. return r;
  493. }
  494. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  495. static int
  496. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  497. {
  498. va_list ap;
  499. int ret;
  500. va_start(ap, fmt);
  501. INT_OFF;
  502. ret = vsnprintf(outbuf, length, fmt, ap);
  503. va_end(ap);
  504. INT_ON;
  505. return ret;
  506. }
  507. static void
  508. out1str(const char *p)
  509. {
  510. outstr(p, stdout);
  511. }
  512. static void
  513. out2str(const char *p)
  514. {
  515. outstr(p, stderr);
  516. flush_stdout_stderr();
  517. }
  518. /* ============ Parser structures */
  519. /* control characters in argument strings */
  520. #define CTL_FIRST CTLESC
  521. #define CTLESC ((unsigned char)'\201') /* escape next character */
  522. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  523. #define CTLENDVAR ((unsigned char)'\203')
  524. #define CTLBACKQ ((unsigned char)'\204')
  525. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  526. /* CTLBACKQ | CTLQUOTE == '\205' */
  527. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  528. #define CTLENDARI ((unsigned char)'\207')
  529. #define CTLQUOTEMARK ((unsigned char)'\210')
  530. #define CTL_LAST CTLQUOTEMARK
  531. /* variable substitution byte (follows CTLVAR) */
  532. #define VSTYPE 0x0f /* type of variable substitution */
  533. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  534. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  535. /* values of VSTYPE field */
  536. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  537. #define VSMINUS 0x2 /* ${var-text} */
  538. #define VSPLUS 0x3 /* ${var+text} */
  539. #define VSQUESTION 0x4 /* ${var?message} */
  540. #define VSASSIGN 0x5 /* ${var=text} */
  541. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  542. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  543. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  544. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  545. #define VSLENGTH 0xa /* ${#var} */
  546. #if ENABLE_ASH_BASH_COMPAT
  547. #define VSSUBSTR 0xc /* ${var:position:length} */
  548. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  549. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  550. #endif
  551. static const char dolatstr[] ALIGN1 = {
  552. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  553. };
  554. #define NCMD 0
  555. #define NPIPE 1
  556. #define NREDIR 2
  557. #define NBACKGND 3
  558. #define NSUBSHELL 4
  559. #define NAND 5
  560. #define NOR 6
  561. #define NSEMI 7
  562. #define NIF 8
  563. #define NWHILE 9
  564. #define NUNTIL 10
  565. #define NFOR 11
  566. #define NCASE 12
  567. #define NCLIST 13
  568. #define NDEFUN 14
  569. #define NARG 15
  570. #define NTO 16
  571. #if ENABLE_ASH_BASH_COMPAT
  572. #define NTO2 17
  573. #endif
  574. #define NCLOBBER 18
  575. #define NFROM 19
  576. #define NFROMTO 20
  577. #define NAPPEND 21
  578. #define NTOFD 22
  579. #define NFROMFD 23
  580. #define NHERE 24
  581. #define NXHERE 25
  582. #define NNOT 26
  583. #define N_NUMBER 27
  584. union node;
  585. struct ncmd {
  586. smallint type; /* Nxxxx */
  587. union node *assign;
  588. union node *args;
  589. union node *redirect;
  590. };
  591. struct npipe {
  592. smallint type;
  593. smallint pipe_backgnd;
  594. struct nodelist *cmdlist;
  595. };
  596. struct nredir {
  597. smallint type;
  598. union node *n;
  599. union node *redirect;
  600. };
  601. struct nbinary {
  602. smallint type;
  603. union node *ch1;
  604. union node *ch2;
  605. };
  606. struct nif {
  607. smallint type;
  608. union node *test;
  609. union node *ifpart;
  610. union node *elsepart;
  611. };
  612. struct nfor {
  613. smallint type;
  614. union node *args;
  615. union node *body;
  616. char *var;
  617. };
  618. struct ncase {
  619. smallint type;
  620. union node *expr;
  621. union node *cases;
  622. };
  623. struct nclist {
  624. smallint type;
  625. union node *next;
  626. union node *pattern;
  627. union node *body;
  628. };
  629. struct narg {
  630. smallint type;
  631. union node *next;
  632. char *text;
  633. struct nodelist *backquote;
  634. };
  635. /* nfile and ndup layout must match!
  636. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  637. * that it is actually NTO2 (>&file), and change its type.
  638. */
  639. struct nfile {
  640. smallint type;
  641. union node *next;
  642. int fd;
  643. int _unused_dupfd;
  644. union node *fname;
  645. char *expfname;
  646. };
  647. struct ndup {
  648. smallint type;
  649. union node *next;
  650. int fd;
  651. int dupfd;
  652. union node *vname;
  653. char *_unused_expfname;
  654. };
  655. struct nhere {
  656. smallint type;
  657. union node *next;
  658. int fd;
  659. union node *doc;
  660. };
  661. struct nnot {
  662. smallint type;
  663. union node *com;
  664. };
  665. union node {
  666. smallint type;
  667. struct ncmd ncmd;
  668. struct npipe npipe;
  669. struct nredir nredir;
  670. struct nbinary nbinary;
  671. struct nif nif;
  672. struct nfor nfor;
  673. struct ncase ncase;
  674. struct nclist nclist;
  675. struct narg narg;
  676. struct nfile nfile;
  677. struct ndup ndup;
  678. struct nhere nhere;
  679. struct nnot nnot;
  680. };
  681. /*
  682. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  683. * It must be distinct from NULL.
  684. */
  685. #define NODE_EOF ((union node *) -1L)
  686. struct nodelist {
  687. struct nodelist *next;
  688. union node *n;
  689. };
  690. struct funcnode {
  691. int count;
  692. union node n;
  693. };
  694. /*
  695. * Free a parse tree.
  696. */
  697. static void
  698. freefunc(struct funcnode *f)
  699. {
  700. if (f && --f->count < 0)
  701. free(f);
  702. }
  703. /* ============ Debugging output */
  704. #if DEBUG
  705. static FILE *tracefile;
  706. static void
  707. trace_printf(const char *fmt, ...)
  708. {
  709. va_list va;
  710. if (debug != 1)
  711. return;
  712. if (DEBUG_TIME)
  713. fprintf(tracefile, "%u ", (int) time(NULL));
  714. if (DEBUG_PID)
  715. fprintf(tracefile, "[%u] ", (int) getpid());
  716. if (DEBUG_SIG)
  717. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  718. va_start(va, fmt);
  719. vfprintf(tracefile, fmt, va);
  720. va_end(va);
  721. }
  722. static void
  723. trace_vprintf(const char *fmt, va_list va)
  724. {
  725. if (debug != 1)
  726. return;
  727. if (DEBUG_TIME)
  728. fprintf(tracefile, "%u ", (int) time(NULL));
  729. if (DEBUG_PID)
  730. fprintf(tracefile, "[%u] ", (int) getpid());
  731. if (DEBUG_SIG)
  732. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  733. vfprintf(tracefile, fmt, va);
  734. }
  735. static void
  736. trace_puts(const char *s)
  737. {
  738. if (debug != 1)
  739. return;
  740. fputs(s, tracefile);
  741. }
  742. static void
  743. trace_puts_quoted(char *s)
  744. {
  745. char *p;
  746. char c;
  747. if (debug != 1)
  748. return;
  749. putc('"', tracefile);
  750. for (p = s; *p; p++) {
  751. switch ((unsigned char)*p) {
  752. case '\n': c = 'n'; goto backslash;
  753. case '\t': c = 't'; goto backslash;
  754. case '\r': c = 'r'; goto backslash;
  755. case '\"': c = '\"'; goto backslash;
  756. case '\\': c = '\\'; goto backslash;
  757. case CTLESC: c = 'e'; goto backslash;
  758. case CTLVAR: c = 'v'; goto backslash;
  759. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  760. case CTLBACKQ: c = 'q'; goto backslash;
  761. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  762. backslash:
  763. putc('\\', tracefile);
  764. putc(c, tracefile);
  765. break;
  766. default:
  767. if (*p >= ' ' && *p <= '~')
  768. putc(*p, tracefile);
  769. else {
  770. putc('\\', tracefile);
  771. putc((*p >> 6) & 03, tracefile);
  772. putc((*p >> 3) & 07, tracefile);
  773. putc(*p & 07, tracefile);
  774. }
  775. break;
  776. }
  777. }
  778. putc('"', tracefile);
  779. }
  780. static void
  781. trace_puts_args(char **ap)
  782. {
  783. if (debug != 1)
  784. return;
  785. if (!*ap)
  786. return;
  787. while (1) {
  788. trace_puts_quoted(*ap);
  789. if (!*++ap) {
  790. putc('\n', tracefile);
  791. break;
  792. }
  793. putc(' ', tracefile);
  794. }
  795. }
  796. static void
  797. opentrace(void)
  798. {
  799. char s[100];
  800. #ifdef O_APPEND
  801. int flags;
  802. #endif
  803. if (debug != 1) {
  804. if (tracefile)
  805. fflush(tracefile);
  806. /* leave open because libedit might be using it */
  807. return;
  808. }
  809. strcpy(s, "./trace");
  810. if (tracefile) {
  811. if (!freopen(s, "a", tracefile)) {
  812. fprintf(stderr, "Can't re-open %s\n", s);
  813. debug = 0;
  814. return;
  815. }
  816. } else {
  817. tracefile = fopen(s, "a");
  818. if (tracefile == NULL) {
  819. fprintf(stderr, "Can't open %s\n", s);
  820. debug = 0;
  821. return;
  822. }
  823. }
  824. #ifdef O_APPEND
  825. flags = fcntl(fileno(tracefile), F_GETFL);
  826. if (flags >= 0)
  827. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  828. #endif
  829. setlinebuf(tracefile);
  830. fputs("\nTracing started.\n", tracefile);
  831. }
  832. static void
  833. indent(int amount, char *pfx, FILE *fp)
  834. {
  835. int i;
  836. for (i = 0; i < amount; i++) {
  837. if (pfx && i == amount - 1)
  838. fputs(pfx, fp);
  839. putc('\t', fp);
  840. }
  841. }
  842. /* little circular references here... */
  843. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  844. static void
  845. sharg(union node *arg, FILE *fp)
  846. {
  847. char *p;
  848. struct nodelist *bqlist;
  849. unsigned char subtype;
  850. if (arg->type != NARG) {
  851. out1fmt("<node type %d>\n", arg->type);
  852. abort();
  853. }
  854. bqlist = arg->narg.backquote;
  855. for (p = arg->narg.text; *p; p++) {
  856. switch ((unsigned char)*p) {
  857. case CTLESC:
  858. p++;
  859. putc(*p, fp);
  860. break;
  861. case CTLVAR:
  862. putc('$', fp);
  863. putc('{', fp);
  864. subtype = *++p;
  865. if (subtype == VSLENGTH)
  866. putc('#', fp);
  867. while (*p != '=') {
  868. putc(*p, fp);
  869. p++;
  870. }
  871. if (subtype & VSNUL)
  872. putc(':', fp);
  873. switch (subtype & VSTYPE) {
  874. case VSNORMAL:
  875. putc('}', fp);
  876. break;
  877. case VSMINUS:
  878. putc('-', fp);
  879. break;
  880. case VSPLUS:
  881. putc('+', fp);
  882. break;
  883. case VSQUESTION:
  884. putc('?', fp);
  885. break;
  886. case VSASSIGN:
  887. putc('=', fp);
  888. break;
  889. case VSTRIMLEFT:
  890. putc('#', fp);
  891. break;
  892. case VSTRIMLEFTMAX:
  893. putc('#', fp);
  894. putc('#', fp);
  895. break;
  896. case VSTRIMRIGHT:
  897. putc('%', fp);
  898. break;
  899. case VSTRIMRIGHTMAX:
  900. putc('%', fp);
  901. putc('%', fp);
  902. break;
  903. case VSLENGTH:
  904. break;
  905. default:
  906. out1fmt("<subtype %d>", subtype);
  907. }
  908. break;
  909. case CTLENDVAR:
  910. putc('}', fp);
  911. break;
  912. case CTLBACKQ:
  913. case CTLBACKQ|CTLQUOTE:
  914. putc('$', fp);
  915. putc('(', fp);
  916. shtree(bqlist->n, -1, NULL, fp);
  917. putc(')', fp);
  918. break;
  919. default:
  920. putc(*p, fp);
  921. break;
  922. }
  923. }
  924. }
  925. static void
  926. shcmd(union node *cmd, FILE *fp)
  927. {
  928. union node *np;
  929. int first;
  930. const char *s;
  931. int dftfd;
  932. first = 1;
  933. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  934. if (!first)
  935. putc(' ', fp);
  936. sharg(np, fp);
  937. first = 0;
  938. }
  939. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  940. if (!first)
  941. putc(' ', fp);
  942. dftfd = 0;
  943. switch (np->nfile.type) {
  944. case NTO: s = ">>"+1; dftfd = 1; break;
  945. case NCLOBBER: s = ">|"; dftfd = 1; break;
  946. case NAPPEND: s = ">>"; dftfd = 1; break;
  947. #if ENABLE_ASH_BASH_COMPAT
  948. case NTO2:
  949. #endif
  950. case NTOFD: s = ">&"; dftfd = 1; break;
  951. case NFROM: s = "<"; break;
  952. case NFROMFD: s = "<&"; break;
  953. case NFROMTO: s = "<>"; break;
  954. default: s = "*error*"; break;
  955. }
  956. if (np->nfile.fd != dftfd)
  957. fprintf(fp, "%d", np->nfile.fd);
  958. fputs(s, fp);
  959. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  960. fprintf(fp, "%d", np->ndup.dupfd);
  961. } else {
  962. sharg(np->nfile.fname, fp);
  963. }
  964. first = 0;
  965. }
  966. }
  967. static void
  968. shtree(union node *n, int ind, char *pfx, FILE *fp)
  969. {
  970. struct nodelist *lp;
  971. const char *s;
  972. if (n == NULL)
  973. return;
  974. indent(ind, pfx, fp);
  975. if (n == NODE_EOF) {
  976. fputs("<EOF>", fp);
  977. return;
  978. }
  979. switch (n->type) {
  980. case NSEMI:
  981. s = "; ";
  982. goto binop;
  983. case NAND:
  984. s = " && ";
  985. goto binop;
  986. case NOR:
  987. s = " || ";
  988. binop:
  989. shtree(n->nbinary.ch1, ind, NULL, fp);
  990. /* if (ind < 0) */
  991. fputs(s, fp);
  992. shtree(n->nbinary.ch2, ind, NULL, fp);
  993. break;
  994. case NCMD:
  995. shcmd(n, fp);
  996. if (ind >= 0)
  997. putc('\n', fp);
  998. break;
  999. case NPIPE:
  1000. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1001. shtree(lp->n, 0, NULL, fp);
  1002. if (lp->next)
  1003. fputs(" | ", fp);
  1004. }
  1005. if (n->npipe.pipe_backgnd)
  1006. fputs(" &", fp);
  1007. if (ind >= 0)
  1008. putc('\n', fp);
  1009. break;
  1010. default:
  1011. fprintf(fp, "<node type %d>", n->type);
  1012. if (ind >= 0)
  1013. putc('\n', fp);
  1014. break;
  1015. }
  1016. }
  1017. static void
  1018. showtree(union node *n)
  1019. {
  1020. trace_puts("showtree called\n");
  1021. shtree(n, 1, NULL, stderr);
  1022. }
  1023. #endif /* DEBUG */
  1024. /* ============ Parser data */
  1025. /*
  1026. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1027. */
  1028. struct strlist {
  1029. struct strlist *next;
  1030. char *text;
  1031. };
  1032. struct alias;
  1033. struct strpush {
  1034. struct strpush *prev; /* preceding string on stack */
  1035. char *prev_string;
  1036. int prev_left_in_line;
  1037. #if ENABLE_ASH_ALIAS
  1038. struct alias *ap; /* if push was associated with an alias */
  1039. #endif
  1040. char *string; /* remember the string since it may change */
  1041. };
  1042. struct parsefile {
  1043. struct parsefile *prev; /* preceding file on stack */
  1044. int linno; /* current line */
  1045. int pf_fd; /* file descriptor (or -1 if string) */
  1046. int left_in_line; /* number of chars left in this line */
  1047. int left_in_buffer; /* number of chars left in this buffer past the line */
  1048. char *next_to_pgetc; /* next char in buffer */
  1049. char *buf; /* input buffer */
  1050. struct strpush *strpush; /* for pushing strings at this level */
  1051. struct strpush basestrpush; /* so pushing one is fast */
  1052. };
  1053. static struct parsefile basepf; /* top level input file */
  1054. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1055. static int startlinno; /* line # where last token started */
  1056. static char *commandname; /* currently executing command */
  1057. static struct strlist *cmdenviron; /* environment for builtin command */
  1058. static uint8_t exitstatus; /* exit status of last command */
  1059. /* ============ Message printing */
  1060. static void
  1061. ash_vmsg(const char *msg, va_list ap)
  1062. {
  1063. fprintf(stderr, "%s: ", arg0);
  1064. if (commandname) {
  1065. if (strcmp(arg0, commandname))
  1066. fprintf(stderr, "%s: ", commandname);
  1067. if (!iflag || g_parsefile->pf_fd > 0)
  1068. fprintf(stderr, "line %d: ", startlinno);
  1069. }
  1070. vfprintf(stderr, msg, ap);
  1071. outcslow('\n', stderr);
  1072. }
  1073. /*
  1074. * Exverror is called to raise the error exception. If the second argument
  1075. * is not NULL then error prints an error message using printf style
  1076. * formatting. It then raises the error exception.
  1077. */
  1078. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1079. static void
  1080. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1081. {
  1082. #if DEBUG
  1083. if (msg) {
  1084. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  1085. TRACEV((msg, ap));
  1086. TRACE(("\") pid=%d\n", getpid()));
  1087. } else
  1088. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  1089. if (msg)
  1090. #endif
  1091. ash_vmsg(msg, ap);
  1092. flush_stdout_stderr();
  1093. raise_exception(cond);
  1094. /* NOTREACHED */
  1095. }
  1096. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1097. static void
  1098. ash_msg_and_raise_error(const char *msg, ...)
  1099. {
  1100. va_list ap;
  1101. va_start(ap, msg);
  1102. ash_vmsg_and_raise(EXERROR, msg, ap);
  1103. /* NOTREACHED */
  1104. va_end(ap);
  1105. }
  1106. static void raise_error_syntax(const char *) NORETURN;
  1107. static void
  1108. raise_error_syntax(const char *msg)
  1109. {
  1110. ash_msg_and_raise_error("syntax error: %s", msg);
  1111. /* NOTREACHED */
  1112. }
  1113. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1114. static void
  1115. ash_msg_and_raise(int cond, const char *msg, ...)
  1116. {
  1117. va_list ap;
  1118. va_start(ap, msg);
  1119. ash_vmsg_and_raise(cond, msg, ap);
  1120. /* NOTREACHED */
  1121. va_end(ap);
  1122. }
  1123. /*
  1124. * error/warning routines for external builtins
  1125. */
  1126. static void
  1127. ash_msg(const char *fmt, ...)
  1128. {
  1129. va_list ap;
  1130. va_start(ap, fmt);
  1131. ash_vmsg(fmt, ap);
  1132. va_end(ap);
  1133. }
  1134. /*
  1135. * Return a string describing an error. The returned string may be a
  1136. * pointer to a static buffer that will be overwritten on the next call.
  1137. * Action describes the operation that got the error.
  1138. */
  1139. static const char *
  1140. errmsg(int e, const char *em)
  1141. {
  1142. if (e == ENOENT || e == ENOTDIR) {
  1143. return em;
  1144. }
  1145. return strerror(e);
  1146. }
  1147. /* ============ Memory allocation */
  1148. #if 0
  1149. /* I consider these wrappers nearly useless:
  1150. * ok, they return you to nearest exception handler, but
  1151. * how much memory do you leak in the process, making
  1152. * memory starvation worse?
  1153. */
  1154. static void *
  1155. ckrealloc(void * p, size_t nbytes)
  1156. {
  1157. p = realloc(p, nbytes);
  1158. if (!p)
  1159. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1160. return p;
  1161. }
  1162. static void *
  1163. ckmalloc(size_t nbytes)
  1164. {
  1165. return ckrealloc(NULL, nbytes);
  1166. }
  1167. static void *
  1168. ckzalloc(size_t nbytes)
  1169. {
  1170. return memset(ckmalloc(nbytes), 0, nbytes);
  1171. }
  1172. static char *
  1173. ckstrdup(const char *s)
  1174. {
  1175. char *p = strdup(s);
  1176. if (!p)
  1177. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1178. return p;
  1179. }
  1180. #else
  1181. /* Using bbox equivalents. They exit if out of memory */
  1182. # define ckrealloc xrealloc
  1183. # define ckmalloc xmalloc
  1184. # define ckzalloc xzalloc
  1185. # define ckstrdup xstrdup
  1186. #endif
  1187. /*
  1188. * It appears that grabstackstr() will barf with such alignments
  1189. * because stalloc() will return a string allocated in a new stackblock.
  1190. */
  1191. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1192. enum {
  1193. /* Most machines require the value returned from malloc to be aligned
  1194. * in some way. The following macro will get this right
  1195. * on many machines. */
  1196. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1197. /* Minimum size of a block */
  1198. MINSIZE = SHELL_ALIGN(504),
  1199. };
  1200. struct stack_block {
  1201. struct stack_block *prev;
  1202. char space[MINSIZE];
  1203. };
  1204. struct stackmark {
  1205. struct stack_block *stackp;
  1206. char *stacknxt;
  1207. size_t stacknleft;
  1208. struct stackmark *marknext;
  1209. };
  1210. struct globals_memstack {
  1211. struct stack_block *g_stackp; // = &stackbase;
  1212. struct stackmark *markp;
  1213. char *g_stacknxt; // = stackbase.space;
  1214. char *sstrend; // = stackbase.space + MINSIZE;
  1215. size_t g_stacknleft; // = MINSIZE;
  1216. int herefd; // = -1;
  1217. struct stack_block stackbase;
  1218. };
  1219. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1220. #define G_memstack (*ash_ptr_to_globals_memstack)
  1221. #define g_stackp (G_memstack.g_stackp )
  1222. #define markp (G_memstack.markp )
  1223. #define g_stacknxt (G_memstack.g_stacknxt )
  1224. #define sstrend (G_memstack.sstrend )
  1225. #define g_stacknleft (G_memstack.g_stacknleft)
  1226. #define herefd (G_memstack.herefd )
  1227. #define stackbase (G_memstack.stackbase )
  1228. #define INIT_G_memstack() do { \
  1229. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1230. barrier(); \
  1231. g_stackp = &stackbase; \
  1232. g_stacknxt = stackbase.space; \
  1233. g_stacknleft = MINSIZE; \
  1234. sstrend = stackbase.space + MINSIZE; \
  1235. herefd = -1; \
  1236. } while (0)
  1237. #define stackblock() ((void *)g_stacknxt)
  1238. #define stackblocksize() g_stacknleft
  1239. /*
  1240. * Parse trees for commands are allocated in lifo order, so we use a stack
  1241. * to make this more efficient, and also to avoid all sorts of exception
  1242. * handling code to handle interrupts in the middle of a parse.
  1243. *
  1244. * The size 504 was chosen because the Ultrix malloc handles that size
  1245. * well.
  1246. */
  1247. static void *
  1248. stalloc(size_t nbytes)
  1249. {
  1250. char *p;
  1251. size_t aligned;
  1252. aligned = SHELL_ALIGN(nbytes);
  1253. if (aligned > g_stacknleft) {
  1254. size_t len;
  1255. size_t blocksize;
  1256. struct stack_block *sp;
  1257. blocksize = aligned;
  1258. if (blocksize < MINSIZE)
  1259. blocksize = MINSIZE;
  1260. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1261. if (len < blocksize)
  1262. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1263. INT_OFF;
  1264. sp = ckmalloc(len);
  1265. sp->prev = g_stackp;
  1266. g_stacknxt = sp->space;
  1267. g_stacknleft = blocksize;
  1268. sstrend = g_stacknxt + blocksize;
  1269. g_stackp = sp;
  1270. INT_ON;
  1271. }
  1272. p = g_stacknxt;
  1273. g_stacknxt += aligned;
  1274. g_stacknleft -= aligned;
  1275. return p;
  1276. }
  1277. static void *
  1278. stzalloc(size_t nbytes)
  1279. {
  1280. return memset(stalloc(nbytes), 0, nbytes);
  1281. }
  1282. static void
  1283. stunalloc(void *p)
  1284. {
  1285. #if DEBUG
  1286. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1287. write(STDERR_FILENO, "stunalloc\n", 10);
  1288. abort();
  1289. }
  1290. #endif
  1291. g_stacknleft += g_stacknxt - (char *)p;
  1292. g_stacknxt = p;
  1293. }
  1294. /*
  1295. * Like strdup but works with the ash stack.
  1296. */
  1297. static char *
  1298. ststrdup(const char *p)
  1299. {
  1300. size_t len = strlen(p) + 1;
  1301. return memcpy(stalloc(len), p, len);
  1302. }
  1303. static void
  1304. setstackmark(struct stackmark *mark)
  1305. {
  1306. mark->stackp = g_stackp;
  1307. mark->stacknxt = g_stacknxt;
  1308. mark->stacknleft = g_stacknleft;
  1309. mark->marknext = markp;
  1310. markp = mark;
  1311. }
  1312. static void
  1313. popstackmark(struct stackmark *mark)
  1314. {
  1315. struct stack_block *sp;
  1316. if (!mark->stackp)
  1317. return;
  1318. INT_OFF;
  1319. markp = mark->marknext;
  1320. while (g_stackp != mark->stackp) {
  1321. sp = g_stackp;
  1322. g_stackp = sp->prev;
  1323. free(sp);
  1324. }
  1325. g_stacknxt = mark->stacknxt;
  1326. g_stacknleft = mark->stacknleft;
  1327. sstrend = mark->stacknxt + mark->stacknleft;
  1328. INT_ON;
  1329. }
  1330. /*
  1331. * When the parser reads in a string, it wants to stick the string on the
  1332. * stack and only adjust the stack pointer when it knows how big the
  1333. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1334. * of space on top of the stack and stackblocklen returns the length of
  1335. * this block. Growstackblock will grow this space by at least one byte,
  1336. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1337. * part of the block that has been used.
  1338. */
  1339. static void
  1340. growstackblock(void)
  1341. {
  1342. size_t newlen;
  1343. newlen = g_stacknleft * 2;
  1344. if (newlen < g_stacknleft)
  1345. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1346. if (newlen < 128)
  1347. newlen += 128;
  1348. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1349. struct stack_block *oldstackp;
  1350. struct stackmark *xmark;
  1351. struct stack_block *sp;
  1352. struct stack_block *prevstackp;
  1353. size_t grosslen;
  1354. INT_OFF;
  1355. oldstackp = g_stackp;
  1356. sp = g_stackp;
  1357. prevstackp = sp->prev;
  1358. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1359. sp = ckrealloc(sp, grosslen);
  1360. sp->prev = prevstackp;
  1361. g_stackp = sp;
  1362. g_stacknxt = sp->space;
  1363. g_stacknleft = newlen;
  1364. sstrend = sp->space + newlen;
  1365. /*
  1366. * Stack marks pointing to the start of the old block
  1367. * must be relocated to point to the new block
  1368. */
  1369. xmark = markp;
  1370. while (xmark != NULL && xmark->stackp == oldstackp) {
  1371. xmark->stackp = g_stackp;
  1372. xmark->stacknxt = g_stacknxt;
  1373. xmark->stacknleft = g_stacknleft;
  1374. xmark = xmark->marknext;
  1375. }
  1376. INT_ON;
  1377. } else {
  1378. char *oldspace = g_stacknxt;
  1379. size_t oldlen = g_stacknleft;
  1380. char *p = stalloc(newlen);
  1381. /* free the space we just allocated */
  1382. g_stacknxt = memcpy(p, oldspace, oldlen);
  1383. g_stacknleft += newlen;
  1384. }
  1385. }
  1386. static void
  1387. grabstackblock(size_t len)
  1388. {
  1389. len = SHELL_ALIGN(len);
  1390. g_stacknxt += len;
  1391. g_stacknleft -= len;
  1392. }
  1393. /*
  1394. * The following routines are somewhat easier to use than the above.
  1395. * The user declares a variable of type STACKSTR, which may be declared
  1396. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1397. * the user uses the macro STPUTC to add characters to the string. In
  1398. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1399. * grown as necessary. When the user is done, she can just leave the
  1400. * string there and refer to it using stackblock(). Or she can allocate
  1401. * the space for it using grabstackstr(). If it is necessary to allow
  1402. * someone else to use the stack temporarily and then continue to grow
  1403. * the string, the user should use grabstack to allocate the space, and
  1404. * then call ungrabstr(p) to return to the previous mode of operation.
  1405. *
  1406. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1407. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1408. * is space for at least one character.
  1409. */
  1410. static void *
  1411. growstackstr(void)
  1412. {
  1413. size_t len = stackblocksize();
  1414. if (herefd >= 0 && len >= 1024) {
  1415. full_write(herefd, stackblock(), len);
  1416. return stackblock();
  1417. }
  1418. growstackblock();
  1419. return (char *)stackblock() + len;
  1420. }
  1421. /*
  1422. * Called from CHECKSTRSPACE.
  1423. */
  1424. static char *
  1425. makestrspace(size_t newlen, char *p)
  1426. {
  1427. size_t len = p - g_stacknxt;
  1428. size_t size = stackblocksize();
  1429. for (;;) {
  1430. size_t nleft;
  1431. size = stackblocksize();
  1432. nleft = size - len;
  1433. if (nleft >= newlen)
  1434. break;
  1435. growstackblock();
  1436. }
  1437. return (char *)stackblock() + len;
  1438. }
  1439. static char *
  1440. stack_nputstr(const char *s, size_t n, char *p)
  1441. {
  1442. p = makestrspace(n, p);
  1443. p = (char *)memcpy(p, s, n) + n;
  1444. return p;
  1445. }
  1446. static char *
  1447. stack_putstr(const char *s, char *p)
  1448. {
  1449. return stack_nputstr(s, strlen(s), p);
  1450. }
  1451. static char *
  1452. _STPUTC(int c, char *p)
  1453. {
  1454. if (p == sstrend)
  1455. p = growstackstr();
  1456. *p++ = c;
  1457. return p;
  1458. }
  1459. #define STARTSTACKSTR(p) ((p) = stackblock())
  1460. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1461. #define CHECKSTRSPACE(n, p) do { \
  1462. char *q = (p); \
  1463. size_t l = (n); \
  1464. size_t m = sstrend - q; \
  1465. if (l > m) \
  1466. (p) = makestrspace(l, q); \
  1467. } while (0)
  1468. #define USTPUTC(c, p) (*(p)++ = (c))
  1469. #define STACKSTRNUL(p) do { \
  1470. if ((p) == sstrend) \
  1471. (p) = growstackstr(); \
  1472. *(p) = '\0'; \
  1473. } while (0)
  1474. #define STUNPUTC(p) (--(p))
  1475. #define STTOPC(p) ((p)[-1])
  1476. #define STADJUST(amount, p) ((p) += (amount))
  1477. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1478. #define ungrabstackstr(s, p) stunalloc(s)
  1479. #define stackstrend() ((void *)sstrend)
  1480. /* ============ String helpers */
  1481. /*
  1482. * prefix -- see if pfx is a prefix of string.
  1483. */
  1484. static char *
  1485. prefix(const char *string, const char *pfx)
  1486. {
  1487. while (*pfx) {
  1488. if (*pfx++ != *string++)
  1489. return NULL;
  1490. }
  1491. return (char *) string;
  1492. }
  1493. /*
  1494. * Check for a valid number. This should be elsewhere.
  1495. */
  1496. static int
  1497. is_number(const char *p)
  1498. {
  1499. do {
  1500. if (!isdigit(*p))
  1501. return 0;
  1502. } while (*++p != '\0');
  1503. return 1;
  1504. }
  1505. /*
  1506. * Convert a string of digits to an integer, printing an error message on
  1507. * failure.
  1508. */
  1509. static int
  1510. number(const char *s)
  1511. {
  1512. if (!is_number(s))
  1513. ash_msg_and_raise_error(msg_illnum, s);
  1514. return atoi(s);
  1515. }
  1516. /*
  1517. * Produce a possibly single quoted string suitable as input to the shell.
  1518. * The return string is allocated on the stack.
  1519. */
  1520. static char *
  1521. single_quote(const char *s)
  1522. {
  1523. char *p;
  1524. STARTSTACKSTR(p);
  1525. do {
  1526. char *q;
  1527. size_t len;
  1528. len = strchrnul(s, '\'') - s;
  1529. q = p = makestrspace(len + 3, p);
  1530. *q++ = '\'';
  1531. q = (char *)memcpy(q, s, len) + len;
  1532. *q++ = '\'';
  1533. s += len;
  1534. STADJUST(q - p, p);
  1535. if (*s != '\'')
  1536. break;
  1537. len = 0;
  1538. do len++; while (*++s == '\'');
  1539. q = p = makestrspace(len + 3, p);
  1540. *q++ = '"';
  1541. q = (char *)memcpy(q, s - len, len) + len;
  1542. *q++ = '"';
  1543. STADJUST(q - p, p);
  1544. } while (*s);
  1545. USTPUTC('\0', p);
  1546. return stackblock();
  1547. }
  1548. /* ============ nextopt */
  1549. static char **argptr; /* argument list for builtin commands */
  1550. static char *optionarg; /* set by nextopt (like getopt) */
  1551. static char *optptr; /* used by nextopt */
  1552. /*
  1553. * XXX - should get rid of. Have all builtins use getopt(3).
  1554. * The library getopt must have the BSD extension static variable
  1555. * "optreset", otherwise it can't be used within the shell safely.
  1556. *
  1557. * Standard option processing (a la getopt) for builtin routines.
  1558. * The only argument that is passed to nextopt is the option string;
  1559. * the other arguments are unnecessary. It returns the character,
  1560. * or '\0' on end of input.
  1561. */
  1562. static int
  1563. nextopt(const char *optstring)
  1564. {
  1565. char *p;
  1566. const char *q;
  1567. char c;
  1568. p = optptr;
  1569. if (p == NULL || *p == '\0') {
  1570. /* We ate entire "-param", take next one */
  1571. p = *argptr;
  1572. if (p == NULL)
  1573. return '\0';
  1574. if (*p != '-')
  1575. return '\0';
  1576. if (*++p == '\0') /* just "-" ? */
  1577. return '\0';
  1578. argptr++;
  1579. if (LONE_DASH(p)) /* "--" ? */
  1580. return '\0';
  1581. /* p => next "-param" */
  1582. }
  1583. /* p => some option char in the middle of a "-param" */
  1584. c = *p++;
  1585. for (q = optstring; *q != c;) {
  1586. if (*q == '\0')
  1587. ash_msg_and_raise_error("illegal option -%c", c);
  1588. if (*++q == ':')
  1589. q++;
  1590. }
  1591. if (*++q == ':') {
  1592. if (*p == '\0') {
  1593. p = *argptr++;
  1594. if (p == NULL)
  1595. ash_msg_and_raise_error("no arg for -%c option", c);
  1596. }
  1597. optionarg = p;
  1598. p = NULL;
  1599. }
  1600. optptr = p;
  1601. return c;
  1602. }
  1603. /* ============ Shell variables */
  1604. /*
  1605. * The parsefile structure pointed to by the global variable parsefile
  1606. * contains information about the current file being read.
  1607. */
  1608. struct shparam {
  1609. int nparam; /* # of positional parameters (without $0) */
  1610. #if ENABLE_ASH_GETOPTS
  1611. int optind; /* next parameter to be processed by getopts */
  1612. int optoff; /* used by getopts */
  1613. #endif
  1614. unsigned char malloced; /* if parameter list dynamically allocated */
  1615. char **p; /* parameter list */
  1616. };
  1617. /*
  1618. * Free the list of positional parameters.
  1619. */
  1620. static void
  1621. freeparam(volatile struct shparam *param)
  1622. {
  1623. if (param->malloced) {
  1624. char **ap, **ap1;
  1625. ap = ap1 = param->p;
  1626. while (*ap)
  1627. free(*ap++);
  1628. free(ap1);
  1629. }
  1630. }
  1631. #if ENABLE_ASH_GETOPTS
  1632. static void FAST_FUNC getoptsreset(const char *value);
  1633. #endif
  1634. struct var {
  1635. struct var *next; /* next entry in hash list */
  1636. int flags; /* flags are defined above */
  1637. const char *var_text; /* name=value */
  1638. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1639. /* the variable gets set/unset */
  1640. };
  1641. struct localvar {
  1642. struct localvar *next; /* next local variable in list */
  1643. struct var *vp; /* the variable that was made local */
  1644. int flags; /* saved flags */
  1645. const char *text; /* saved text */
  1646. };
  1647. /* flags */
  1648. #define VEXPORT 0x01 /* variable is exported */
  1649. #define VREADONLY 0x02 /* variable cannot be modified */
  1650. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1651. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1652. #define VSTACK 0x10 /* text is allocated on the stack */
  1653. #define VUNSET 0x20 /* the variable is not set */
  1654. #define VNOFUNC 0x40 /* don't call the callback function */
  1655. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1656. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1657. #if ENABLE_ASH_RANDOM_SUPPORT
  1658. # define VDYNAMIC 0x200 /* dynamic variable */
  1659. #else
  1660. # define VDYNAMIC 0
  1661. #endif
  1662. /* Need to be before varinit_data[] */
  1663. #if ENABLE_LOCALE_SUPPORT
  1664. static void FAST_FUNC
  1665. change_lc_all(const char *value)
  1666. {
  1667. if (value && *value != '\0')
  1668. setlocale(LC_ALL, value);
  1669. }
  1670. static void FAST_FUNC
  1671. change_lc_ctype(const char *value)
  1672. {
  1673. if (value && *value != '\0')
  1674. setlocale(LC_CTYPE, value);
  1675. }
  1676. #endif
  1677. #if ENABLE_ASH_MAIL
  1678. static void chkmail(void);
  1679. static void changemail(const char *var_value) FAST_FUNC;
  1680. #else
  1681. # define chkmail() ((void)0)
  1682. #endif
  1683. static void changepath(const char *) FAST_FUNC;
  1684. #if ENABLE_ASH_RANDOM_SUPPORT
  1685. static void change_random(const char *) FAST_FUNC;
  1686. #endif
  1687. static const struct {
  1688. int flags;
  1689. const char *var_text;
  1690. void (*var_func)(const char *) FAST_FUNC;
  1691. } varinit_data[] = {
  1692. /*
  1693. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1694. * some environment strings may be constant.
  1695. */
  1696. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1697. #if ENABLE_ASH_MAIL
  1698. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1699. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1700. #endif
  1701. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1702. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1703. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1704. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1705. #if ENABLE_ASH_GETOPTS
  1706. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1707. #endif
  1708. #if ENABLE_ASH_RANDOM_SUPPORT
  1709. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1710. #endif
  1711. #if ENABLE_LOCALE_SUPPORT
  1712. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1713. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1714. #endif
  1715. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1716. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1717. #endif
  1718. };
  1719. struct redirtab;
  1720. struct globals_var {
  1721. struct shparam shellparam; /* $@ current positional parameters */
  1722. struct redirtab *redirlist;
  1723. int g_nullredirs;
  1724. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1725. struct var *vartab[VTABSIZE];
  1726. struct var varinit[ARRAY_SIZE(varinit_data)];
  1727. };
  1728. extern struct globals_var *const ash_ptr_to_globals_var;
  1729. #define G_var (*ash_ptr_to_globals_var)
  1730. #define shellparam (G_var.shellparam )
  1731. //#define redirlist (G_var.redirlist )
  1732. #define g_nullredirs (G_var.g_nullredirs )
  1733. #define preverrout_fd (G_var.preverrout_fd)
  1734. #define vartab (G_var.vartab )
  1735. #define varinit (G_var.varinit )
  1736. #define INIT_G_var() do { \
  1737. unsigned i; \
  1738. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1739. barrier(); \
  1740. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1741. varinit[i].flags = varinit_data[i].flags; \
  1742. varinit[i].var_text = varinit_data[i].var_text; \
  1743. varinit[i].var_func = varinit_data[i].var_func; \
  1744. } \
  1745. } while (0)
  1746. #define vifs varinit[0]
  1747. #if ENABLE_ASH_MAIL
  1748. # define vmail (&vifs)[1]
  1749. # define vmpath (&vmail)[1]
  1750. # define vpath (&vmpath)[1]
  1751. #else
  1752. # define vpath (&vifs)[1]
  1753. #endif
  1754. #define vps1 (&vpath)[1]
  1755. #define vps2 (&vps1)[1]
  1756. #define vps4 (&vps2)[1]
  1757. #if ENABLE_ASH_GETOPTS
  1758. # define voptind (&vps4)[1]
  1759. # if ENABLE_ASH_RANDOM_SUPPORT
  1760. # define vrandom (&voptind)[1]
  1761. # endif
  1762. #else
  1763. # if ENABLE_ASH_RANDOM_SUPPORT
  1764. # define vrandom (&vps4)[1]
  1765. # endif
  1766. #endif
  1767. /*
  1768. * The following macros access the values of the above variables.
  1769. * They have to skip over the name. They return the null string
  1770. * for unset variables.
  1771. */
  1772. #define ifsval() (vifs.var_text + 4)
  1773. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1774. #if ENABLE_ASH_MAIL
  1775. # define mailval() (vmail.var_text + 5)
  1776. # define mpathval() (vmpath.var_text + 9)
  1777. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1778. #endif
  1779. #define pathval() (vpath.var_text + 5)
  1780. #define ps1val() (vps1.var_text + 4)
  1781. #define ps2val() (vps2.var_text + 4)
  1782. #define ps4val() (vps4.var_text + 4)
  1783. #if ENABLE_ASH_GETOPTS
  1784. # define optindval() (voptind.var_text + 7)
  1785. #endif
  1786. #if ENABLE_ASH_GETOPTS
  1787. static void FAST_FUNC
  1788. getoptsreset(const char *value)
  1789. {
  1790. shellparam.optind = number(value);
  1791. shellparam.optoff = -1;
  1792. }
  1793. #endif
  1794. /* math.h has these, otherwise define our private copies */
  1795. #if !ENABLE_SH_MATH_SUPPORT
  1796. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1797. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1798. /*
  1799. * Return the pointer to the first char which is not part of a legal variable name
  1800. * (a letter or underscore followed by letters, underscores, and digits).
  1801. */
  1802. static const char*
  1803. endofname(const char *name)
  1804. {
  1805. if (!is_name(*name))
  1806. return name;
  1807. while (*++name) {
  1808. if (!is_in_name(*name))
  1809. break;
  1810. }
  1811. return name;
  1812. }
  1813. #endif
  1814. /*
  1815. * Compares two strings up to the first = or '\0'. The first
  1816. * string must be terminated by '='; the second may be terminated by
  1817. * either '=' or '\0'.
  1818. */
  1819. static int
  1820. varcmp(const char *p, const char *q)
  1821. {
  1822. int c, d;
  1823. while ((c = *p) == (d = *q)) {
  1824. if (!c || c == '=')
  1825. goto out;
  1826. p++;
  1827. q++;
  1828. }
  1829. if (c == '=')
  1830. c = '\0';
  1831. if (d == '=')
  1832. d = '\0';
  1833. out:
  1834. return c - d;
  1835. }
  1836. /*
  1837. * Find the appropriate entry in the hash table from the name.
  1838. */
  1839. static struct var **
  1840. hashvar(const char *p)
  1841. {
  1842. unsigned hashval;
  1843. hashval = ((unsigned char) *p) << 4;
  1844. while (*p && *p != '=')
  1845. hashval += (unsigned char) *p++;
  1846. return &vartab[hashval % VTABSIZE];
  1847. }
  1848. static int
  1849. vpcmp(const void *a, const void *b)
  1850. {
  1851. return varcmp(*(const char **)a, *(const char **)b);
  1852. }
  1853. /*
  1854. * This routine initializes the builtin variables.
  1855. */
  1856. static void
  1857. initvar(void)
  1858. {
  1859. struct var *vp;
  1860. struct var *end;
  1861. struct var **vpp;
  1862. /*
  1863. * PS1 depends on uid
  1864. */
  1865. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1866. vps1.var_text = "PS1=\\w \\$ ";
  1867. #else
  1868. if (!geteuid())
  1869. vps1.var_text = "PS1=# ";
  1870. #endif
  1871. vp = varinit;
  1872. end = vp + ARRAY_SIZE(varinit);
  1873. do {
  1874. vpp = hashvar(vp->var_text);
  1875. vp->next = *vpp;
  1876. *vpp = vp;
  1877. } while (++vp < end);
  1878. }
  1879. static struct var **
  1880. findvar(struct var **vpp, const char *name)
  1881. {
  1882. for (; *vpp; vpp = &(*vpp)->next) {
  1883. if (varcmp((*vpp)->var_text, name) == 0) {
  1884. break;
  1885. }
  1886. }
  1887. return vpp;
  1888. }
  1889. /*
  1890. * Find the value of a variable. Returns NULL if not set.
  1891. */
  1892. static const char* FAST_FUNC
  1893. lookupvar(const char *name)
  1894. {
  1895. struct var *v;
  1896. v = *findvar(hashvar(name), name);
  1897. if (v) {
  1898. #if ENABLE_ASH_RANDOM_SUPPORT
  1899. /*
  1900. * Dynamic variables are implemented roughly the same way they are
  1901. * in bash. Namely, they're "special" so long as they aren't unset.
  1902. * As soon as they're unset, they're no longer dynamic, and dynamic
  1903. * lookup will no longer happen at that point. -- PFM.
  1904. */
  1905. if (v->flags & VDYNAMIC)
  1906. v->var_func(NULL);
  1907. #endif
  1908. if (!(v->flags & VUNSET))
  1909. return var_end(v->var_text);
  1910. }
  1911. return NULL;
  1912. }
  1913. /*
  1914. * Search the environment of a builtin command.
  1915. */
  1916. static const char *
  1917. bltinlookup(const char *name)
  1918. {
  1919. struct strlist *sp;
  1920. for (sp = cmdenviron; sp; sp = sp->next) {
  1921. if (varcmp(sp->text, name) == 0)
  1922. return var_end(sp->text);
  1923. }
  1924. return lookupvar(name);
  1925. }
  1926. /*
  1927. * Same as setvar except that the variable and value are passed in
  1928. * the first argument as name=value. Since the first argument will
  1929. * be actually stored in the table, it should not be a string that
  1930. * will go away.
  1931. * Called with interrupts off.
  1932. */
  1933. static void
  1934. setvareq(char *s, int flags)
  1935. {
  1936. struct var *vp, **vpp;
  1937. vpp = hashvar(s);
  1938. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1939. vp = *findvar(vpp, s);
  1940. if (vp) {
  1941. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1942. const char *n;
  1943. if (flags & VNOSAVE)
  1944. free(s);
  1945. n = vp->var_text;
  1946. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1947. }
  1948. if (flags & VNOSET)
  1949. return;
  1950. if (vp->var_func && !(flags & VNOFUNC))
  1951. vp->var_func(var_end(s));
  1952. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  1953. free((char*)vp->var_text);
  1954. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1955. } else {
  1956. /* variable s is not found */
  1957. if (flags & VNOSET)
  1958. return;
  1959. vp = ckzalloc(sizeof(*vp));
  1960. vp->next = *vpp;
  1961. /*vp->func = NULL; - ckzalloc did it */
  1962. *vpp = vp;
  1963. }
  1964. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1965. s = ckstrdup(s);
  1966. vp->var_text = s;
  1967. vp->flags = flags;
  1968. }
  1969. /*
  1970. * Set the value of a variable. The flags argument is ored with the
  1971. * flags of the variable. If val is NULL, the variable is unset.
  1972. */
  1973. static void
  1974. setvar(const char *name, const char *val, int flags)
  1975. {
  1976. const char *q;
  1977. char *p;
  1978. char *nameeq;
  1979. size_t namelen;
  1980. size_t vallen;
  1981. q = endofname(name);
  1982. p = strchrnul(q, '=');
  1983. namelen = p - name;
  1984. if (!namelen || p != q)
  1985. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1986. vallen = 0;
  1987. if (val == NULL) {
  1988. flags |= VUNSET;
  1989. } else {
  1990. vallen = strlen(val);
  1991. }
  1992. INT_OFF;
  1993. nameeq = ckmalloc(namelen + vallen + 2);
  1994. p = memcpy(nameeq, name, namelen) + namelen;
  1995. if (val) {
  1996. *p++ = '=';
  1997. p = memcpy(p, val, vallen) + vallen;
  1998. }
  1999. *p = '\0';
  2000. setvareq(nameeq, flags | VNOSAVE);
  2001. INT_ON;
  2002. }
  2003. static void FAST_FUNC
  2004. setvar2(const char *name, const char *val)
  2005. {
  2006. setvar(name, val, 0);
  2007. }
  2008. #if ENABLE_ASH_GETOPTS
  2009. /*
  2010. * Safe version of setvar, returns 1 on success 0 on failure.
  2011. */
  2012. static int
  2013. setvarsafe(const char *name, const char *val, int flags)
  2014. {
  2015. int err;
  2016. volatile int saveint;
  2017. struct jmploc *volatile savehandler = exception_handler;
  2018. struct jmploc jmploc;
  2019. SAVE_INT(saveint);
  2020. if (setjmp(jmploc.loc))
  2021. err = 1;
  2022. else {
  2023. exception_handler = &jmploc;
  2024. setvar(name, val, flags);
  2025. err = 0;
  2026. }
  2027. exception_handler = savehandler;
  2028. RESTORE_INT(saveint);
  2029. return err;
  2030. }
  2031. #endif
  2032. /*
  2033. * Unset the specified variable.
  2034. */
  2035. static int
  2036. unsetvar(const char *s)
  2037. {
  2038. struct var **vpp;
  2039. struct var *vp;
  2040. int retval;
  2041. vpp = findvar(hashvar(s), s);
  2042. vp = *vpp;
  2043. retval = 2;
  2044. if (vp) {
  2045. int flags = vp->flags;
  2046. retval = 1;
  2047. if (flags & VREADONLY)
  2048. goto out;
  2049. #if ENABLE_ASH_RANDOM_SUPPORT
  2050. vp->flags &= ~VDYNAMIC;
  2051. #endif
  2052. if (flags & VUNSET)
  2053. goto ok;
  2054. if ((flags & VSTRFIXED) == 0) {
  2055. INT_OFF;
  2056. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  2057. free((char*)vp->var_text);
  2058. *vpp = vp->next;
  2059. free(vp);
  2060. INT_ON;
  2061. } else {
  2062. setvar(s, 0, 0);
  2063. vp->flags &= ~VEXPORT;
  2064. }
  2065. ok:
  2066. retval = 0;
  2067. }
  2068. out:
  2069. return retval;
  2070. }
  2071. /*
  2072. * Process a linked list of variable assignments.
  2073. */
  2074. static void
  2075. listsetvar(struct strlist *list_set_var, int flags)
  2076. {
  2077. struct strlist *lp = list_set_var;
  2078. if (!lp)
  2079. return;
  2080. INT_OFF;
  2081. do {
  2082. setvareq(lp->text, flags);
  2083. lp = lp->next;
  2084. } while (lp);
  2085. INT_ON;
  2086. }
  2087. /*
  2088. * Generate a list of variables satisfying the given conditions.
  2089. */
  2090. static char **
  2091. listvars(int on, int off, char ***end)
  2092. {
  2093. struct var **vpp;
  2094. struct var *vp;
  2095. char **ep;
  2096. int mask;
  2097. STARTSTACKSTR(ep);
  2098. vpp = vartab;
  2099. mask = on | off;
  2100. do {
  2101. for (vp = *vpp; vp; vp = vp->next) {
  2102. if ((vp->flags & mask) == on) {
  2103. if (ep == stackstrend())
  2104. ep = growstackstr();
  2105. *ep++ = (char*)vp->var_text;
  2106. }
  2107. }
  2108. } while (++vpp < vartab + VTABSIZE);
  2109. if (ep == stackstrend())
  2110. ep = growstackstr();
  2111. if (end)
  2112. *end = ep;
  2113. *ep++ = NULL;
  2114. return grabstackstr(ep);
  2115. }
  2116. /* ============ Path search helper
  2117. *
  2118. * The variable path (passed by reference) should be set to the start
  2119. * of the path before the first call; path_advance will update
  2120. * this value as it proceeds. Successive calls to path_advance will return
  2121. * the possible path expansions in sequence. If an option (indicated by
  2122. * a percent sign) appears in the path entry then the global variable
  2123. * pathopt will be set to point to it; otherwise pathopt will be set to
  2124. * NULL.
  2125. */
  2126. static const char *pathopt; /* set by path_advance */
  2127. static char *
  2128. path_advance(const char **path, const char *name)
  2129. {
  2130. const char *p;
  2131. char *q;
  2132. const char *start;
  2133. size_t len;
  2134. if (*path == NULL)
  2135. return NULL;
  2136. start = *path;
  2137. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2138. continue;
  2139. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2140. while (stackblocksize() < len)
  2141. growstackblock();
  2142. q = stackblock();
  2143. if (p != start) {
  2144. memcpy(q, start, p - start);
  2145. q += p - start;
  2146. *q++ = '/';
  2147. }
  2148. strcpy(q, name);
  2149. pathopt = NULL;
  2150. if (*p == '%') {
  2151. pathopt = ++p;
  2152. while (*p && *p != ':')
  2153. p++;
  2154. }
  2155. if (*p == ':')
  2156. *path = p + 1;
  2157. else
  2158. *path = NULL;
  2159. return stalloc(len);
  2160. }
  2161. /* ============ Prompt */
  2162. static smallint doprompt; /* if set, prompt the user */
  2163. static smallint needprompt; /* true if interactive and at start of line */
  2164. #if ENABLE_FEATURE_EDITING
  2165. static line_input_t *line_input_state;
  2166. static const char *cmdedit_prompt;
  2167. static void
  2168. putprompt(const char *s)
  2169. {
  2170. if (ENABLE_ASH_EXPAND_PRMT) {
  2171. free((char*)cmdedit_prompt);
  2172. cmdedit_prompt = ckstrdup(s);
  2173. return;
  2174. }
  2175. cmdedit_prompt = s;
  2176. }
  2177. #else
  2178. static void
  2179. putprompt(const char *s)
  2180. {
  2181. out2str(s);
  2182. }
  2183. #endif
  2184. #if ENABLE_ASH_EXPAND_PRMT
  2185. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2186. static const char *expandstr(const char *ps);
  2187. #else
  2188. #define expandstr(s) s
  2189. #endif
  2190. static void
  2191. setprompt_if(smallint do_set, int whichprompt)
  2192. {
  2193. const char *prompt;
  2194. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2195. if (!do_set)
  2196. return;
  2197. needprompt = 0;
  2198. switch (whichprompt) {
  2199. case 1:
  2200. prompt = ps1val();
  2201. break;
  2202. case 2:
  2203. prompt = ps2val();
  2204. break;
  2205. default: /* 0 */
  2206. prompt = nullstr;
  2207. }
  2208. #if ENABLE_ASH_EXPAND_PRMT
  2209. setstackmark(&smark);
  2210. stalloc(stackblocksize());
  2211. #endif
  2212. putprompt(expandstr(prompt));
  2213. #if ENABLE_ASH_EXPAND_PRMT
  2214. popstackmark(&smark);
  2215. #endif
  2216. }
  2217. /* ============ The cd and pwd commands */
  2218. #define CD_PHYSICAL 1
  2219. #define CD_PRINT 2
  2220. static int
  2221. cdopt(void)
  2222. {
  2223. int flags = 0;
  2224. int i, j;
  2225. j = 'L';
  2226. while ((i = nextopt("LP")) != '\0') {
  2227. if (i != j) {
  2228. flags ^= CD_PHYSICAL;
  2229. j = i;
  2230. }
  2231. }
  2232. return flags;
  2233. }
  2234. /*
  2235. * Update curdir (the name of the current directory) in response to a
  2236. * cd command.
  2237. */
  2238. static const char *
  2239. updatepwd(const char *dir)
  2240. {
  2241. char *new;
  2242. char *p;
  2243. char *cdcomppath;
  2244. const char *lim;
  2245. cdcomppath = ststrdup(dir);
  2246. STARTSTACKSTR(new);
  2247. if (*dir != '/') {
  2248. if (curdir == nullstr)
  2249. return 0;
  2250. new = stack_putstr(curdir, new);
  2251. }
  2252. new = makestrspace(strlen(dir) + 2, new);
  2253. lim = (char *)stackblock() + 1;
  2254. if (*dir != '/') {
  2255. if (new[-1] != '/')
  2256. USTPUTC('/', new);
  2257. if (new > lim && *lim == '/')
  2258. lim++;
  2259. } else {
  2260. USTPUTC('/', new);
  2261. cdcomppath++;
  2262. if (dir[1] == '/' && dir[2] != '/') {
  2263. USTPUTC('/', new);
  2264. cdcomppath++;
  2265. lim++;
  2266. }
  2267. }
  2268. p = strtok(cdcomppath, "/");
  2269. while (p) {
  2270. switch (*p) {
  2271. case '.':
  2272. if (p[1] == '.' && p[2] == '\0') {
  2273. while (new > lim) {
  2274. STUNPUTC(new);
  2275. if (new[-1] == '/')
  2276. break;
  2277. }
  2278. break;
  2279. }
  2280. if (p[1] == '\0')
  2281. break;
  2282. /* fall through */
  2283. default:
  2284. new = stack_putstr(p, new);
  2285. USTPUTC('/', new);
  2286. }
  2287. p = strtok(0, "/");
  2288. }
  2289. if (new > lim)
  2290. STUNPUTC(new);
  2291. *new = 0;
  2292. return stackblock();
  2293. }
  2294. /*
  2295. * Find out what the current directory is. If we already know the current
  2296. * directory, this routine returns immediately.
  2297. */
  2298. static char *
  2299. getpwd(void)
  2300. {
  2301. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2302. return dir ? dir : nullstr;
  2303. }
  2304. static void
  2305. setpwd(const char *val, int setold)
  2306. {
  2307. char *oldcur, *dir;
  2308. oldcur = dir = curdir;
  2309. if (setold) {
  2310. setvar("OLDPWD", oldcur, VEXPORT);
  2311. }
  2312. INT_OFF;
  2313. if (physdir != nullstr) {
  2314. if (physdir != oldcur)
  2315. free(physdir);
  2316. physdir = nullstr;
  2317. }
  2318. if (oldcur == val || !val) {
  2319. char *s = getpwd();
  2320. physdir = s;
  2321. if (!val)
  2322. dir = s;
  2323. } else
  2324. dir = ckstrdup(val);
  2325. if (oldcur != dir && oldcur != nullstr) {
  2326. free(oldcur);
  2327. }
  2328. curdir = dir;
  2329. INT_ON;
  2330. setvar("PWD", dir, VEXPORT);
  2331. }
  2332. static void hashcd(void);
  2333. /*
  2334. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2335. * know that the current directory has changed.
  2336. */
  2337. static int
  2338. docd(const char *dest, int flags)
  2339. {
  2340. const char *dir = NULL;
  2341. int err;
  2342. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2343. INT_OFF;
  2344. if (!(flags & CD_PHYSICAL)) {
  2345. dir = updatepwd(dest);
  2346. if (dir)
  2347. dest = dir;
  2348. }
  2349. err = chdir(dest);
  2350. if (err)
  2351. goto out;
  2352. setpwd(dir, 1);
  2353. hashcd();
  2354. out:
  2355. INT_ON;
  2356. return err;
  2357. }
  2358. static int FAST_FUNC
  2359. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2360. {
  2361. const char *dest;
  2362. const char *path;
  2363. const char *p;
  2364. char c;
  2365. struct stat statb;
  2366. int flags;
  2367. flags = cdopt();
  2368. dest = *argptr;
  2369. if (!dest)
  2370. dest = bltinlookup("HOME");
  2371. else if (LONE_DASH(dest)) {
  2372. dest = bltinlookup("OLDPWD");
  2373. flags |= CD_PRINT;
  2374. }
  2375. if (!dest)
  2376. dest = nullstr;
  2377. if (*dest == '/')
  2378. goto step7;
  2379. if (*dest == '.') {
  2380. c = dest[1];
  2381. dotdot:
  2382. switch (c) {
  2383. case '\0':
  2384. case '/':
  2385. goto step6;
  2386. case '.':
  2387. c = dest[2];
  2388. if (c != '.')
  2389. goto dotdot;
  2390. }
  2391. }
  2392. if (!*dest)
  2393. dest = ".";
  2394. path = bltinlookup("CDPATH");
  2395. if (!path) {
  2396. step6:
  2397. step7:
  2398. p = dest;
  2399. goto docd;
  2400. }
  2401. do {
  2402. c = *path;
  2403. p = path_advance(&path, dest);
  2404. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2405. if (c && c != ':')
  2406. flags |= CD_PRINT;
  2407. docd:
  2408. if (!docd(p, flags))
  2409. goto out;
  2410. break;
  2411. }
  2412. } while (path);
  2413. ash_msg_and_raise_error("can't cd to %s", dest);
  2414. /* NOTREACHED */
  2415. out:
  2416. if (flags & CD_PRINT)
  2417. out1fmt("%s\n", curdir);
  2418. return 0;
  2419. }
  2420. static int FAST_FUNC
  2421. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2422. {
  2423. int flags;
  2424. const char *dir = curdir;
  2425. flags = cdopt();
  2426. if (flags) {
  2427. if (physdir == nullstr)
  2428. setpwd(dir, 0);
  2429. dir = physdir;
  2430. }
  2431. out1fmt("%s\n", dir);
  2432. return 0;
  2433. }
  2434. /* ============ ... */
  2435. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2436. /* Syntax classes */
  2437. #define CWORD 0 /* character is nothing special */
  2438. #define CNL 1 /* newline character */
  2439. #define CBACK 2 /* a backslash character */
  2440. #define CSQUOTE 3 /* single quote */
  2441. #define CDQUOTE 4 /* double quote */
  2442. #define CENDQUOTE 5 /* a terminating quote */
  2443. #define CBQUOTE 6 /* backwards single quote */
  2444. #define CVAR 7 /* a dollar sign */
  2445. #define CENDVAR 8 /* a '}' character */
  2446. #define CLP 9 /* a left paren in arithmetic */
  2447. #define CRP 10 /* a right paren in arithmetic */
  2448. #define CENDFILE 11 /* end of file */
  2449. #define CCTL 12 /* like CWORD, except it must be escaped */
  2450. #define CSPCL 13 /* these terminate a word */
  2451. #define CIGN 14 /* character should be ignored */
  2452. #define PEOF 256
  2453. #if ENABLE_ASH_ALIAS
  2454. # define PEOA 257
  2455. #endif
  2456. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2457. #if ENABLE_SH_MATH_SUPPORT
  2458. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2459. #else
  2460. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2461. #endif
  2462. static const uint16_t S_I_T[] = {
  2463. #if ENABLE_ASH_ALIAS
  2464. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2465. #endif
  2466. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2467. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2468. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2469. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2470. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2471. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2472. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2473. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2474. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2475. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2476. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2477. #if !USE_SIT_FUNCTION
  2478. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2479. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2480. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2481. #endif
  2482. #undef SIT_ITEM
  2483. };
  2484. /* Constants below must match table above */
  2485. enum {
  2486. #if ENABLE_ASH_ALIAS
  2487. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2488. #endif
  2489. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2490. CNL_CNL_CNL_CNL , /* 2 */
  2491. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2492. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2493. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2494. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2495. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2496. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2497. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2498. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2499. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2500. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2501. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2502. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2503. };
  2504. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2505. * caller must ensure proper cast on it if c is *char_ptr!
  2506. */
  2507. /* Values for syntax param */
  2508. #define BASESYNTAX 0 /* not in quotes */
  2509. #define DQSYNTAX 1 /* in double quotes */
  2510. #define SQSYNTAX 2 /* in single quotes */
  2511. #define ARISYNTAX 3 /* in arithmetic */
  2512. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2513. #if USE_SIT_FUNCTION
  2514. static int
  2515. SIT(int c, int syntax)
  2516. {
  2517. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2518. # if ENABLE_ASH_ALIAS
  2519. static const uint8_t syntax_index_table[] ALIGN1 = {
  2520. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2521. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2522. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2523. 11, 3 /* "}~" */
  2524. };
  2525. # else
  2526. static const uint8_t syntax_index_table[] ALIGN1 = {
  2527. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2528. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2529. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2530. 10, 2 /* "}~" */
  2531. };
  2532. # endif
  2533. const char *s;
  2534. int indx;
  2535. if (c == PEOF)
  2536. return CENDFILE;
  2537. # if ENABLE_ASH_ALIAS
  2538. if (c == PEOA)
  2539. indx = 0;
  2540. else
  2541. # endif
  2542. {
  2543. /* Cast is purely for paranoia here,
  2544. * just in case someone passed signed char to us */
  2545. if ((unsigned char)c >= CTL_FIRST
  2546. && (unsigned char)c <= CTL_LAST
  2547. ) {
  2548. return CCTL;
  2549. }
  2550. s = strchrnul(spec_symbls, c);
  2551. if (*s == '\0')
  2552. return CWORD;
  2553. indx = syntax_index_table[s - spec_symbls];
  2554. }
  2555. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2556. }
  2557. #else /* !USE_SIT_FUNCTION */
  2558. static const uint8_t syntax_index_table[] = {
  2559. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2560. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2570. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2571. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2593. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2594. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2595. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2597. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2599. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2600. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2601. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2602. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2603. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2606. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2608. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2619. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2620. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2621. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2622. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2623. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2624. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2625. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2652. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2653. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2654. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2657. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2685. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2686. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2687. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2690. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2691. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2692. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2693. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2694. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2695. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2696. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2697. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2698. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2817. # if ENABLE_ASH_ALIAS
  2818. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2819. # endif
  2820. };
  2821. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2822. #endif /* !USE_SIT_FUNCTION */
  2823. /* ============ Alias handling */
  2824. #if ENABLE_ASH_ALIAS
  2825. #define ALIASINUSE 1
  2826. #define ALIASDEAD 2
  2827. struct alias {
  2828. struct alias *next;
  2829. char *name;
  2830. char *val;
  2831. int flag;
  2832. };
  2833. static struct alias **atab; // [ATABSIZE];
  2834. #define INIT_G_alias() do { \
  2835. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2836. } while (0)
  2837. static struct alias **
  2838. __lookupalias(const char *name) {
  2839. unsigned int hashval;
  2840. struct alias **app;
  2841. const char *p;
  2842. unsigned int ch;
  2843. p = name;
  2844. ch = (unsigned char)*p;
  2845. hashval = ch << 4;
  2846. while (ch) {
  2847. hashval += ch;
  2848. ch = (unsigned char)*++p;
  2849. }
  2850. app = &atab[hashval % ATABSIZE];
  2851. for (; *app; app = &(*app)->next) {
  2852. if (strcmp(name, (*app)->name) == 0) {
  2853. break;
  2854. }
  2855. }
  2856. return app;
  2857. }
  2858. static struct alias *
  2859. lookupalias(const char *name, int check)
  2860. {
  2861. struct alias *ap = *__lookupalias(name);
  2862. if (check && ap && (ap->flag & ALIASINUSE))
  2863. return NULL;
  2864. return ap;
  2865. }
  2866. static struct alias *
  2867. freealias(struct alias *ap)
  2868. {
  2869. struct alias *next;
  2870. if (ap->flag & ALIASINUSE) {
  2871. ap->flag |= ALIASDEAD;
  2872. return ap;
  2873. }
  2874. next = ap->next;
  2875. free(ap->name);
  2876. free(ap->val);
  2877. free(ap);
  2878. return next;
  2879. }
  2880. static void
  2881. setalias(const char *name, const char *val)
  2882. {
  2883. struct alias *ap, **app;
  2884. app = __lookupalias(name);
  2885. ap = *app;
  2886. INT_OFF;
  2887. if (ap) {
  2888. if (!(ap->flag & ALIASINUSE)) {
  2889. free(ap->val);
  2890. }
  2891. ap->val = ckstrdup(val);
  2892. ap->flag &= ~ALIASDEAD;
  2893. } else {
  2894. /* not found */
  2895. ap = ckzalloc(sizeof(struct alias));
  2896. ap->name = ckstrdup(name);
  2897. ap->val = ckstrdup(val);
  2898. /*ap->flag = 0; - ckzalloc did it */
  2899. /*ap->next = NULL;*/
  2900. *app = ap;
  2901. }
  2902. INT_ON;
  2903. }
  2904. static int
  2905. unalias(const char *name)
  2906. {
  2907. struct alias **app;
  2908. app = __lookupalias(name);
  2909. if (*app) {
  2910. INT_OFF;
  2911. *app = freealias(*app);
  2912. INT_ON;
  2913. return 0;
  2914. }
  2915. return 1;
  2916. }
  2917. static void
  2918. rmaliases(void)
  2919. {
  2920. struct alias *ap, **app;
  2921. int i;
  2922. INT_OFF;
  2923. for (i = 0; i < ATABSIZE; i++) {
  2924. app = &atab[i];
  2925. for (ap = *app; ap; ap = *app) {
  2926. *app = freealias(*app);
  2927. if (ap == *app) {
  2928. app = &ap->next;
  2929. }
  2930. }
  2931. }
  2932. INT_ON;
  2933. }
  2934. static void
  2935. printalias(const struct alias *ap)
  2936. {
  2937. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2938. }
  2939. /*
  2940. * TODO - sort output
  2941. */
  2942. static int FAST_FUNC
  2943. aliascmd(int argc UNUSED_PARAM, char **argv)
  2944. {
  2945. char *n, *v;
  2946. int ret = 0;
  2947. struct alias *ap;
  2948. if (!argv[1]) {
  2949. int i;
  2950. for (i = 0; i < ATABSIZE; i++) {
  2951. for (ap = atab[i]; ap; ap = ap->next) {
  2952. printalias(ap);
  2953. }
  2954. }
  2955. return 0;
  2956. }
  2957. while ((n = *++argv) != NULL) {
  2958. v = strchr(n+1, '=');
  2959. if (v == NULL) { /* n+1: funny ksh stuff */
  2960. ap = *__lookupalias(n);
  2961. if (ap == NULL) {
  2962. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2963. ret = 1;
  2964. } else
  2965. printalias(ap);
  2966. } else {
  2967. *v++ = '\0';
  2968. setalias(n, v);
  2969. }
  2970. }
  2971. return ret;
  2972. }
  2973. static int FAST_FUNC
  2974. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2975. {
  2976. int i;
  2977. while ((i = nextopt("a")) != '\0') {
  2978. if (i == 'a') {
  2979. rmaliases();
  2980. return 0;
  2981. }
  2982. }
  2983. for (i = 0; *argptr; argptr++) {
  2984. if (unalias(*argptr)) {
  2985. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2986. i = 1;
  2987. }
  2988. }
  2989. return i;
  2990. }
  2991. #endif /* ASH_ALIAS */
  2992. /* ============ jobs.c */
  2993. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2994. #define FORK_FG 0
  2995. #define FORK_BG 1
  2996. #define FORK_NOJOB 2
  2997. /* mode flags for showjob(s) */
  2998. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  2999. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3000. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3001. /*
  3002. * A job structure contains information about a job. A job is either a
  3003. * single process or a set of processes contained in a pipeline. In the
  3004. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3005. * array of pids.
  3006. */
  3007. struct procstat {
  3008. pid_t ps_pid; /* process id */
  3009. int ps_status; /* last process status from wait() */
  3010. char *ps_cmd; /* text of command being run */
  3011. };
  3012. struct job {
  3013. struct procstat ps0; /* status of process */
  3014. struct procstat *ps; /* status or processes when more than one */
  3015. #if JOBS
  3016. int stopstatus; /* status of a stopped job */
  3017. #endif
  3018. uint32_t
  3019. nprocs: 16, /* number of processes */
  3020. state: 8,
  3021. #define JOBRUNNING 0 /* at least one proc running */
  3022. #define JOBSTOPPED 1 /* all procs are stopped */
  3023. #define JOBDONE 2 /* all procs are completed */
  3024. #if JOBS
  3025. sigint: 1, /* job was killed by SIGINT */
  3026. jobctl: 1, /* job running under job control */
  3027. #endif
  3028. waited: 1, /* true if this entry has been waited for */
  3029. used: 1, /* true if this entry is in used */
  3030. changed: 1; /* true if status has changed */
  3031. struct job *prev_job; /* previous job */
  3032. };
  3033. static struct job *makejob(/*union node *,*/ int);
  3034. static int forkshell(struct job *, union node *, int);
  3035. static int waitforjob(struct job *);
  3036. #if !JOBS
  3037. enum { doing_jobctl = 0 };
  3038. #define setjobctl(on) do {} while (0)
  3039. #else
  3040. static smallint doing_jobctl; //references:8
  3041. static void setjobctl(int);
  3042. #endif
  3043. /*
  3044. * Ignore a signal.
  3045. */
  3046. static void
  3047. ignoresig(int signo)
  3048. {
  3049. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3050. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3051. /* No, need to do it */
  3052. signal(signo, SIG_IGN);
  3053. }
  3054. sigmode[signo - 1] = S_HARD_IGN;
  3055. }
  3056. /*
  3057. * Only one usage site - in setsignal()
  3058. */
  3059. static void
  3060. signal_handler(int signo)
  3061. {
  3062. gotsig[signo - 1] = 1;
  3063. if (signo == SIGINT && !trap[SIGINT]) {
  3064. if (!suppress_int) {
  3065. pending_sig = 0;
  3066. raise_interrupt(); /* does not return */
  3067. }
  3068. pending_int = 1;
  3069. } else {
  3070. pending_sig = signo;
  3071. }
  3072. }
  3073. /*
  3074. * Set the signal handler for the specified signal. The routine figures
  3075. * out what it should be set to.
  3076. */
  3077. static void
  3078. setsignal(int signo)
  3079. {
  3080. char *t;
  3081. char cur_act, new_act;
  3082. struct sigaction act;
  3083. t = trap[signo];
  3084. new_act = S_DFL;
  3085. if (t != NULL) { /* trap for this sig is set */
  3086. new_act = S_CATCH;
  3087. if (t[0] == '\0') /* trap is "": ignore this sig */
  3088. new_act = S_IGN;
  3089. }
  3090. if (rootshell && new_act == S_DFL) {
  3091. switch (signo) {
  3092. case SIGINT:
  3093. if (iflag || minusc || sflag == 0)
  3094. new_act = S_CATCH;
  3095. break;
  3096. case SIGQUIT:
  3097. #if DEBUG
  3098. if (debug)
  3099. break;
  3100. #endif
  3101. /* man bash:
  3102. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3103. * commands run by bash have signal handlers
  3104. * set to the values inherited by the shell
  3105. * from its parent". */
  3106. new_act = S_IGN;
  3107. break;
  3108. case SIGTERM:
  3109. if (iflag)
  3110. new_act = S_IGN;
  3111. break;
  3112. #if JOBS
  3113. case SIGTSTP:
  3114. case SIGTTOU:
  3115. if (mflag)
  3116. new_act = S_IGN;
  3117. break;
  3118. #endif
  3119. }
  3120. }
  3121. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3122. //whereas we have to restore it to what shell got on entry
  3123. //from the parent. See comment above
  3124. t = &sigmode[signo - 1];
  3125. cur_act = *t;
  3126. if (cur_act == 0) {
  3127. /* current setting is not yet known */
  3128. if (sigaction(signo, NULL, &act)) {
  3129. /* pretend it worked; maybe we should give a warning,
  3130. * but other shells don't. We don't alter sigmode,
  3131. * so we retry every time.
  3132. * btw, in Linux it never fails. --vda */
  3133. return;
  3134. }
  3135. if (act.sa_handler == SIG_IGN) {
  3136. cur_act = S_HARD_IGN;
  3137. if (mflag
  3138. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3139. ) {
  3140. cur_act = S_IGN; /* don't hard ignore these */
  3141. }
  3142. }
  3143. }
  3144. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3145. return;
  3146. act.sa_handler = SIG_DFL;
  3147. switch (new_act) {
  3148. case S_CATCH:
  3149. act.sa_handler = signal_handler;
  3150. break;
  3151. case S_IGN:
  3152. act.sa_handler = SIG_IGN;
  3153. break;
  3154. }
  3155. /* flags and mask matter only if !DFL and !IGN, but we do it
  3156. * for all cases for more deterministic behavior:
  3157. */
  3158. act.sa_flags = 0;
  3159. sigfillset(&act.sa_mask);
  3160. sigaction_set(signo, &act);
  3161. *t = new_act;
  3162. }
  3163. /* mode flags for set_curjob */
  3164. #define CUR_DELETE 2
  3165. #define CUR_RUNNING 1
  3166. #define CUR_STOPPED 0
  3167. /* mode flags for dowait */
  3168. #define DOWAIT_NONBLOCK WNOHANG
  3169. #define DOWAIT_BLOCK 0
  3170. #if JOBS
  3171. /* pgrp of shell on invocation */
  3172. static int initialpgrp; //references:2
  3173. static int ttyfd = -1; //5
  3174. #endif
  3175. /* array of jobs */
  3176. static struct job *jobtab; //5
  3177. /* size of array */
  3178. static unsigned njobs; //4
  3179. /* current job */
  3180. static struct job *curjob; //lots
  3181. /* number of presumed living untracked jobs */
  3182. static int jobless; //4
  3183. static void
  3184. set_curjob(struct job *jp, unsigned mode)
  3185. {
  3186. struct job *jp1;
  3187. struct job **jpp, **curp;
  3188. /* first remove from list */
  3189. jpp = curp = &curjob;
  3190. while (1) {
  3191. jp1 = *jpp;
  3192. if (jp1 == jp)
  3193. break;
  3194. jpp = &jp1->prev_job;
  3195. }
  3196. *jpp = jp1->prev_job;
  3197. /* Then re-insert in correct position */
  3198. jpp = curp;
  3199. switch (mode) {
  3200. default:
  3201. #if DEBUG
  3202. abort();
  3203. #endif
  3204. case CUR_DELETE:
  3205. /* job being deleted */
  3206. break;
  3207. case CUR_RUNNING:
  3208. /* newly created job or backgrounded job,
  3209. * put after all stopped jobs.
  3210. */
  3211. while (1) {
  3212. jp1 = *jpp;
  3213. #if JOBS
  3214. if (!jp1 || jp1->state != JOBSTOPPED)
  3215. #endif
  3216. break;
  3217. jpp = &jp1->prev_job;
  3218. }
  3219. /* FALLTHROUGH */
  3220. #if JOBS
  3221. case CUR_STOPPED:
  3222. #endif
  3223. /* newly stopped job - becomes curjob */
  3224. jp->prev_job = *jpp;
  3225. *jpp = jp;
  3226. break;
  3227. }
  3228. }
  3229. #if JOBS || DEBUG
  3230. static int
  3231. jobno(const struct job *jp)
  3232. {
  3233. return jp - jobtab + 1;
  3234. }
  3235. #endif
  3236. /*
  3237. * Convert a job name to a job structure.
  3238. */
  3239. #if !JOBS
  3240. #define getjob(name, getctl) getjob(name)
  3241. #endif
  3242. static struct job *
  3243. getjob(const char *name, int getctl)
  3244. {
  3245. struct job *jp;
  3246. struct job *found;
  3247. const char *err_msg = "%s: no such job";
  3248. unsigned num;
  3249. int c;
  3250. const char *p;
  3251. char *(*match)(const char *, const char *);
  3252. jp = curjob;
  3253. p = name;
  3254. if (!p)
  3255. goto currentjob;
  3256. if (*p != '%')
  3257. goto err;
  3258. c = *++p;
  3259. if (!c)
  3260. goto currentjob;
  3261. if (!p[1]) {
  3262. if (c == '+' || c == '%') {
  3263. currentjob:
  3264. err_msg = "No current job";
  3265. goto check;
  3266. }
  3267. if (c == '-') {
  3268. if (jp)
  3269. jp = jp->prev_job;
  3270. err_msg = "No previous job";
  3271. check:
  3272. if (!jp)
  3273. goto err;
  3274. goto gotit;
  3275. }
  3276. }
  3277. if (is_number(p)) {
  3278. num = atoi(p);
  3279. if (num < njobs) {
  3280. jp = jobtab + num - 1;
  3281. if (jp->used)
  3282. goto gotit;
  3283. goto err;
  3284. }
  3285. }
  3286. match = prefix;
  3287. if (*p == '?') {
  3288. match = strstr;
  3289. p++;
  3290. }
  3291. found = NULL;
  3292. while (jp) {
  3293. if (match(jp->ps[0].ps_cmd, p)) {
  3294. if (found)
  3295. goto err;
  3296. found = jp;
  3297. err_msg = "%s: ambiguous";
  3298. }
  3299. jp = jp->prev_job;
  3300. }
  3301. if (!found)
  3302. goto err;
  3303. jp = found;
  3304. gotit:
  3305. #if JOBS
  3306. err_msg = "job %s not created under job control";
  3307. if (getctl && jp->jobctl == 0)
  3308. goto err;
  3309. #endif
  3310. return jp;
  3311. err:
  3312. ash_msg_and_raise_error(err_msg, name);
  3313. }
  3314. /*
  3315. * Mark a job structure as unused.
  3316. */
  3317. static void
  3318. freejob(struct job *jp)
  3319. {
  3320. struct procstat *ps;
  3321. int i;
  3322. INT_OFF;
  3323. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3324. if (ps->ps_cmd != nullstr)
  3325. free(ps->ps_cmd);
  3326. }
  3327. if (jp->ps != &jp->ps0)
  3328. free(jp->ps);
  3329. jp->used = 0;
  3330. set_curjob(jp, CUR_DELETE);
  3331. INT_ON;
  3332. }
  3333. #if JOBS
  3334. static void
  3335. xtcsetpgrp(int fd, pid_t pgrp)
  3336. {
  3337. if (tcsetpgrp(fd, pgrp))
  3338. ash_msg_and_raise_error("can't set tty process group (%m)");
  3339. }
  3340. /*
  3341. * Turn job control on and off.
  3342. *
  3343. * Note: This code assumes that the third arg to ioctl is a character
  3344. * pointer, which is true on Berkeley systems but not System V. Since
  3345. * System V doesn't have job control yet, this isn't a problem now.
  3346. *
  3347. * Called with interrupts off.
  3348. */
  3349. static void
  3350. setjobctl(int on)
  3351. {
  3352. int fd;
  3353. int pgrp;
  3354. if (on == doing_jobctl || rootshell == 0)
  3355. return;
  3356. if (on) {
  3357. int ofd;
  3358. ofd = fd = open(_PATH_TTY, O_RDWR);
  3359. if (fd < 0) {
  3360. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3361. * That sometimes helps to acquire controlling tty.
  3362. * Obviously, a workaround for bugs when someone
  3363. * failed to provide a controlling tty to bash! :) */
  3364. fd = 2;
  3365. while (!isatty(fd))
  3366. if (--fd < 0)
  3367. goto out;
  3368. }
  3369. fd = fcntl(fd, F_DUPFD, 10);
  3370. if (ofd >= 0)
  3371. close(ofd);
  3372. if (fd < 0)
  3373. goto out;
  3374. /* fd is a tty at this point */
  3375. close_on_exec_on(fd);
  3376. while (1) { /* while we are in the background */
  3377. pgrp = tcgetpgrp(fd);
  3378. if (pgrp < 0) {
  3379. out:
  3380. ash_msg("can't access tty; job control turned off");
  3381. mflag = on = 0;
  3382. goto close;
  3383. }
  3384. if (pgrp == getpgrp())
  3385. break;
  3386. killpg(0, SIGTTIN);
  3387. }
  3388. initialpgrp = pgrp;
  3389. setsignal(SIGTSTP);
  3390. setsignal(SIGTTOU);
  3391. setsignal(SIGTTIN);
  3392. pgrp = rootpid;
  3393. setpgid(0, pgrp);
  3394. xtcsetpgrp(fd, pgrp);
  3395. } else {
  3396. /* turning job control off */
  3397. fd = ttyfd;
  3398. pgrp = initialpgrp;
  3399. /* was xtcsetpgrp, but this can make exiting ash
  3400. * loop forever if pty is already deleted */
  3401. tcsetpgrp(fd, pgrp);
  3402. setpgid(0, pgrp);
  3403. setsignal(SIGTSTP);
  3404. setsignal(SIGTTOU);
  3405. setsignal(SIGTTIN);
  3406. close:
  3407. if (fd >= 0)
  3408. close(fd);
  3409. fd = -1;
  3410. }
  3411. ttyfd = fd;
  3412. doing_jobctl = on;
  3413. }
  3414. static int FAST_FUNC
  3415. killcmd(int argc, char **argv)
  3416. {
  3417. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3418. int i = 1;
  3419. do {
  3420. if (argv[i][0] == '%') {
  3421. /*
  3422. * "kill %N" - job kill
  3423. * Converting to pgrp / pid kill
  3424. */
  3425. struct job *jp;
  3426. char *dst;
  3427. int j, n;
  3428. jp = getjob(argv[i], 0);
  3429. /*
  3430. * In jobs started under job control, we signal
  3431. * entire process group by kill -PGRP_ID.
  3432. * This happens, f.e., in interactive shell.
  3433. *
  3434. * Otherwise, we signal each child via
  3435. * kill PID1 PID2 PID3.
  3436. * Testcases:
  3437. * sh -c 'sleep 1|sleep 1 & kill %1'
  3438. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3439. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3440. */
  3441. n = jp->nprocs; /* can't be 0 (I hope) */
  3442. if (jp->jobctl)
  3443. n = 1;
  3444. dst = alloca(n * sizeof(int)*4);
  3445. argv[i] = dst;
  3446. for (j = 0; j < n; j++) {
  3447. struct procstat *ps = &jp->ps[j];
  3448. /* Skip non-running and not-stopped members
  3449. * (i.e. dead members) of the job
  3450. */
  3451. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3452. continue;
  3453. /*
  3454. * kill_main has matching code to expect
  3455. * leading space. Needed to not confuse
  3456. * negative pids with "kill -SIGNAL_NO" syntax
  3457. */
  3458. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3459. }
  3460. *dst = '\0';
  3461. }
  3462. } while (argv[++i]);
  3463. }
  3464. return kill_main(argc, argv);
  3465. }
  3466. static void
  3467. showpipe(struct job *jp /*, FILE *out*/)
  3468. {
  3469. struct procstat *ps;
  3470. struct procstat *psend;
  3471. psend = jp->ps + jp->nprocs;
  3472. for (ps = jp->ps + 1; ps < psend; ps++)
  3473. printf(" | %s", ps->ps_cmd);
  3474. outcslow('\n', stdout);
  3475. flush_stdout_stderr();
  3476. }
  3477. static int
  3478. restartjob(struct job *jp, int mode)
  3479. {
  3480. struct procstat *ps;
  3481. int i;
  3482. int status;
  3483. pid_t pgid;
  3484. INT_OFF;
  3485. if (jp->state == JOBDONE)
  3486. goto out;
  3487. jp->state = JOBRUNNING;
  3488. pgid = jp->ps[0].ps_pid;
  3489. if (mode == FORK_FG)
  3490. xtcsetpgrp(ttyfd, pgid);
  3491. killpg(pgid, SIGCONT);
  3492. ps = jp->ps;
  3493. i = jp->nprocs;
  3494. do {
  3495. if (WIFSTOPPED(ps->ps_status)) {
  3496. ps->ps_status = -1;
  3497. }
  3498. ps++;
  3499. } while (--i);
  3500. out:
  3501. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3502. INT_ON;
  3503. return status;
  3504. }
  3505. static int FAST_FUNC
  3506. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3507. {
  3508. struct job *jp;
  3509. int mode;
  3510. int retval;
  3511. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3512. nextopt(nullstr);
  3513. argv = argptr;
  3514. do {
  3515. jp = getjob(*argv, 1);
  3516. if (mode == FORK_BG) {
  3517. set_curjob(jp, CUR_RUNNING);
  3518. printf("[%d] ", jobno(jp));
  3519. }
  3520. out1str(jp->ps[0].ps_cmd);
  3521. showpipe(jp /*, stdout*/);
  3522. retval = restartjob(jp, mode);
  3523. } while (*argv && *++argv);
  3524. return retval;
  3525. }
  3526. #endif
  3527. static int
  3528. sprint_status(char *s, int status, int sigonly)
  3529. {
  3530. int col;
  3531. int st;
  3532. col = 0;
  3533. if (!WIFEXITED(status)) {
  3534. #if JOBS
  3535. if (WIFSTOPPED(status))
  3536. st = WSTOPSIG(status);
  3537. else
  3538. #endif
  3539. st = WTERMSIG(status);
  3540. if (sigonly) {
  3541. if (st == SIGINT || st == SIGPIPE)
  3542. goto out;
  3543. #if JOBS
  3544. if (WIFSTOPPED(status))
  3545. goto out;
  3546. #endif
  3547. }
  3548. st &= 0x7f;
  3549. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3550. col = fmtstr(s, 32, strsignal(st));
  3551. if (WCOREDUMP(status)) {
  3552. col += fmtstr(s + col, 16, " (core dumped)");
  3553. }
  3554. } else if (!sigonly) {
  3555. st = WEXITSTATUS(status);
  3556. if (st)
  3557. col = fmtstr(s, 16, "Done(%d)", st);
  3558. else
  3559. col = fmtstr(s, 16, "Done");
  3560. }
  3561. out:
  3562. return col;
  3563. }
  3564. static int
  3565. dowait(int wait_flags, struct job *job)
  3566. {
  3567. int pid;
  3568. int status;
  3569. struct job *jp;
  3570. struct job *thisjob;
  3571. int state;
  3572. TRACE(("dowait(0x%x) called\n", wait_flags));
  3573. /* Do a wait system call. If job control is compiled in, we accept
  3574. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3575. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3576. if (doing_jobctl)
  3577. wait_flags |= WUNTRACED;
  3578. pid = waitpid(-1, &status, wait_flags);
  3579. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3580. pid, status, errno, strerror(errno)));
  3581. if (pid <= 0)
  3582. return pid;
  3583. INT_OFF;
  3584. thisjob = NULL;
  3585. for (jp = curjob; jp; jp = jp->prev_job) {
  3586. struct procstat *ps;
  3587. struct procstat *psend;
  3588. if (jp->state == JOBDONE)
  3589. continue;
  3590. state = JOBDONE;
  3591. ps = jp->ps;
  3592. psend = ps + jp->nprocs;
  3593. do {
  3594. if (ps->ps_pid == pid) {
  3595. TRACE(("Job %d: changing status of proc %d "
  3596. "from 0x%x to 0x%x\n",
  3597. jobno(jp), pid, ps->ps_status, status));
  3598. ps->ps_status = status;
  3599. thisjob = jp;
  3600. }
  3601. if (ps->ps_status == -1)
  3602. state = JOBRUNNING;
  3603. #if JOBS
  3604. if (state == JOBRUNNING)
  3605. continue;
  3606. if (WIFSTOPPED(ps->ps_status)) {
  3607. jp->stopstatus = ps->ps_status;
  3608. state = JOBSTOPPED;
  3609. }
  3610. #endif
  3611. } while (++ps < psend);
  3612. if (thisjob)
  3613. goto gotjob;
  3614. }
  3615. #if JOBS
  3616. if (!WIFSTOPPED(status))
  3617. #endif
  3618. jobless--;
  3619. goto out;
  3620. gotjob:
  3621. if (state != JOBRUNNING) {
  3622. thisjob->changed = 1;
  3623. if (thisjob->state != state) {
  3624. TRACE(("Job %d: changing state from %d to %d\n",
  3625. jobno(thisjob), thisjob->state, state));
  3626. thisjob->state = state;
  3627. #if JOBS
  3628. if (state == JOBSTOPPED) {
  3629. set_curjob(thisjob, CUR_STOPPED);
  3630. }
  3631. #endif
  3632. }
  3633. }
  3634. out:
  3635. INT_ON;
  3636. if (thisjob && thisjob == job) {
  3637. char s[48 + 1];
  3638. int len;
  3639. len = sprint_status(s, status, 1);
  3640. if (len) {
  3641. s[len] = '\n';
  3642. s[len + 1] = '\0';
  3643. out2str(s);
  3644. }
  3645. }
  3646. return pid;
  3647. }
  3648. static int
  3649. blocking_wait_with_raise_on_sig(void)
  3650. {
  3651. pid_t pid = dowait(DOWAIT_BLOCK, NULL);
  3652. if (pid <= 0 && pending_sig)
  3653. raise_exception(EXSIG);
  3654. return pid;
  3655. }
  3656. #if JOBS
  3657. static void
  3658. showjob(FILE *out, struct job *jp, int mode)
  3659. {
  3660. struct procstat *ps;
  3661. struct procstat *psend;
  3662. int col;
  3663. int indent_col;
  3664. char s[80];
  3665. ps = jp->ps;
  3666. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3667. /* just output process (group) id of pipeline */
  3668. fprintf(out, "%d\n", ps->ps_pid);
  3669. return;
  3670. }
  3671. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3672. indent_col = col;
  3673. if (jp == curjob)
  3674. s[col - 3] = '+';
  3675. else if (curjob && jp == curjob->prev_job)
  3676. s[col - 3] = '-';
  3677. if (mode & SHOW_PIDS)
  3678. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3679. psend = ps + jp->nprocs;
  3680. if (jp->state == JOBRUNNING) {
  3681. strcpy(s + col, "Running");
  3682. col += sizeof("Running") - 1;
  3683. } else {
  3684. int status = psend[-1].ps_status;
  3685. if (jp->state == JOBSTOPPED)
  3686. status = jp->stopstatus;
  3687. col += sprint_status(s + col, status, 0);
  3688. }
  3689. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3690. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3691. * or prints several "PID | <cmdN>" lines,
  3692. * depending on SHOW_PIDS bit.
  3693. * We do not print status of individual processes
  3694. * between PID and <cmdN>. bash does it, but not very well:
  3695. * first line shows overall job status, not process status,
  3696. * making it impossible to know 1st process status.
  3697. */
  3698. goto start;
  3699. do {
  3700. /* for each process */
  3701. s[0] = '\0';
  3702. col = 33;
  3703. if (mode & SHOW_PIDS)
  3704. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3705. start:
  3706. fprintf(out, "%s%*c%s%s",
  3707. s,
  3708. 33 - col >= 0 ? 33 - col : 0, ' ',
  3709. ps == jp->ps ? "" : "| ",
  3710. ps->ps_cmd
  3711. );
  3712. } while (++ps != psend);
  3713. outcslow('\n', out);
  3714. jp->changed = 0;
  3715. if (jp->state == JOBDONE) {
  3716. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3717. freejob(jp);
  3718. }
  3719. }
  3720. /*
  3721. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3722. * statuses have changed since the last call to showjobs.
  3723. */
  3724. static void
  3725. showjobs(FILE *out, int mode)
  3726. {
  3727. struct job *jp;
  3728. TRACE(("showjobs(0x%x) called\n", mode));
  3729. /* Handle all finished jobs */
  3730. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3731. continue;
  3732. for (jp = curjob; jp; jp = jp->prev_job) {
  3733. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3734. showjob(out, jp, mode);
  3735. }
  3736. }
  3737. }
  3738. static int FAST_FUNC
  3739. jobscmd(int argc UNUSED_PARAM, char **argv)
  3740. {
  3741. int mode, m;
  3742. mode = 0;
  3743. while ((m = nextopt("lp")) != '\0') {
  3744. if (m == 'l')
  3745. mode |= SHOW_PIDS;
  3746. else
  3747. mode |= SHOW_ONLY_PGID;
  3748. }
  3749. argv = argptr;
  3750. if (*argv) {
  3751. do
  3752. showjob(stdout, getjob(*argv, 0), mode);
  3753. while (*++argv);
  3754. } else {
  3755. showjobs(stdout, mode);
  3756. }
  3757. return 0;
  3758. }
  3759. #endif /* JOBS */
  3760. /* Called only on finished or stopped jobs (no members are running) */
  3761. static int
  3762. getstatus(struct job *job)
  3763. {
  3764. int status;
  3765. int retval;
  3766. struct procstat *ps;
  3767. /* Fetch last member's status */
  3768. ps = job->ps + job->nprocs - 1;
  3769. status = ps->ps_status;
  3770. if (pipefail) {
  3771. /* "set -o pipefail" mode: use last _nonzero_ status */
  3772. while (status == 0 && --ps >= job->ps)
  3773. status = ps->ps_status;
  3774. }
  3775. retval = WEXITSTATUS(status);
  3776. if (!WIFEXITED(status)) {
  3777. #if JOBS
  3778. retval = WSTOPSIG(status);
  3779. if (!WIFSTOPPED(status))
  3780. #endif
  3781. {
  3782. /* XXX: limits number of signals */
  3783. retval = WTERMSIG(status);
  3784. #if JOBS
  3785. if (retval == SIGINT)
  3786. job->sigint = 1;
  3787. #endif
  3788. }
  3789. retval += 128;
  3790. }
  3791. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3792. jobno(job), job->nprocs, status, retval));
  3793. return retval;
  3794. }
  3795. static int FAST_FUNC
  3796. waitcmd(int argc UNUSED_PARAM, char **argv)
  3797. {
  3798. struct job *job;
  3799. int retval;
  3800. struct job *jp;
  3801. if (pending_sig)
  3802. raise_exception(EXSIG);
  3803. nextopt(nullstr);
  3804. retval = 0;
  3805. argv = argptr;
  3806. if (!*argv) {
  3807. /* wait for all jobs */
  3808. for (;;) {
  3809. jp = curjob;
  3810. while (1) {
  3811. if (!jp) /* no running procs */
  3812. goto ret;
  3813. if (jp->state == JOBRUNNING)
  3814. break;
  3815. jp->waited = 1;
  3816. jp = jp->prev_job;
  3817. }
  3818. blocking_wait_with_raise_on_sig();
  3819. /* man bash:
  3820. * "When bash is waiting for an asynchronous command via
  3821. * the wait builtin, the reception of a signal for which a trap
  3822. * has been set will cause the wait builtin to return immediately
  3823. * with an exit status greater than 128, immediately after which
  3824. * the trap is executed."
  3825. *
  3826. * blocking_wait_with_raise_on_sig raises signal handlers
  3827. * if it gets no pid (pid < 0). However,
  3828. * if child sends us a signal *and immediately exits*,
  3829. * blocking_wait_with_raise_on_sig gets pid > 0
  3830. * and does not handle pending_sig. Check this case: */
  3831. if (pending_sig)
  3832. raise_exception(EXSIG);
  3833. }
  3834. }
  3835. retval = 127;
  3836. do {
  3837. if (**argv != '%') {
  3838. pid_t pid = number(*argv);
  3839. job = curjob;
  3840. while (1) {
  3841. if (!job)
  3842. goto repeat;
  3843. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3844. break;
  3845. job = job->prev_job;
  3846. }
  3847. } else {
  3848. job = getjob(*argv, 0);
  3849. }
  3850. /* loop until process terminated or stopped */
  3851. while (job->state == JOBRUNNING)
  3852. blocking_wait_with_raise_on_sig();
  3853. job->waited = 1;
  3854. retval = getstatus(job);
  3855. repeat: ;
  3856. } while (*++argv);
  3857. ret:
  3858. return retval;
  3859. }
  3860. static struct job *
  3861. growjobtab(void)
  3862. {
  3863. size_t len;
  3864. ptrdiff_t offset;
  3865. struct job *jp, *jq;
  3866. len = njobs * sizeof(*jp);
  3867. jq = jobtab;
  3868. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3869. offset = (char *)jp - (char *)jq;
  3870. if (offset) {
  3871. /* Relocate pointers */
  3872. size_t l = len;
  3873. jq = (struct job *)((char *)jq + l);
  3874. while (l) {
  3875. l -= sizeof(*jp);
  3876. jq--;
  3877. #define joff(p) ((struct job *)((char *)(p) + l))
  3878. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3879. if (joff(jp)->ps == &jq->ps0)
  3880. jmove(joff(jp)->ps);
  3881. if (joff(jp)->prev_job)
  3882. jmove(joff(jp)->prev_job);
  3883. }
  3884. if (curjob)
  3885. jmove(curjob);
  3886. #undef joff
  3887. #undef jmove
  3888. }
  3889. njobs += 4;
  3890. jobtab = jp;
  3891. jp = (struct job *)((char *)jp + len);
  3892. jq = jp + 3;
  3893. do {
  3894. jq->used = 0;
  3895. } while (--jq >= jp);
  3896. return jp;
  3897. }
  3898. /*
  3899. * Return a new job structure.
  3900. * Called with interrupts off.
  3901. */
  3902. static struct job *
  3903. makejob(/*union node *node,*/ int nprocs)
  3904. {
  3905. int i;
  3906. struct job *jp;
  3907. for (i = njobs, jp = jobtab; ; jp++) {
  3908. if (--i < 0) {
  3909. jp = growjobtab();
  3910. break;
  3911. }
  3912. if (jp->used == 0)
  3913. break;
  3914. if (jp->state != JOBDONE || !jp->waited)
  3915. continue;
  3916. #if JOBS
  3917. if (doing_jobctl)
  3918. continue;
  3919. #endif
  3920. freejob(jp);
  3921. break;
  3922. }
  3923. memset(jp, 0, sizeof(*jp));
  3924. #if JOBS
  3925. /* jp->jobctl is a bitfield.
  3926. * "jp->jobctl |= jobctl" likely to give awful code */
  3927. if (doing_jobctl)
  3928. jp->jobctl = 1;
  3929. #endif
  3930. jp->prev_job = curjob;
  3931. curjob = jp;
  3932. jp->used = 1;
  3933. jp->ps = &jp->ps0;
  3934. if (nprocs > 1) {
  3935. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3936. }
  3937. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3938. jobno(jp)));
  3939. return jp;
  3940. }
  3941. #if JOBS
  3942. /*
  3943. * Return a string identifying a command (to be printed by the
  3944. * jobs command).
  3945. */
  3946. static char *cmdnextc;
  3947. static void
  3948. cmdputs(const char *s)
  3949. {
  3950. static const char vstype[VSTYPE + 1][3] = {
  3951. "", "}", "-", "+", "?", "=",
  3952. "%", "%%", "#", "##"
  3953. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3954. };
  3955. const char *p, *str;
  3956. char cc[2];
  3957. char *nextc;
  3958. unsigned char c;
  3959. unsigned char subtype = 0;
  3960. int quoted = 0;
  3961. cc[1] = '\0';
  3962. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3963. p = s;
  3964. while ((c = *p++) != '\0') {
  3965. str = NULL;
  3966. switch (c) {
  3967. case CTLESC:
  3968. c = *p++;
  3969. break;
  3970. case CTLVAR:
  3971. subtype = *p++;
  3972. if ((subtype & VSTYPE) == VSLENGTH)
  3973. str = "${#";
  3974. else
  3975. str = "${";
  3976. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3977. goto dostr;
  3978. quoted ^= 1;
  3979. c = '"';
  3980. break;
  3981. case CTLENDVAR:
  3982. str = "\"}" + !(quoted & 1);
  3983. quoted >>= 1;
  3984. subtype = 0;
  3985. goto dostr;
  3986. case CTLBACKQ:
  3987. str = "$(...)";
  3988. goto dostr;
  3989. case CTLBACKQ+CTLQUOTE:
  3990. str = "\"$(...)\"";
  3991. goto dostr;
  3992. #if ENABLE_SH_MATH_SUPPORT
  3993. case CTLARI:
  3994. str = "$((";
  3995. goto dostr;
  3996. case CTLENDARI:
  3997. str = "))";
  3998. goto dostr;
  3999. #endif
  4000. case CTLQUOTEMARK:
  4001. quoted ^= 1;
  4002. c = '"';
  4003. break;
  4004. case '=':
  4005. if (subtype == 0)
  4006. break;
  4007. if ((subtype & VSTYPE) != VSNORMAL)
  4008. quoted <<= 1;
  4009. str = vstype[subtype & VSTYPE];
  4010. if (subtype & VSNUL)
  4011. c = ':';
  4012. else
  4013. goto checkstr;
  4014. break;
  4015. case '\'':
  4016. case '\\':
  4017. case '"':
  4018. case '$':
  4019. /* These can only happen inside quotes */
  4020. cc[0] = c;
  4021. str = cc;
  4022. c = '\\';
  4023. break;
  4024. default:
  4025. break;
  4026. }
  4027. USTPUTC(c, nextc);
  4028. checkstr:
  4029. if (!str)
  4030. continue;
  4031. dostr:
  4032. while ((c = *str++) != '\0') {
  4033. USTPUTC(c, nextc);
  4034. }
  4035. } /* while *p++ not NUL */
  4036. if (quoted & 1) {
  4037. USTPUTC('"', nextc);
  4038. }
  4039. *nextc = 0;
  4040. cmdnextc = nextc;
  4041. }
  4042. /* cmdtxt() and cmdlist() call each other */
  4043. static void cmdtxt(union node *n);
  4044. static void
  4045. cmdlist(union node *np, int sep)
  4046. {
  4047. for (; np; np = np->narg.next) {
  4048. if (!sep)
  4049. cmdputs(" ");
  4050. cmdtxt(np);
  4051. if (sep && np->narg.next)
  4052. cmdputs(" ");
  4053. }
  4054. }
  4055. static void
  4056. cmdtxt(union node *n)
  4057. {
  4058. union node *np;
  4059. struct nodelist *lp;
  4060. const char *p;
  4061. if (!n)
  4062. return;
  4063. switch (n->type) {
  4064. default:
  4065. #if DEBUG
  4066. abort();
  4067. #endif
  4068. case NPIPE:
  4069. lp = n->npipe.cmdlist;
  4070. for (;;) {
  4071. cmdtxt(lp->n);
  4072. lp = lp->next;
  4073. if (!lp)
  4074. break;
  4075. cmdputs(" | ");
  4076. }
  4077. break;
  4078. case NSEMI:
  4079. p = "; ";
  4080. goto binop;
  4081. case NAND:
  4082. p = " && ";
  4083. goto binop;
  4084. case NOR:
  4085. p = " || ";
  4086. binop:
  4087. cmdtxt(n->nbinary.ch1);
  4088. cmdputs(p);
  4089. n = n->nbinary.ch2;
  4090. goto donode;
  4091. case NREDIR:
  4092. case NBACKGND:
  4093. n = n->nredir.n;
  4094. goto donode;
  4095. case NNOT:
  4096. cmdputs("!");
  4097. n = n->nnot.com;
  4098. donode:
  4099. cmdtxt(n);
  4100. break;
  4101. case NIF:
  4102. cmdputs("if ");
  4103. cmdtxt(n->nif.test);
  4104. cmdputs("; then ");
  4105. if (n->nif.elsepart) {
  4106. cmdtxt(n->nif.ifpart);
  4107. cmdputs("; else ");
  4108. n = n->nif.elsepart;
  4109. } else {
  4110. n = n->nif.ifpart;
  4111. }
  4112. p = "; fi";
  4113. goto dotail;
  4114. case NSUBSHELL:
  4115. cmdputs("(");
  4116. n = n->nredir.n;
  4117. p = ")";
  4118. goto dotail;
  4119. case NWHILE:
  4120. p = "while ";
  4121. goto until;
  4122. case NUNTIL:
  4123. p = "until ";
  4124. until:
  4125. cmdputs(p);
  4126. cmdtxt(n->nbinary.ch1);
  4127. n = n->nbinary.ch2;
  4128. p = "; done";
  4129. dodo:
  4130. cmdputs("; do ");
  4131. dotail:
  4132. cmdtxt(n);
  4133. goto dotail2;
  4134. case NFOR:
  4135. cmdputs("for ");
  4136. cmdputs(n->nfor.var);
  4137. cmdputs(" in ");
  4138. cmdlist(n->nfor.args, 1);
  4139. n = n->nfor.body;
  4140. p = "; done";
  4141. goto dodo;
  4142. case NDEFUN:
  4143. cmdputs(n->narg.text);
  4144. p = "() { ... }";
  4145. goto dotail2;
  4146. case NCMD:
  4147. cmdlist(n->ncmd.args, 1);
  4148. cmdlist(n->ncmd.redirect, 0);
  4149. break;
  4150. case NARG:
  4151. p = n->narg.text;
  4152. dotail2:
  4153. cmdputs(p);
  4154. break;
  4155. case NHERE:
  4156. case NXHERE:
  4157. p = "<<...";
  4158. goto dotail2;
  4159. case NCASE:
  4160. cmdputs("case ");
  4161. cmdputs(n->ncase.expr->narg.text);
  4162. cmdputs(" in ");
  4163. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4164. cmdtxt(np->nclist.pattern);
  4165. cmdputs(") ");
  4166. cmdtxt(np->nclist.body);
  4167. cmdputs(";; ");
  4168. }
  4169. p = "esac";
  4170. goto dotail2;
  4171. case NTO:
  4172. p = ">";
  4173. goto redir;
  4174. case NCLOBBER:
  4175. p = ">|";
  4176. goto redir;
  4177. case NAPPEND:
  4178. p = ">>";
  4179. goto redir;
  4180. #if ENABLE_ASH_BASH_COMPAT
  4181. case NTO2:
  4182. #endif
  4183. case NTOFD:
  4184. p = ">&";
  4185. goto redir;
  4186. case NFROM:
  4187. p = "<";
  4188. goto redir;
  4189. case NFROMFD:
  4190. p = "<&";
  4191. goto redir;
  4192. case NFROMTO:
  4193. p = "<>";
  4194. redir:
  4195. cmdputs(utoa(n->nfile.fd));
  4196. cmdputs(p);
  4197. if (n->type == NTOFD || n->type == NFROMFD) {
  4198. cmdputs(utoa(n->ndup.dupfd));
  4199. break;
  4200. }
  4201. n = n->nfile.fname;
  4202. goto donode;
  4203. }
  4204. }
  4205. static char *
  4206. commandtext(union node *n)
  4207. {
  4208. char *name;
  4209. STARTSTACKSTR(cmdnextc);
  4210. cmdtxt(n);
  4211. name = stackblock();
  4212. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4213. name, cmdnextc, cmdnextc));
  4214. return ckstrdup(name);
  4215. }
  4216. #endif /* JOBS */
  4217. /*
  4218. * Fork off a subshell. If we are doing job control, give the subshell its
  4219. * own process group. Jp is a job structure that the job is to be added to.
  4220. * N is the command that will be evaluated by the child. Both jp and n may
  4221. * be NULL. The mode parameter can be one of the following:
  4222. * FORK_FG - Fork off a foreground process.
  4223. * FORK_BG - Fork off a background process.
  4224. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4225. * process group even if job control is on.
  4226. *
  4227. * When job control is turned off, background processes have their standard
  4228. * input redirected to /dev/null (except for the second and later processes
  4229. * in a pipeline).
  4230. *
  4231. * Called with interrupts off.
  4232. */
  4233. /*
  4234. * Clear traps on a fork.
  4235. */
  4236. static void
  4237. clear_traps(void)
  4238. {
  4239. char **tp;
  4240. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4241. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4242. INT_OFF;
  4243. if (trap_ptr == trap)
  4244. free(*tp);
  4245. /* else: it "belongs" to trap_ptr vector, don't free */
  4246. *tp = NULL;
  4247. if ((tp - trap) != 0)
  4248. setsignal(tp - trap);
  4249. INT_ON;
  4250. }
  4251. }
  4252. may_have_traps = 0;
  4253. }
  4254. /* Lives far away from here, needed for forkchild */
  4255. static void closescript(void);
  4256. /* Called after fork(), in child */
  4257. static NOINLINE void
  4258. forkchild(struct job *jp, union node *n, int mode)
  4259. {
  4260. int oldlvl;
  4261. TRACE(("Child shell %d\n", getpid()));
  4262. oldlvl = shlvl;
  4263. shlvl++;
  4264. /* man bash: "Non-builtin commands run by bash have signal handlers
  4265. * set to the values inherited by the shell from its parent".
  4266. * Do we do it correctly? */
  4267. closescript();
  4268. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4269. && n && n->type == NCMD /* is it single cmd? */
  4270. /* && n->ncmd.args->type == NARG - always true? */
  4271. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4272. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4273. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4274. ) {
  4275. TRACE(("Trap hack\n"));
  4276. /* Awful hack for `trap` or $(trap).
  4277. *
  4278. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4279. * contains an example where "trap" is executed in a subshell:
  4280. *
  4281. * save_traps=$(trap)
  4282. * ...
  4283. * eval "$save_traps"
  4284. *
  4285. * Standard does not say that "trap" in subshell shall print
  4286. * parent shell's traps. It only says that its output
  4287. * must have suitable form, but then, in the above example
  4288. * (which is not supposed to be normative), it implies that.
  4289. *
  4290. * bash (and probably other shell) does implement it
  4291. * (traps are reset to defaults, but "trap" still shows them),
  4292. * but as a result, "trap" logic is hopelessly messed up:
  4293. *
  4294. * # trap
  4295. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4296. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4297. * # true | trap <--- trap is in subshell - no output (ditto)
  4298. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4299. * trap -- 'echo Ho' SIGWINCH
  4300. * # echo `(trap)` <--- in subshell in subshell - output
  4301. * trap -- 'echo Ho' SIGWINCH
  4302. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4303. * trap -- 'echo Ho' SIGWINCH
  4304. *
  4305. * The rules when to forget and when to not forget traps
  4306. * get really complex and nonsensical.
  4307. *
  4308. * Our solution: ONLY bare $(trap) or `trap` is special.
  4309. */
  4310. /* Save trap handler strings for trap builtin to print */
  4311. trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
  4312. /* Fall through into clearing traps */
  4313. }
  4314. clear_traps();
  4315. #if JOBS
  4316. /* do job control only in root shell */
  4317. doing_jobctl = 0;
  4318. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4319. pid_t pgrp;
  4320. if (jp->nprocs == 0)
  4321. pgrp = getpid();
  4322. else
  4323. pgrp = jp->ps[0].ps_pid;
  4324. /* this can fail because we are doing it in the parent also */
  4325. setpgid(0, pgrp);
  4326. if (mode == FORK_FG)
  4327. xtcsetpgrp(ttyfd, pgrp);
  4328. setsignal(SIGTSTP);
  4329. setsignal(SIGTTOU);
  4330. } else
  4331. #endif
  4332. if (mode == FORK_BG) {
  4333. /* man bash: "When job control is not in effect,
  4334. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4335. ignoresig(SIGINT);
  4336. ignoresig(SIGQUIT);
  4337. if (jp->nprocs == 0) {
  4338. close(0);
  4339. if (open(bb_dev_null, O_RDONLY) != 0)
  4340. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4341. }
  4342. }
  4343. if (oldlvl == 0) {
  4344. if (iflag) { /* why if iflag only? */
  4345. setsignal(SIGINT);
  4346. setsignal(SIGTERM);
  4347. }
  4348. /* man bash:
  4349. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4350. * commands run by bash have signal handlers
  4351. * set to the values inherited by the shell
  4352. * from its parent".
  4353. * Take care of the second rule: */
  4354. setsignal(SIGQUIT);
  4355. }
  4356. #if JOBS
  4357. if (n && n->type == NCMD
  4358. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4359. ) {
  4360. TRACE(("Job hack\n"));
  4361. /* "jobs": we do not want to clear job list for it,
  4362. * instead we remove only _its_ own_ job from job list.
  4363. * This makes "jobs .... | cat" more useful.
  4364. */
  4365. freejob(curjob);
  4366. return;
  4367. }
  4368. #endif
  4369. for (jp = curjob; jp; jp = jp->prev_job)
  4370. freejob(jp);
  4371. jobless = 0;
  4372. }
  4373. /* Called after fork(), in parent */
  4374. #if !JOBS
  4375. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4376. #endif
  4377. static void
  4378. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4379. {
  4380. TRACE(("In parent shell: child = %d\n", pid));
  4381. if (!jp) {
  4382. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4383. continue;
  4384. jobless++;
  4385. return;
  4386. }
  4387. #if JOBS
  4388. if (mode != FORK_NOJOB && jp->jobctl) {
  4389. int pgrp;
  4390. if (jp->nprocs == 0)
  4391. pgrp = pid;
  4392. else
  4393. pgrp = jp->ps[0].ps_pid;
  4394. /* This can fail because we are doing it in the child also */
  4395. setpgid(pid, pgrp);
  4396. }
  4397. #endif
  4398. if (mode == FORK_BG) {
  4399. backgndpid = pid; /* set $! */
  4400. set_curjob(jp, CUR_RUNNING);
  4401. }
  4402. if (jp) {
  4403. struct procstat *ps = &jp->ps[jp->nprocs++];
  4404. ps->ps_pid = pid;
  4405. ps->ps_status = -1;
  4406. ps->ps_cmd = nullstr;
  4407. #if JOBS
  4408. if (doing_jobctl && n)
  4409. ps->ps_cmd = commandtext(n);
  4410. #endif
  4411. }
  4412. }
  4413. static int
  4414. forkshell(struct job *jp, union node *n, int mode)
  4415. {
  4416. int pid;
  4417. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4418. pid = fork();
  4419. if (pid < 0) {
  4420. TRACE(("Fork failed, errno=%d", errno));
  4421. if (jp)
  4422. freejob(jp);
  4423. ash_msg_and_raise_error("can't fork");
  4424. }
  4425. if (pid == 0) {
  4426. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4427. forkchild(jp, n, mode);
  4428. } else {
  4429. forkparent(jp, n, mode, pid);
  4430. }
  4431. return pid;
  4432. }
  4433. /*
  4434. * Wait for job to finish.
  4435. *
  4436. * Under job control we have the problem that while a child process
  4437. * is running interrupts generated by the user are sent to the child
  4438. * but not to the shell. This means that an infinite loop started by
  4439. * an interactive user may be hard to kill. With job control turned off,
  4440. * an interactive user may place an interactive program inside a loop.
  4441. * If the interactive program catches interrupts, the user doesn't want
  4442. * these interrupts to also abort the loop. The approach we take here
  4443. * is to have the shell ignore interrupt signals while waiting for a
  4444. * foreground process to terminate, and then send itself an interrupt
  4445. * signal if the child process was terminated by an interrupt signal.
  4446. * Unfortunately, some programs want to do a bit of cleanup and then
  4447. * exit on interrupt; unless these processes terminate themselves by
  4448. * sending a signal to themselves (instead of calling exit) they will
  4449. * confuse this approach.
  4450. *
  4451. * Called with interrupts off.
  4452. */
  4453. static int
  4454. waitforjob(struct job *jp)
  4455. {
  4456. int st;
  4457. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4458. INT_OFF;
  4459. while (jp->state == JOBRUNNING) {
  4460. /* In non-interactive shells, we _can_ get
  4461. * a keyboard signal here and be EINTRed,
  4462. * but we just loop back, waiting for command to complete.
  4463. *
  4464. * man bash:
  4465. * "If bash is waiting for a command to complete and receives
  4466. * a signal for which a trap has been set, the trap
  4467. * will not be executed until the command completes."
  4468. *
  4469. * Reality is that even if trap is not set, bash
  4470. * will not act on the signal until command completes.
  4471. * Try this. sleep5intoff.c:
  4472. * #include <signal.h>
  4473. * #include <unistd.h>
  4474. * int main() {
  4475. * sigset_t set;
  4476. * sigemptyset(&set);
  4477. * sigaddset(&set, SIGINT);
  4478. * sigaddset(&set, SIGQUIT);
  4479. * sigprocmask(SIG_BLOCK, &set, NULL);
  4480. * sleep(5);
  4481. * return 0;
  4482. * }
  4483. * $ bash -c './sleep5intoff; echo hi'
  4484. * ^C^C^C^C <--- pressing ^C once a second
  4485. * $ _
  4486. * $ bash -c './sleep5intoff; echo hi'
  4487. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4488. * $ _
  4489. */
  4490. dowait(DOWAIT_BLOCK, jp);
  4491. }
  4492. INT_ON;
  4493. st = getstatus(jp);
  4494. #if JOBS
  4495. if (jp->jobctl) {
  4496. xtcsetpgrp(ttyfd, rootpid);
  4497. /*
  4498. * This is truly gross.
  4499. * If we're doing job control, then we did a TIOCSPGRP which
  4500. * caused us (the shell) to no longer be in the controlling
  4501. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4502. * intuit from the subprocess exit status whether a SIGINT
  4503. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4504. */
  4505. if (jp->sigint) /* TODO: do the same with all signals */
  4506. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4507. }
  4508. if (jp->state == JOBDONE)
  4509. #endif
  4510. freejob(jp);
  4511. return st;
  4512. }
  4513. /*
  4514. * return 1 if there are stopped jobs, otherwise 0
  4515. */
  4516. static int
  4517. stoppedjobs(void)
  4518. {
  4519. struct job *jp;
  4520. int retval;
  4521. retval = 0;
  4522. if (job_warning)
  4523. goto out;
  4524. jp = curjob;
  4525. if (jp && jp->state == JOBSTOPPED) {
  4526. out2str("You have stopped jobs.\n");
  4527. job_warning = 2;
  4528. retval++;
  4529. }
  4530. out:
  4531. return retval;
  4532. }
  4533. /* ============ redir.c
  4534. *
  4535. * Code for dealing with input/output redirection.
  4536. */
  4537. #undef EMPTY
  4538. #undef CLOSED
  4539. #define EMPTY -2 /* marks an unused slot in redirtab */
  4540. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4541. /*
  4542. * Open a file in noclobber mode.
  4543. * The code was copied from bash.
  4544. */
  4545. static int
  4546. noclobberopen(const char *fname)
  4547. {
  4548. int r, fd;
  4549. struct stat finfo, finfo2;
  4550. /*
  4551. * If the file exists and is a regular file, return an error
  4552. * immediately.
  4553. */
  4554. r = stat(fname, &finfo);
  4555. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4556. errno = EEXIST;
  4557. return -1;
  4558. }
  4559. /*
  4560. * If the file was not present (r != 0), make sure we open it
  4561. * exclusively so that if it is created before we open it, our open
  4562. * will fail. Make sure that we do not truncate an existing file.
  4563. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4564. * file was not a regular file, we leave O_EXCL off.
  4565. */
  4566. if (r != 0)
  4567. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4568. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4569. /* If the open failed, return the file descriptor right away. */
  4570. if (fd < 0)
  4571. return fd;
  4572. /*
  4573. * OK, the open succeeded, but the file may have been changed from a
  4574. * non-regular file to a regular file between the stat and the open.
  4575. * We are assuming that the O_EXCL open handles the case where FILENAME
  4576. * did not exist and is symlinked to an existing file between the stat
  4577. * and open.
  4578. */
  4579. /*
  4580. * If we can open it and fstat the file descriptor, and neither check
  4581. * revealed that it was a regular file, and the file has not been
  4582. * replaced, return the file descriptor.
  4583. */
  4584. if (fstat(fd, &finfo2) == 0
  4585. && !S_ISREG(finfo2.st_mode)
  4586. && finfo.st_dev == finfo2.st_dev
  4587. && finfo.st_ino == finfo2.st_ino
  4588. ) {
  4589. return fd;
  4590. }
  4591. /* The file has been replaced. badness. */
  4592. close(fd);
  4593. errno = EEXIST;
  4594. return -1;
  4595. }
  4596. /*
  4597. * Handle here documents. Normally we fork off a process to write the
  4598. * data to a pipe. If the document is short, we can stuff the data in
  4599. * the pipe without forking.
  4600. */
  4601. /* openhere needs this forward reference */
  4602. static void expandhere(union node *arg, int fd);
  4603. static int
  4604. openhere(union node *redir)
  4605. {
  4606. int pip[2];
  4607. size_t len = 0;
  4608. if (pipe(pip) < 0)
  4609. ash_msg_and_raise_error("pipe call failed");
  4610. if (redir->type == NHERE) {
  4611. len = strlen(redir->nhere.doc->narg.text);
  4612. if (len <= PIPE_BUF) {
  4613. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4614. goto out;
  4615. }
  4616. }
  4617. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4618. /* child */
  4619. close(pip[0]);
  4620. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4621. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4622. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4623. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4624. signal(SIGPIPE, SIG_DFL);
  4625. if (redir->type == NHERE)
  4626. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4627. else /* NXHERE */
  4628. expandhere(redir->nhere.doc, pip[1]);
  4629. _exit(EXIT_SUCCESS);
  4630. }
  4631. out:
  4632. close(pip[1]);
  4633. return pip[0];
  4634. }
  4635. static int
  4636. openredirect(union node *redir)
  4637. {
  4638. char *fname;
  4639. int f;
  4640. fname = redir->nfile.expfname;
  4641. switch (redir->nfile.type) {
  4642. case NFROM:
  4643. f = open(fname, O_RDONLY);
  4644. if (f < 0)
  4645. goto eopen;
  4646. break;
  4647. case NFROMTO:
  4648. f = open(fname, O_RDWR|O_CREAT, 0666);
  4649. if (f < 0)
  4650. goto ecreate;
  4651. break;
  4652. case NTO:
  4653. #if ENABLE_ASH_BASH_COMPAT
  4654. case NTO2:
  4655. #endif
  4656. /* Take care of noclobber mode. */
  4657. if (Cflag) {
  4658. f = noclobberopen(fname);
  4659. if (f < 0)
  4660. goto ecreate;
  4661. break;
  4662. }
  4663. /* FALLTHROUGH */
  4664. case NCLOBBER:
  4665. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4666. if (f < 0)
  4667. goto ecreate;
  4668. break;
  4669. case NAPPEND:
  4670. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4671. if (f < 0)
  4672. goto ecreate;
  4673. break;
  4674. default:
  4675. #if DEBUG
  4676. abort();
  4677. #endif
  4678. /* Fall through to eliminate warning. */
  4679. /* Our single caller does this itself */
  4680. // case NTOFD:
  4681. // case NFROMFD:
  4682. // f = -1;
  4683. // break;
  4684. case NHERE:
  4685. case NXHERE:
  4686. f = openhere(redir);
  4687. break;
  4688. }
  4689. return f;
  4690. ecreate:
  4691. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4692. eopen:
  4693. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4694. }
  4695. /*
  4696. * Copy a file descriptor to be >= to. Returns -1
  4697. * if the source file descriptor is closed, EMPTY if there are no unused
  4698. * file descriptors left.
  4699. */
  4700. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4701. * old code was doing close(to) prior to copyfd() to achieve the same */
  4702. enum {
  4703. COPYFD_EXACT = (int)~(INT_MAX),
  4704. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4705. };
  4706. static int
  4707. copyfd(int from, int to)
  4708. {
  4709. int newfd;
  4710. if (to & COPYFD_EXACT) {
  4711. to &= ~COPYFD_EXACT;
  4712. /*if (from != to)*/
  4713. newfd = dup2(from, to);
  4714. } else {
  4715. newfd = fcntl(from, F_DUPFD, to);
  4716. }
  4717. if (newfd < 0) {
  4718. if (errno == EMFILE)
  4719. return EMPTY;
  4720. /* Happens when source fd is not open: try "echo >&99" */
  4721. ash_msg_and_raise_error("%d: %m", from);
  4722. }
  4723. return newfd;
  4724. }
  4725. /* Struct def and variable are moved down to the first usage site */
  4726. struct two_fd_t {
  4727. int orig, copy;
  4728. };
  4729. struct redirtab {
  4730. struct redirtab *next;
  4731. int nullredirs;
  4732. int pair_count;
  4733. struct two_fd_t two_fd[];
  4734. };
  4735. #define redirlist (G_var.redirlist)
  4736. static int need_to_remember(struct redirtab *rp, int fd)
  4737. {
  4738. int i;
  4739. if (!rp) /* remembering was not requested */
  4740. return 0;
  4741. for (i = 0; i < rp->pair_count; i++) {
  4742. if (rp->two_fd[i].orig == fd) {
  4743. /* already remembered */
  4744. return 0;
  4745. }
  4746. }
  4747. return 1;
  4748. }
  4749. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4750. static int is_hidden_fd(struct redirtab *rp, int fd)
  4751. {
  4752. int i;
  4753. struct parsefile *pf;
  4754. if (fd == -1)
  4755. return 0;
  4756. /* Check open scripts' fds */
  4757. pf = g_parsefile;
  4758. while (pf) {
  4759. /* We skip pf_fd == 0 case because of the following case:
  4760. * $ ash # running ash interactively
  4761. * $ . ./script.sh
  4762. * and in script.sh: "exec 9>&0".
  4763. * Even though top-level pf_fd _is_ 0,
  4764. * it's still ok to use it: "read" builtin uses it,
  4765. * why should we cripple "exec" builtin?
  4766. */
  4767. if (pf->pf_fd > 0 && fd == pf->pf_fd) {
  4768. return 1;
  4769. }
  4770. pf = pf->prev;
  4771. }
  4772. if (!rp)
  4773. return 0;
  4774. /* Check saved fds of redirects */
  4775. fd |= COPYFD_RESTORE;
  4776. for (i = 0; i < rp->pair_count; i++) {
  4777. if (rp->two_fd[i].copy == fd) {
  4778. return 1;
  4779. }
  4780. }
  4781. return 0;
  4782. }
  4783. /*
  4784. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4785. * old file descriptors are stashed away so that the redirection can be
  4786. * undone by calling popredir.
  4787. */
  4788. /* flags passed to redirect */
  4789. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4790. #define REDIR_SAVEFD2 03 /* set preverrout */
  4791. static void
  4792. redirect(union node *redir, int flags)
  4793. {
  4794. struct redirtab *sv;
  4795. int sv_pos;
  4796. int i;
  4797. int fd;
  4798. int newfd;
  4799. int copied_fd2 = -1;
  4800. g_nullredirs++;
  4801. if (!redir) {
  4802. return;
  4803. }
  4804. sv = NULL;
  4805. sv_pos = 0;
  4806. INT_OFF;
  4807. if (flags & REDIR_PUSH) {
  4808. union node *tmp = redir;
  4809. do {
  4810. sv_pos++;
  4811. #if ENABLE_ASH_BASH_COMPAT
  4812. if (tmp->nfile.type == NTO2)
  4813. sv_pos++;
  4814. #endif
  4815. tmp = tmp->nfile.next;
  4816. } while (tmp);
  4817. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4818. sv->next = redirlist;
  4819. sv->pair_count = sv_pos;
  4820. redirlist = sv;
  4821. sv->nullredirs = g_nullredirs - 1;
  4822. g_nullredirs = 0;
  4823. while (sv_pos > 0) {
  4824. sv_pos--;
  4825. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4826. }
  4827. }
  4828. do {
  4829. int right_fd = -1;
  4830. fd = redir->nfile.fd;
  4831. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4832. right_fd = redir->ndup.dupfd;
  4833. //bb_error_msg("doing %d > %d", fd, right_fd);
  4834. /* redirect from/to same file descriptor? */
  4835. if (right_fd == fd)
  4836. continue;
  4837. /* "echo >&10" and 10 is a fd opened to a sh script? */
  4838. if (is_hidden_fd(sv, right_fd)) {
  4839. errno = EBADF; /* as if it is closed */
  4840. ash_msg_and_raise_error("%d: %m", right_fd);
  4841. }
  4842. newfd = -1;
  4843. } else {
  4844. newfd = openredirect(redir); /* always >= 0 */
  4845. if (fd == newfd) {
  4846. /* Descriptor wasn't open before redirect.
  4847. * Mark it for close in the future */
  4848. if (need_to_remember(sv, fd)) {
  4849. goto remember_to_close;
  4850. }
  4851. continue;
  4852. }
  4853. }
  4854. #if ENABLE_ASH_BASH_COMPAT
  4855. redirect_more:
  4856. #endif
  4857. if (need_to_remember(sv, fd)) {
  4858. /* Copy old descriptor */
  4859. /* Careful to not accidentally "save"
  4860. * to the same fd as right side fd in N>&M */
  4861. int minfd = right_fd < 10 ? 10 : right_fd + 1;
  4862. i = fcntl(fd, F_DUPFD, minfd);
  4863. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4864. * are closed in popredir() in the child, preventing them from leaking
  4865. * into child. (popredir() also cleans up the mess in case of failures)
  4866. */
  4867. if (i == -1) {
  4868. i = errno;
  4869. if (i != EBADF) {
  4870. /* Strange error (e.g. "too many files" EMFILE?) */
  4871. if (newfd >= 0)
  4872. close(newfd);
  4873. errno = i;
  4874. ash_msg_and_raise_error("%d: %m", fd);
  4875. /* NOTREACHED */
  4876. }
  4877. /* EBADF: it is not open - good, remember to close it */
  4878. remember_to_close:
  4879. i = CLOSED;
  4880. } else { /* fd is open, save its copy */
  4881. /* "exec fd>&-" should not close fds
  4882. * which point to script file(s).
  4883. * Force them to be restored afterwards */
  4884. if (is_hidden_fd(sv, fd))
  4885. i |= COPYFD_RESTORE;
  4886. }
  4887. if (fd == 2)
  4888. copied_fd2 = i;
  4889. sv->two_fd[sv_pos].orig = fd;
  4890. sv->two_fd[sv_pos].copy = i;
  4891. sv_pos++;
  4892. }
  4893. if (newfd < 0) {
  4894. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4895. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4896. /* Don't want to trigger debugging */
  4897. if (fd != -1)
  4898. close(fd);
  4899. } else {
  4900. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4901. }
  4902. } else if (fd != newfd) { /* move newfd to fd */
  4903. copyfd(newfd, fd | COPYFD_EXACT);
  4904. #if ENABLE_ASH_BASH_COMPAT
  4905. if (!(redir->nfile.type == NTO2 && fd == 2))
  4906. #endif
  4907. close(newfd);
  4908. }
  4909. #if ENABLE_ASH_BASH_COMPAT
  4910. if (redir->nfile.type == NTO2 && fd == 1) {
  4911. /* We already redirected it to fd 1, now copy it to 2 */
  4912. newfd = 1;
  4913. fd = 2;
  4914. goto redirect_more;
  4915. }
  4916. #endif
  4917. } while ((redir = redir->nfile.next) != NULL);
  4918. INT_ON;
  4919. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4920. preverrout_fd = copied_fd2;
  4921. }
  4922. /*
  4923. * Undo the effects of the last redirection.
  4924. */
  4925. static void
  4926. popredir(int drop, int restore)
  4927. {
  4928. struct redirtab *rp;
  4929. int i;
  4930. if (--g_nullredirs >= 0)
  4931. return;
  4932. INT_OFF;
  4933. rp = redirlist;
  4934. for (i = 0; i < rp->pair_count; i++) {
  4935. int fd = rp->two_fd[i].orig;
  4936. int copy = rp->two_fd[i].copy;
  4937. if (copy == CLOSED) {
  4938. if (!drop)
  4939. close(fd);
  4940. continue;
  4941. }
  4942. if (copy != EMPTY) {
  4943. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4944. copy &= ~COPYFD_RESTORE;
  4945. /*close(fd);*/
  4946. copyfd(copy, fd | COPYFD_EXACT);
  4947. }
  4948. close(copy & ~COPYFD_RESTORE);
  4949. }
  4950. }
  4951. redirlist = rp->next;
  4952. g_nullredirs = rp->nullredirs;
  4953. free(rp);
  4954. INT_ON;
  4955. }
  4956. /*
  4957. * Undo all redirections. Called on error or interrupt.
  4958. */
  4959. /*
  4960. * Discard all saved file descriptors.
  4961. */
  4962. static void
  4963. clearredir(int drop)
  4964. {
  4965. for (;;) {
  4966. g_nullredirs = 0;
  4967. if (!redirlist)
  4968. break;
  4969. popredir(drop, /*restore:*/ 0);
  4970. }
  4971. }
  4972. static int
  4973. redirectsafe(union node *redir, int flags)
  4974. {
  4975. int err;
  4976. volatile int saveint;
  4977. struct jmploc *volatile savehandler = exception_handler;
  4978. struct jmploc jmploc;
  4979. SAVE_INT(saveint);
  4980. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4981. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4982. if (!err) {
  4983. exception_handler = &jmploc;
  4984. redirect(redir, flags);
  4985. }
  4986. exception_handler = savehandler;
  4987. if (err && exception_type != EXERROR)
  4988. longjmp(exception_handler->loc, 1);
  4989. RESTORE_INT(saveint);
  4990. return err;
  4991. }
  4992. /* ============ Routines to expand arguments to commands
  4993. *
  4994. * We have to deal with backquotes, shell variables, and file metacharacters.
  4995. */
  4996. #if ENABLE_SH_MATH_SUPPORT
  4997. static arith_t
  4998. ash_arith(const char *s)
  4999. {
  5000. arith_state_t math_state;
  5001. arith_t result;
  5002. math_state.lookupvar = lookupvar;
  5003. math_state.setvar = setvar2;
  5004. //math_state.endofname = endofname;
  5005. INT_OFF;
  5006. result = arith(&math_state, s);
  5007. if (math_state.errmsg)
  5008. ash_msg_and_raise_error(math_state.errmsg);
  5009. INT_ON;
  5010. return result;
  5011. }
  5012. #endif
  5013. /*
  5014. * expandarg flags
  5015. */
  5016. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5017. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5018. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5019. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5020. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5021. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  5022. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5023. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5024. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  5025. /*
  5026. * rmescape() flags
  5027. */
  5028. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5029. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5030. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  5031. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5032. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5033. /*
  5034. * Structure specifying which parts of the string should be searched
  5035. * for IFS characters.
  5036. */
  5037. struct ifsregion {
  5038. struct ifsregion *next; /* next region in list */
  5039. int begoff; /* offset of start of region */
  5040. int endoff; /* offset of end of region */
  5041. int nulonly; /* search for nul bytes only */
  5042. };
  5043. struct arglist {
  5044. struct strlist *list;
  5045. struct strlist **lastp;
  5046. };
  5047. /* output of current string */
  5048. static char *expdest;
  5049. /* list of back quote expressions */
  5050. static struct nodelist *argbackq;
  5051. /* first struct in list of ifs regions */
  5052. static struct ifsregion ifsfirst;
  5053. /* last struct in list */
  5054. static struct ifsregion *ifslastp;
  5055. /* holds expanded arg list */
  5056. static struct arglist exparg;
  5057. /*
  5058. * Our own itoa().
  5059. */
  5060. #if !ENABLE_SH_MATH_SUPPORT
  5061. /* cvtnum() is used even if math support is off (to prepare $? values and such) */
  5062. typedef long arith_t;
  5063. # define ARITH_FMT "%ld"
  5064. #endif
  5065. static int
  5066. cvtnum(arith_t num)
  5067. {
  5068. int len;
  5069. expdest = makestrspace(32, expdest);
  5070. len = fmtstr(expdest, 32, ARITH_FMT, num);
  5071. STADJUST(len, expdest);
  5072. return len;
  5073. }
  5074. static size_t
  5075. esclen(const char *start, const char *p)
  5076. {
  5077. size_t esc = 0;
  5078. while (p > start && (unsigned char)*--p == CTLESC) {
  5079. esc++;
  5080. }
  5081. return esc;
  5082. }
  5083. /*
  5084. * Remove any CTLESC characters from a string.
  5085. */
  5086. static char *
  5087. rmescapes(char *str, int flag)
  5088. {
  5089. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  5090. char *p, *q, *r;
  5091. unsigned inquotes;
  5092. unsigned protect_against_glob;
  5093. unsigned globbing;
  5094. p = strpbrk(str, qchars);
  5095. if (!p)
  5096. return str;
  5097. q = p;
  5098. r = str;
  5099. if (flag & RMESCAPE_ALLOC) {
  5100. size_t len = p - str;
  5101. size_t fulllen = len + strlen(p) + 1;
  5102. if (flag & RMESCAPE_GROW) {
  5103. int strloc = str - (char *)stackblock();
  5104. r = makestrspace(fulllen, expdest);
  5105. /* p and str may be invalidated by makestrspace */
  5106. str = (char *)stackblock() + strloc;
  5107. p = str + len;
  5108. } else if (flag & RMESCAPE_HEAP) {
  5109. r = ckmalloc(fulllen);
  5110. } else {
  5111. r = stalloc(fulllen);
  5112. }
  5113. q = r;
  5114. if (len > 0) {
  5115. q = (char *)memcpy(q, str, len) + len;
  5116. }
  5117. }
  5118. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  5119. globbing = flag & RMESCAPE_GLOB;
  5120. protect_against_glob = globbing;
  5121. while (*p) {
  5122. if ((unsigned char)*p == CTLQUOTEMARK) {
  5123. // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
  5124. // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
  5125. // Note: both inquotes and protect_against_glob only affect whether
  5126. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5127. inquotes = ~inquotes;
  5128. p++;
  5129. protect_against_glob = globbing;
  5130. continue;
  5131. }
  5132. if (*p == '\\') {
  5133. /* naked back slash */
  5134. protect_against_glob = 0;
  5135. goto copy;
  5136. }
  5137. if ((unsigned char)*p == CTLESC) {
  5138. p++;
  5139. if (protect_against_glob && inquotes && *p != '/') {
  5140. *q++ = '\\';
  5141. }
  5142. }
  5143. protect_against_glob = globbing;
  5144. copy:
  5145. *q++ = *p++;
  5146. }
  5147. *q = '\0';
  5148. if (flag & RMESCAPE_GROW) {
  5149. expdest = r;
  5150. STADJUST(q - r + 1, expdest);
  5151. }
  5152. return r;
  5153. }
  5154. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5155. /*
  5156. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5157. *
  5158. * Returns an stalloced string.
  5159. */
  5160. static char *
  5161. preglob(const char *pattern, int quoted, int flag)
  5162. {
  5163. flag |= RMESCAPE_GLOB;
  5164. if (quoted) {
  5165. flag |= RMESCAPE_QUOTED;
  5166. }
  5167. return rmescapes((char *)pattern, flag);
  5168. }
  5169. /*
  5170. * Put a string on the stack.
  5171. */
  5172. static void
  5173. memtodest(const char *p, size_t len, int syntax, int quotes)
  5174. {
  5175. char *q = expdest;
  5176. q = makestrspace(quotes ? len * 2 : len, q);
  5177. while (len--) {
  5178. unsigned char c = *p++;
  5179. if (c == '\0')
  5180. continue;
  5181. if (quotes) {
  5182. int n = SIT(c, syntax);
  5183. if (n == CCTL || n == CBACK)
  5184. USTPUTC(CTLESC, q);
  5185. }
  5186. USTPUTC(c, q);
  5187. }
  5188. expdest = q;
  5189. }
  5190. static void
  5191. strtodest(const char *p, int syntax, int quotes)
  5192. {
  5193. memtodest(p, strlen(p), syntax, quotes);
  5194. }
  5195. /*
  5196. * Record the fact that we have to scan this region of the
  5197. * string for IFS characters.
  5198. */
  5199. static void
  5200. recordregion(int start, int end, int nulonly)
  5201. {
  5202. struct ifsregion *ifsp;
  5203. if (ifslastp == NULL) {
  5204. ifsp = &ifsfirst;
  5205. } else {
  5206. INT_OFF;
  5207. ifsp = ckzalloc(sizeof(*ifsp));
  5208. /*ifsp->next = NULL; - ckzalloc did it */
  5209. ifslastp->next = ifsp;
  5210. INT_ON;
  5211. }
  5212. ifslastp = ifsp;
  5213. ifslastp->begoff = start;
  5214. ifslastp->endoff = end;
  5215. ifslastp->nulonly = nulonly;
  5216. }
  5217. static void
  5218. removerecordregions(int endoff)
  5219. {
  5220. if (ifslastp == NULL)
  5221. return;
  5222. if (ifsfirst.endoff > endoff) {
  5223. while (ifsfirst.next) {
  5224. struct ifsregion *ifsp;
  5225. INT_OFF;
  5226. ifsp = ifsfirst.next->next;
  5227. free(ifsfirst.next);
  5228. ifsfirst.next = ifsp;
  5229. INT_ON;
  5230. }
  5231. if (ifsfirst.begoff > endoff) {
  5232. ifslastp = NULL;
  5233. } else {
  5234. ifslastp = &ifsfirst;
  5235. ifsfirst.endoff = endoff;
  5236. }
  5237. return;
  5238. }
  5239. ifslastp = &ifsfirst;
  5240. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5241. ifslastp = ifslastp->next;
  5242. while (ifslastp->next) {
  5243. struct ifsregion *ifsp;
  5244. INT_OFF;
  5245. ifsp = ifslastp->next->next;
  5246. free(ifslastp->next);
  5247. ifslastp->next = ifsp;
  5248. INT_ON;
  5249. }
  5250. if (ifslastp->endoff > endoff)
  5251. ifslastp->endoff = endoff;
  5252. }
  5253. static char *
  5254. exptilde(char *startp, char *p, int flags)
  5255. {
  5256. unsigned char c;
  5257. char *name;
  5258. struct passwd *pw;
  5259. const char *home;
  5260. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5261. int startloc;
  5262. name = p + 1;
  5263. while ((c = *++p) != '\0') {
  5264. switch (c) {
  5265. case CTLESC:
  5266. return startp;
  5267. case CTLQUOTEMARK:
  5268. return startp;
  5269. case ':':
  5270. if (flags & EXP_VARTILDE)
  5271. goto done;
  5272. break;
  5273. case '/':
  5274. case CTLENDVAR:
  5275. goto done;
  5276. }
  5277. }
  5278. done:
  5279. *p = '\0';
  5280. if (*name == '\0') {
  5281. home = lookupvar("HOME");
  5282. } else {
  5283. pw = getpwnam(name);
  5284. if (pw == NULL)
  5285. goto lose;
  5286. home = pw->pw_dir;
  5287. }
  5288. if (!home || !*home)
  5289. goto lose;
  5290. *p = c;
  5291. startloc = expdest - (char *)stackblock();
  5292. strtodest(home, SQSYNTAX, quotes);
  5293. recordregion(startloc, expdest - (char *)stackblock(), 0);
  5294. return p;
  5295. lose:
  5296. *p = c;
  5297. return startp;
  5298. }
  5299. /*
  5300. * Execute a command inside back quotes. If it's a builtin command, we
  5301. * want to save its output in a block obtained from malloc. Otherwise
  5302. * we fork off a subprocess and get the output of the command via a pipe.
  5303. * Should be called with interrupts off.
  5304. */
  5305. struct backcmd { /* result of evalbackcmd */
  5306. int fd; /* file descriptor to read from */
  5307. int nleft; /* number of chars in buffer */
  5308. char *buf; /* buffer */
  5309. struct job *jp; /* job structure for command */
  5310. };
  5311. /* These forward decls are needed to use "eval" code for backticks handling: */
  5312. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5313. #define EV_EXIT 01 /* exit after evaluating tree */
  5314. static void evaltree(union node *, int);
  5315. static void FAST_FUNC
  5316. evalbackcmd(union node *n, struct backcmd *result)
  5317. {
  5318. int saveherefd;
  5319. result->fd = -1;
  5320. result->buf = NULL;
  5321. result->nleft = 0;
  5322. result->jp = NULL;
  5323. if (n == NULL)
  5324. goto out;
  5325. saveherefd = herefd;
  5326. herefd = -1;
  5327. {
  5328. int pip[2];
  5329. struct job *jp;
  5330. if (pipe(pip) < 0)
  5331. ash_msg_and_raise_error("pipe call failed");
  5332. jp = makejob(/*n,*/ 1);
  5333. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5334. FORCE_INT_ON;
  5335. close(pip[0]);
  5336. if (pip[1] != 1) {
  5337. /*close(1);*/
  5338. copyfd(pip[1], 1 | COPYFD_EXACT);
  5339. close(pip[1]);
  5340. }
  5341. eflag = 0;
  5342. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5343. /* NOTREACHED */
  5344. }
  5345. close(pip[1]);
  5346. result->fd = pip[0];
  5347. result->jp = jp;
  5348. }
  5349. herefd = saveherefd;
  5350. out:
  5351. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5352. result->fd, result->buf, result->nleft, result->jp));
  5353. }
  5354. /*
  5355. * Expand stuff in backwards quotes.
  5356. */
  5357. static void
  5358. expbackq(union node *cmd, int quoted, int quotes)
  5359. {
  5360. struct backcmd in;
  5361. int i;
  5362. char buf[128];
  5363. char *p;
  5364. char *dest;
  5365. int startloc;
  5366. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5367. struct stackmark smark;
  5368. INT_OFF;
  5369. setstackmark(&smark);
  5370. dest = expdest;
  5371. startloc = dest - (char *)stackblock();
  5372. grabstackstr(dest);
  5373. evalbackcmd(cmd, &in);
  5374. popstackmark(&smark);
  5375. p = in.buf;
  5376. i = in.nleft;
  5377. if (i == 0)
  5378. goto read;
  5379. for (;;) {
  5380. memtodest(p, i, syntax, quotes);
  5381. read:
  5382. if (in.fd < 0)
  5383. break;
  5384. i = nonblock_immune_read(in.fd, buf, sizeof(buf), /*loop_on_EINTR:*/ 1);
  5385. TRACE(("expbackq: read returns %d\n", i));
  5386. if (i <= 0)
  5387. break;
  5388. p = buf;
  5389. }
  5390. free(in.buf);
  5391. if (in.fd >= 0) {
  5392. close(in.fd);
  5393. back_exitstatus = waitforjob(in.jp);
  5394. }
  5395. INT_ON;
  5396. /* Eat all trailing newlines */
  5397. dest = expdest;
  5398. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5399. STUNPUTC(dest);
  5400. expdest = dest;
  5401. if (quoted == 0)
  5402. recordregion(startloc, dest - (char *)stackblock(), 0);
  5403. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5404. (int)((dest - (char *)stackblock()) - startloc),
  5405. (int)((dest - (char *)stackblock()) - startloc),
  5406. stackblock() + startloc));
  5407. }
  5408. #if ENABLE_SH_MATH_SUPPORT
  5409. /*
  5410. * Expand arithmetic expression. Backup to start of expression,
  5411. * evaluate, place result in (backed up) result, adjust string position.
  5412. */
  5413. static void
  5414. expari(int quotes)
  5415. {
  5416. char *p, *start;
  5417. int begoff;
  5418. int flag;
  5419. int len;
  5420. /* ifsfree(); */
  5421. /*
  5422. * This routine is slightly over-complicated for
  5423. * efficiency. Next we scan backwards looking for the
  5424. * start of arithmetic.
  5425. */
  5426. start = stackblock();
  5427. p = expdest - 1;
  5428. *p = '\0';
  5429. p--;
  5430. while (1) {
  5431. int esc;
  5432. while ((unsigned char)*p != CTLARI) {
  5433. p--;
  5434. #if DEBUG
  5435. if (p < start) {
  5436. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5437. }
  5438. #endif
  5439. }
  5440. esc = esclen(start, p);
  5441. if (!(esc % 2)) {
  5442. break;
  5443. }
  5444. p -= esc + 1;
  5445. }
  5446. begoff = p - start;
  5447. removerecordregions(begoff);
  5448. flag = p[1];
  5449. expdest = p;
  5450. if (quotes)
  5451. rmescapes(p + 2, 0);
  5452. len = cvtnum(ash_arith(p + 2));
  5453. if (flag != '"')
  5454. recordregion(begoff, begoff + len, 0);
  5455. }
  5456. #endif
  5457. /* argstr needs it */
  5458. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5459. /*
  5460. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5461. * characters to allow for further processing. Otherwise treat
  5462. * $@ like $* since no splitting will be performed.
  5463. *
  5464. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5465. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5466. * for correct expansion of "B=$A" word.
  5467. */
  5468. static void
  5469. argstr(char *p, int flags, struct strlist *var_str_list)
  5470. {
  5471. static const char spclchars[] ALIGN1 = {
  5472. '=',
  5473. ':',
  5474. CTLQUOTEMARK,
  5475. CTLENDVAR,
  5476. CTLESC,
  5477. CTLVAR,
  5478. CTLBACKQ,
  5479. CTLBACKQ | CTLQUOTE,
  5480. #if ENABLE_SH_MATH_SUPPORT
  5481. CTLENDARI,
  5482. #endif
  5483. '\0'
  5484. };
  5485. const char *reject = spclchars;
  5486. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
  5487. int breakall = flags & EXP_WORD;
  5488. int inquotes;
  5489. size_t length;
  5490. int startloc;
  5491. if (!(flags & EXP_VARTILDE)) {
  5492. reject += 2;
  5493. } else if (flags & EXP_VARTILDE2) {
  5494. reject++;
  5495. }
  5496. inquotes = 0;
  5497. length = 0;
  5498. if (flags & EXP_TILDE) {
  5499. char *q;
  5500. flags &= ~EXP_TILDE;
  5501. tilde:
  5502. q = p;
  5503. if ((unsigned char)*q == CTLESC && (flags & EXP_QWORD))
  5504. q++;
  5505. if (*q == '~')
  5506. p = exptilde(p, q, flags);
  5507. }
  5508. start:
  5509. startloc = expdest - (char *)stackblock();
  5510. for (;;) {
  5511. unsigned char c;
  5512. length += strcspn(p + length, reject);
  5513. c = p[length];
  5514. if (c) {
  5515. if (!(c & 0x80)
  5516. IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
  5517. ) {
  5518. /* c == '=' || c == ':' || c == CTLENDARI */
  5519. length++;
  5520. }
  5521. }
  5522. if (length > 0) {
  5523. int newloc;
  5524. expdest = stack_nputstr(p, length, expdest);
  5525. newloc = expdest - (char *)stackblock();
  5526. if (breakall && !inquotes && newloc > startloc) {
  5527. recordregion(startloc, newloc, 0);
  5528. }
  5529. startloc = newloc;
  5530. }
  5531. p += length + 1;
  5532. length = 0;
  5533. switch (c) {
  5534. case '\0':
  5535. goto breakloop;
  5536. case '=':
  5537. if (flags & EXP_VARTILDE2) {
  5538. p--;
  5539. continue;
  5540. }
  5541. flags |= EXP_VARTILDE2;
  5542. reject++;
  5543. /* fall through */
  5544. case ':':
  5545. /*
  5546. * sort of a hack - expand tildes in variable
  5547. * assignments (after the first '=' and after ':'s).
  5548. */
  5549. if (*--p == '~') {
  5550. goto tilde;
  5551. }
  5552. continue;
  5553. }
  5554. switch (c) {
  5555. case CTLENDVAR: /* ??? */
  5556. goto breakloop;
  5557. case CTLQUOTEMARK:
  5558. /* "$@" syntax adherence hack */
  5559. if (!inquotes
  5560. && memcmp(p, dolatstr, 4) == 0
  5561. && ( p[4] == (char)CTLQUOTEMARK
  5562. || (p[4] == (char)CTLENDVAR && p[5] == (char)CTLQUOTEMARK)
  5563. )
  5564. ) {
  5565. p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
  5566. goto start;
  5567. }
  5568. inquotes = !inquotes;
  5569. addquote:
  5570. if (quotes) {
  5571. p--;
  5572. length++;
  5573. startloc++;
  5574. }
  5575. break;
  5576. case CTLESC:
  5577. startloc++;
  5578. length++;
  5579. goto addquote;
  5580. case CTLVAR:
  5581. TRACE(("argstr: evalvar('%s')\n", p));
  5582. p = evalvar(p, flags, var_str_list);
  5583. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  5584. goto start;
  5585. case CTLBACKQ:
  5586. c = '\0';
  5587. case CTLBACKQ|CTLQUOTE:
  5588. expbackq(argbackq->n, c, quotes);
  5589. argbackq = argbackq->next;
  5590. goto start;
  5591. #if ENABLE_SH_MATH_SUPPORT
  5592. case CTLENDARI:
  5593. p--;
  5594. expari(quotes);
  5595. goto start;
  5596. #endif
  5597. }
  5598. }
  5599. breakloop: ;
  5600. }
  5601. static char *
  5602. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  5603. char *pattern, int quotes, int zero)
  5604. {
  5605. char *loc, *loc2;
  5606. char c;
  5607. loc = startp;
  5608. loc2 = rmesc;
  5609. do {
  5610. int match;
  5611. const char *s = loc2;
  5612. c = *loc2;
  5613. if (zero) {
  5614. *loc2 = '\0';
  5615. s = rmesc;
  5616. }
  5617. match = pmatch(pattern, s);
  5618. *loc2 = c;
  5619. if (match)
  5620. return loc;
  5621. if (quotes && (unsigned char)*loc == CTLESC)
  5622. loc++;
  5623. loc++;
  5624. loc2++;
  5625. } while (c);
  5626. return NULL;
  5627. }
  5628. static char *
  5629. scanright(char *startp, char *rmesc, char *rmescend,
  5630. char *pattern, int quotes, int match_at_start)
  5631. {
  5632. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5633. int try2optimize = match_at_start;
  5634. #endif
  5635. int esc = 0;
  5636. char *loc;
  5637. char *loc2;
  5638. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5639. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5640. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5641. * Logic:
  5642. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5643. * and on each iteration they go back two/one char until they reach the beginning.
  5644. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5645. */
  5646. /* TODO: document in what other circumstances we are called. */
  5647. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5648. int match;
  5649. char c = *loc2;
  5650. const char *s = loc2;
  5651. if (match_at_start) {
  5652. *loc2 = '\0';
  5653. s = rmesc;
  5654. }
  5655. match = pmatch(pattern, s);
  5656. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5657. *loc2 = c;
  5658. if (match)
  5659. return loc;
  5660. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5661. if (try2optimize) {
  5662. /* Maybe we can optimize this:
  5663. * if pattern ends with unescaped *, we can avoid checking
  5664. * shorter strings: if "foo*" doesnt match "raw_value_of_v",
  5665. * it wont match truncated "raw_value_of_" strings too.
  5666. */
  5667. unsigned plen = strlen(pattern);
  5668. /* Does it end with "*"? */
  5669. if (plen != 0 && pattern[--plen] == '*') {
  5670. /* "xxxx*" is not escaped */
  5671. /* "xxx\*" is escaped */
  5672. /* "xx\\*" is not escaped */
  5673. /* "x\\\*" is escaped */
  5674. int slashes = 0;
  5675. while (plen != 0 && pattern[--plen] == '\\')
  5676. slashes++;
  5677. if (!(slashes & 1))
  5678. break; /* ends with unescaped "*" */
  5679. }
  5680. try2optimize = 0;
  5681. }
  5682. #endif
  5683. loc--;
  5684. if (quotes) {
  5685. if (--esc < 0) {
  5686. esc = esclen(startp, loc);
  5687. }
  5688. if (esc % 2) {
  5689. esc--;
  5690. loc--;
  5691. }
  5692. }
  5693. }
  5694. return NULL;
  5695. }
  5696. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5697. static void
  5698. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5699. {
  5700. const char *msg;
  5701. const char *tail;
  5702. tail = nullstr;
  5703. msg = "parameter not set";
  5704. if (umsg) {
  5705. if ((unsigned char)*end == CTLENDVAR) {
  5706. if (varflags & VSNUL)
  5707. tail = " or null";
  5708. } else {
  5709. msg = umsg;
  5710. }
  5711. }
  5712. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  5713. }
  5714. #if ENABLE_ASH_BASH_COMPAT
  5715. static char *
  5716. parse_sub_pattern(char *arg, int varflags)
  5717. {
  5718. char *idx, *repl = NULL;
  5719. unsigned char c;
  5720. //char *org_arg = arg;
  5721. //bb_error_msg("arg:'%s' varflags:%x", arg, varflags);
  5722. idx = arg;
  5723. while (1) {
  5724. c = *arg;
  5725. if (!c)
  5726. break;
  5727. if (c == '/') {
  5728. /* Only the first '/' seen is our separator */
  5729. if (!repl) {
  5730. repl = idx + 1;
  5731. c = '\0';
  5732. }
  5733. }
  5734. *idx++ = c;
  5735. arg++;
  5736. /*
  5737. * Example: v='ab\c'; echo ${v/\\b/_\\_\z_}
  5738. * The result is a_\_z_c (not a\_\_z_c)!
  5739. *
  5740. * Enable debug prints in this function and you'll see:
  5741. * ash: arg:'\\b/_\\_z_' varflags:d
  5742. * ash: pattern:'\\b' repl:'_\_z_'
  5743. * That is, \\b is interpreted as \\b, but \\_ as \_!
  5744. * IOW: search pattern and replace string treat backslashes
  5745. * differently! That is the reason why we check repl below:
  5746. */
  5747. if (c == '\\' && *arg == '\\' && repl && !(varflags & VSQUOTE))
  5748. arg++; /* skip both '\', not just first one */
  5749. }
  5750. *idx = c; /* NUL */
  5751. //bb_error_msg("pattern:'%s' repl:'%s'", org_arg, repl);
  5752. return repl;
  5753. }
  5754. #endif /* ENABLE_ASH_BASH_COMPAT */
  5755. static const char *
  5756. subevalvar(char *p, char *varname, int strloc, int subtype,
  5757. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5758. {
  5759. struct nodelist *saveargbackq = argbackq;
  5760. char *startp;
  5761. char *loc;
  5762. char *rmesc, *rmescend;
  5763. char *str;
  5764. IF_ASH_BASH_COMPAT(const char *repl = NULL;)
  5765. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5766. int saveherefd = herefd;
  5767. int amount, resetloc;
  5768. IF_ASH_BASH_COMPAT(int workloc;)
  5769. int zero;
  5770. char *(*scan)(char*, char*, char*, char*, int, int);
  5771. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  5772. // p, varname, strloc, subtype, startloc, varflags, quotes);
  5773. herefd = -1;
  5774. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5775. var_str_list);
  5776. STPUTC('\0', expdest);
  5777. herefd = saveherefd;
  5778. argbackq = saveargbackq;
  5779. startp = (char *)stackblock() + startloc;
  5780. switch (subtype) {
  5781. case VSASSIGN:
  5782. setvar(varname, startp, 0);
  5783. amount = startp - expdest;
  5784. STADJUST(amount, expdest);
  5785. return startp;
  5786. case VSQUESTION:
  5787. varunset(p, varname, startp, varflags);
  5788. /* NOTREACHED */
  5789. #if ENABLE_ASH_BASH_COMPAT
  5790. case VSSUBSTR:
  5791. loc = str = stackblock() + strloc;
  5792. /* Read POS in ${var:POS:LEN} */
  5793. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5794. len = str - startp - 1;
  5795. /* *loc != '\0', guaranteed by parser */
  5796. if (quotes) {
  5797. char *ptr;
  5798. /* Adjust the length by the number of escapes */
  5799. for (ptr = startp; ptr < (str - 1); ptr++) {
  5800. if ((unsigned char)*ptr == CTLESC) {
  5801. len--;
  5802. ptr++;
  5803. }
  5804. }
  5805. }
  5806. orig_len = len;
  5807. if (*loc++ == ':') {
  5808. /* ${var::LEN} */
  5809. len = number(loc);
  5810. } else {
  5811. /* Skip POS in ${var:POS:LEN} */
  5812. len = orig_len;
  5813. while (*loc && *loc != ':') {
  5814. /* TODO?
  5815. * bash complains on: var=qwe; echo ${var:1a:123}
  5816. if (!isdigit(*loc))
  5817. ash_msg_and_raise_error(msg_illnum, str);
  5818. */
  5819. loc++;
  5820. }
  5821. if (*loc++ == ':') {
  5822. len = number(loc);
  5823. }
  5824. }
  5825. if (pos >= orig_len) {
  5826. pos = 0;
  5827. len = 0;
  5828. }
  5829. if (len > (orig_len - pos))
  5830. len = orig_len - pos;
  5831. for (str = startp; pos; str++, pos--) {
  5832. if (quotes && (unsigned char)*str == CTLESC)
  5833. str++;
  5834. }
  5835. for (loc = startp; len; len--) {
  5836. if (quotes && (unsigned char)*str == CTLESC)
  5837. *loc++ = *str++;
  5838. *loc++ = *str++;
  5839. }
  5840. *loc = '\0';
  5841. amount = loc - expdest;
  5842. STADJUST(amount, expdest);
  5843. return loc;
  5844. #endif
  5845. }
  5846. resetloc = expdest - (char *)stackblock();
  5847. /* We'll comeback here if we grow the stack while handling
  5848. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5849. * stack will need rebasing, and we'll need to remove our work
  5850. * areas each time
  5851. */
  5852. IF_ASH_BASH_COMPAT(restart:)
  5853. amount = expdest - ((char *)stackblock() + resetloc);
  5854. STADJUST(-amount, expdest);
  5855. startp = (char *)stackblock() + startloc;
  5856. rmesc = startp;
  5857. rmescend = (char *)stackblock() + strloc;
  5858. if (quotes) {
  5859. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5860. if (rmesc != startp) {
  5861. rmescend = expdest;
  5862. startp = (char *)stackblock() + startloc;
  5863. }
  5864. }
  5865. rmescend--;
  5866. str = (char *)stackblock() + strloc;
  5867. preglob(str, varflags & VSQUOTE, 0);
  5868. #if ENABLE_ASH_BASH_COMPAT
  5869. workloc = expdest - (char *)stackblock();
  5870. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5871. char *idx, *end;
  5872. if (!repl) {
  5873. repl = parse_sub_pattern(str, varflags);
  5874. //bb_error_msg("repl:'%s'", repl);
  5875. if (!repl)
  5876. repl = nullstr;
  5877. }
  5878. /* If there's no pattern to match, return the expansion unmolested */
  5879. if (str[0] == '\0')
  5880. return NULL;
  5881. len = 0;
  5882. idx = startp;
  5883. end = str - 1;
  5884. while (idx < end) {
  5885. try_to_match:
  5886. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5887. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  5888. if (!loc) {
  5889. /* No match, advance */
  5890. char *restart_detect = stackblock();
  5891. skip_matching:
  5892. STPUTC(*idx, expdest);
  5893. if (quotes && (unsigned char)*idx == CTLESC) {
  5894. idx++;
  5895. len++;
  5896. STPUTC(*idx, expdest);
  5897. }
  5898. if (stackblock() != restart_detect)
  5899. goto restart;
  5900. idx++;
  5901. len++;
  5902. rmesc++;
  5903. /* continue; - prone to quadratic behavior, smarter code: */
  5904. if (idx >= end)
  5905. break;
  5906. if (str[0] == '*') {
  5907. /* Pattern is "*foo". If "*foo" does not match "long_string",
  5908. * it would never match "ong_string" etc, no point in trying.
  5909. */
  5910. goto skip_matching;
  5911. }
  5912. goto try_to_match;
  5913. }
  5914. if (subtype == VSREPLACEALL) {
  5915. while (idx < loc) {
  5916. if (quotes && (unsigned char)*idx == CTLESC)
  5917. idx++;
  5918. idx++;
  5919. rmesc++;
  5920. }
  5921. } else {
  5922. idx = loc;
  5923. }
  5924. //bb_error_msg("repl:'%s'", repl);
  5925. for (loc = (char*)repl; *loc; loc++) {
  5926. char *restart_detect = stackblock();
  5927. if (quotes && *loc == '\\') {
  5928. STPUTC(CTLESC, expdest);
  5929. len++;
  5930. }
  5931. STPUTC(*loc, expdest);
  5932. if (stackblock() != restart_detect)
  5933. goto restart;
  5934. len++;
  5935. }
  5936. if (subtype == VSREPLACE) {
  5937. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  5938. while (*idx) {
  5939. char *restart_detect = stackblock();
  5940. STPUTC(*idx, expdest);
  5941. if (stackblock() != restart_detect)
  5942. goto restart;
  5943. len++;
  5944. idx++;
  5945. }
  5946. break;
  5947. }
  5948. }
  5949. /* We've put the replaced text into a buffer at workloc, now
  5950. * move it to the right place and adjust the stack.
  5951. */
  5952. STPUTC('\0', expdest);
  5953. startp = (char *)stackblock() + startloc;
  5954. memmove(startp, (char *)stackblock() + workloc, len + 1);
  5955. //bb_error_msg("startp:'%s'", startp);
  5956. amount = expdest - (startp + len);
  5957. STADJUST(-amount, expdest);
  5958. return startp;
  5959. }
  5960. #endif /* ENABLE_ASH_BASH_COMPAT */
  5961. subtype -= VSTRIMRIGHT;
  5962. #if DEBUG
  5963. if (subtype < 0 || subtype > 7)
  5964. abort();
  5965. #endif
  5966. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  5967. zero = subtype >> 1;
  5968. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5969. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5970. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5971. if (loc) {
  5972. if (zero) {
  5973. memmove(startp, loc, str - loc);
  5974. loc = startp + (str - loc) - 1;
  5975. }
  5976. *loc = '\0';
  5977. amount = loc - expdest;
  5978. STADJUST(amount, expdest);
  5979. }
  5980. return loc;
  5981. }
  5982. /*
  5983. * Add the value of a specialized variable to the stack string.
  5984. * name parameter (examples):
  5985. * ash -c 'echo $1' name:'1='
  5986. * ash -c 'echo $qwe' name:'qwe='
  5987. * ash -c 'echo $$' name:'$='
  5988. * ash -c 'echo ${$}' name:'$='
  5989. * ash -c 'echo ${$##q}' name:'$=q'
  5990. * ash -c 'echo ${#$}' name:'$='
  5991. * note: examples with bad shell syntax:
  5992. * ash -c 'echo ${#$1}' name:'$=1'
  5993. * ash -c 'echo ${#1#}' name:'1=#'
  5994. */
  5995. static NOINLINE ssize_t
  5996. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5997. {
  5998. const char *p;
  5999. int num;
  6000. int i;
  6001. int sepq = 0;
  6002. ssize_t len = 0;
  6003. int subtype = varflags & VSTYPE;
  6004. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  6005. int quoted = varflags & VSQUOTE;
  6006. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6007. switch (*name) {
  6008. case '$':
  6009. num = rootpid;
  6010. goto numvar;
  6011. case '?':
  6012. num = exitstatus;
  6013. goto numvar;
  6014. case '#':
  6015. num = shellparam.nparam;
  6016. goto numvar;
  6017. case '!':
  6018. num = backgndpid;
  6019. if (num == 0)
  6020. return -1;
  6021. numvar:
  6022. len = cvtnum(num);
  6023. goto check_1char_name;
  6024. case '-':
  6025. expdest = makestrspace(NOPTS, expdest);
  6026. for (i = NOPTS - 1; i >= 0; i--) {
  6027. if (optlist[i]) {
  6028. USTPUTC(optletters(i), expdest);
  6029. len++;
  6030. }
  6031. }
  6032. check_1char_name:
  6033. #if 0
  6034. /* handles cases similar to ${#$1} */
  6035. if (name[2] != '\0')
  6036. raise_error_syntax("bad substitution");
  6037. #endif
  6038. break;
  6039. case '@': {
  6040. char **ap;
  6041. int sep;
  6042. if (quoted && (flags & EXP_FULL)) {
  6043. /* note: this is not meant as PEOF value */
  6044. sep = 1 << CHAR_BIT;
  6045. goto param;
  6046. }
  6047. /* fall through */
  6048. case '*':
  6049. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  6050. i = SIT(sep, syntax);
  6051. if (quotes && (i == CCTL || i == CBACK))
  6052. sepq = 1;
  6053. param:
  6054. ap = shellparam.p;
  6055. if (!ap)
  6056. return -1;
  6057. while ((p = *ap++) != NULL) {
  6058. size_t partlen;
  6059. partlen = strlen(p);
  6060. len += partlen;
  6061. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  6062. memtodest(p, partlen, syntax, quotes);
  6063. if (*ap && sep) {
  6064. char *q;
  6065. len++;
  6066. if (subtype == VSPLUS || subtype == VSLENGTH) {
  6067. continue;
  6068. }
  6069. q = expdest;
  6070. if (sepq)
  6071. STPUTC(CTLESC, q);
  6072. /* note: may put NUL despite sep != 0
  6073. * (see sep = 1 << CHAR_BIT above) */
  6074. STPUTC(sep, q);
  6075. expdest = q;
  6076. }
  6077. }
  6078. return len;
  6079. } /* case '@' and '*' */
  6080. case '0':
  6081. case '1':
  6082. case '2':
  6083. case '3':
  6084. case '4':
  6085. case '5':
  6086. case '6':
  6087. case '7':
  6088. case '8':
  6089. case '9':
  6090. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6091. if (num < 0 || num > shellparam.nparam)
  6092. return -1;
  6093. p = num ? shellparam.p[num - 1] : arg0;
  6094. goto value;
  6095. default:
  6096. /* NB: name has form "VAR=..." */
  6097. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  6098. * which should be considered before we check variables. */
  6099. if (var_str_list) {
  6100. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  6101. p = NULL;
  6102. do {
  6103. char *str, *eq;
  6104. str = var_str_list->text;
  6105. eq = strchr(str, '=');
  6106. if (!eq) /* stop at first non-assignment */
  6107. break;
  6108. eq++;
  6109. if (name_len == (unsigned)(eq - str)
  6110. && strncmp(str, name, name_len) == 0
  6111. ) {
  6112. p = eq;
  6113. /* goto value; - WRONG! */
  6114. /* think "A=1 A=2 B=$A" */
  6115. }
  6116. var_str_list = var_str_list->next;
  6117. } while (var_str_list);
  6118. if (p)
  6119. goto value;
  6120. }
  6121. p = lookupvar(name);
  6122. value:
  6123. if (!p)
  6124. return -1;
  6125. len = strlen(p);
  6126. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  6127. memtodest(p, len, syntax, quotes);
  6128. return len;
  6129. }
  6130. if (subtype == VSPLUS || subtype == VSLENGTH)
  6131. STADJUST(-len, expdest);
  6132. return len;
  6133. }
  6134. /*
  6135. * Expand a variable, and return a pointer to the next character in the
  6136. * input string.
  6137. */
  6138. static char *
  6139. evalvar(char *p, int flags, struct strlist *var_str_list)
  6140. {
  6141. char varflags;
  6142. char subtype;
  6143. char quoted;
  6144. char easy;
  6145. char *var;
  6146. int patloc;
  6147. int startloc;
  6148. ssize_t varlen;
  6149. varflags = (unsigned char) *p++;
  6150. subtype = varflags & VSTYPE;
  6151. quoted = varflags & VSQUOTE;
  6152. var = p;
  6153. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6154. startloc = expdest - (char *)stackblock();
  6155. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6156. again:
  6157. varlen = varvalue(var, varflags, flags, var_str_list);
  6158. if (varflags & VSNUL)
  6159. varlen--;
  6160. if (subtype == VSPLUS) {
  6161. varlen = -1 - varlen;
  6162. goto vsplus;
  6163. }
  6164. if (subtype == VSMINUS) {
  6165. vsplus:
  6166. if (varlen < 0) {
  6167. argstr(
  6168. p,
  6169. flags | (quoted ? EXP_TILDE|EXP_QWORD : EXP_TILDE|EXP_WORD),
  6170. var_str_list
  6171. );
  6172. goto end;
  6173. }
  6174. if (easy)
  6175. goto record;
  6176. goto end;
  6177. }
  6178. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6179. if (varlen < 0) {
  6180. if (subevalvar(p, var, /* strloc: */ 0,
  6181. subtype, startloc, varflags,
  6182. /* quotes: */ 0,
  6183. var_str_list)
  6184. ) {
  6185. varflags &= ~VSNUL;
  6186. /*
  6187. * Remove any recorded regions beyond
  6188. * start of variable
  6189. */
  6190. removerecordregions(startloc);
  6191. goto again;
  6192. }
  6193. goto end;
  6194. }
  6195. if (easy)
  6196. goto record;
  6197. goto end;
  6198. }
  6199. if (varlen < 0 && uflag)
  6200. varunset(p, var, 0, 0);
  6201. if (subtype == VSLENGTH) {
  6202. cvtnum(varlen > 0 ? varlen : 0);
  6203. goto record;
  6204. }
  6205. if (subtype == VSNORMAL) {
  6206. if (easy)
  6207. goto record;
  6208. goto end;
  6209. }
  6210. #if DEBUG
  6211. switch (subtype) {
  6212. case VSTRIMLEFT:
  6213. case VSTRIMLEFTMAX:
  6214. case VSTRIMRIGHT:
  6215. case VSTRIMRIGHTMAX:
  6216. #if ENABLE_ASH_BASH_COMPAT
  6217. case VSSUBSTR:
  6218. case VSREPLACE:
  6219. case VSREPLACEALL:
  6220. #endif
  6221. break;
  6222. default:
  6223. abort();
  6224. }
  6225. #endif
  6226. if (varlen >= 0) {
  6227. /*
  6228. * Terminate the string and start recording the pattern
  6229. * right after it
  6230. */
  6231. STPUTC('\0', expdest);
  6232. patloc = expdest - (char *)stackblock();
  6233. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6234. startloc, varflags,
  6235. /* quotes: */ flags & (EXP_FULL | EXP_CASE | EXP_REDIR),
  6236. var_str_list)
  6237. ) {
  6238. int amount = expdest - (
  6239. (char *)stackblock() + patloc - 1
  6240. );
  6241. STADJUST(-amount, expdest);
  6242. }
  6243. /* Remove any recorded regions beyond start of variable */
  6244. removerecordregions(startloc);
  6245. record:
  6246. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6247. }
  6248. end:
  6249. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6250. int nesting = 1;
  6251. for (;;) {
  6252. unsigned char c = *p++;
  6253. if (c == CTLESC)
  6254. p++;
  6255. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  6256. if (varlen >= 0)
  6257. argbackq = argbackq->next;
  6258. } else if (c == CTLVAR) {
  6259. if ((*p++ & VSTYPE) != VSNORMAL)
  6260. nesting++;
  6261. } else if (c == CTLENDVAR) {
  6262. if (--nesting == 0)
  6263. break;
  6264. }
  6265. }
  6266. }
  6267. return p;
  6268. }
  6269. /*
  6270. * Break the argument string into pieces based upon IFS and add the
  6271. * strings to the argument list. The regions of the string to be
  6272. * searched for IFS characters have been stored by recordregion.
  6273. */
  6274. static void
  6275. ifsbreakup(char *string, struct arglist *arglist)
  6276. {
  6277. struct ifsregion *ifsp;
  6278. struct strlist *sp;
  6279. char *start;
  6280. char *p;
  6281. char *q;
  6282. const char *ifs, *realifs;
  6283. int ifsspc;
  6284. int nulonly;
  6285. start = string;
  6286. if (ifslastp != NULL) {
  6287. ifsspc = 0;
  6288. nulonly = 0;
  6289. realifs = ifsset() ? ifsval() : defifs;
  6290. ifsp = &ifsfirst;
  6291. do {
  6292. p = string + ifsp->begoff;
  6293. nulonly = ifsp->nulonly;
  6294. ifs = nulonly ? nullstr : realifs;
  6295. ifsspc = 0;
  6296. while (p < string + ifsp->endoff) {
  6297. q = p;
  6298. if ((unsigned char)*p == CTLESC)
  6299. p++;
  6300. if (!strchr(ifs, *p)) {
  6301. p++;
  6302. continue;
  6303. }
  6304. if (!nulonly)
  6305. ifsspc = (strchr(defifs, *p) != NULL);
  6306. /* Ignore IFS whitespace at start */
  6307. if (q == start && ifsspc) {
  6308. p++;
  6309. start = p;
  6310. continue;
  6311. }
  6312. *q = '\0';
  6313. sp = stzalloc(sizeof(*sp));
  6314. sp->text = start;
  6315. *arglist->lastp = sp;
  6316. arglist->lastp = &sp->next;
  6317. p++;
  6318. if (!nulonly) {
  6319. for (;;) {
  6320. if (p >= string + ifsp->endoff) {
  6321. break;
  6322. }
  6323. q = p;
  6324. if ((unsigned char)*p == CTLESC)
  6325. p++;
  6326. if (strchr(ifs, *p) == NULL) {
  6327. p = q;
  6328. break;
  6329. }
  6330. if (strchr(defifs, *p) == NULL) {
  6331. if (ifsspc) {
  6332. p++;
  6333. ifsspc = 0;
  6334. } else {
  6335. p = q;
  6336. break;
  6337. }
  6338. } else
  6339. p++;
  6340. }
  6341. }
  6342. start = p;
  6343. } /* while */
  6344. ifsp = ifsp->next;
  6345. } while (ifsp != NULL);
  6346. if (nulonly)
  6347. goto add;
  6348. }
  6349. if (!*start)
  6350. return;
  6351. add:
  6352. sp = stzalloc(sizeof(*sp));
  6353. sp->text = start;
  6354. *arglist->lastp = sp;
  6355. arglist->lastp = &sp->next;
  6356. }
  6357. static void
  6358. ifsfree(void)
  6359. {
  6360. struct ifsregion *p;
  6361. INT_OFF;
  6362. p = ifsfirst.next;
  6363. do {
  6364. struct ifsregion *ifsp;
  6365. ifsp = p->next;
  6366. free(p);
  6367. p = ifsp;
  6368. } while (p);
  6369. ifslastp = NULL;
  6370. ifsfirst.next = NULL;
  6371. INT_ON;
  6372. }
  6373. /*
  6374. * Add a file name to the list.
  6375. */
  6376. static void
  6377. addfname(const char *name)
  6378. {
  6379. struct strlist *sp;
  6380. sp = stzalloc(sizeof(*sp));
  6381. sp->text = ststrdup(name);
  6382. *exparg.lastp = sp;
  6383. exparg.lastp = &sp->next;
  6384. }
  6385. /*
  6386. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6387. */
  6388. static void
  6389. expmeta(char *expdir, char *enddir, char *name)
  6390. {
  6391. char *p;
  6392. const char *cp;
  6393. char *start;
  6394. char *endname;
  6395. int metaflag;
  6396. struct stat statb;
  6397. DIR *dirp;
  6398. struct dirent *dp;
  6399. int atend;
  6400. int matchdot;
  6401. metaflag = 0;
  6402. start = name;
  6403. for (p = name; *p; p++) {
  6404. if (*p == '*' || *p == '?')
  6405. metaflag = 1;
  6406. else if (*p == '[') {
  6407. char *q = p + 1;
  6408. if (*q == '!')
  6409. q++;
  6410. for (;;) {
  6411. if (*q == '\\')
  6412. q++;
  6413. if (*q == '/' || *q == '\0')
  6414. break;
  6415. if (*++q == ']') {
  6416. metaflag = 1;
  6417. break;
  6418. }
  6419. }
  6420. } else if (*p == '\\')
  6421. p++;
  6422. else if (*p == '/') {
  6423. if (metaflag)
  6424. goto out;
  6425. start = p + 1;
  6426. }
  6427. }
  6428. out:
  6429. if (metaflag == 0) { /* we've reached the end of the file name */
  6430. if (enddir != expdir)
  6431. metaflag++;
  6432. p = name;
  6433. do {
  6434. if (*p == '\\')
  6435. p++;
  6436. *enddir++ = *p;
  6437. } while (*p++);
  6438. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6439. addfname(expdir);
  6440. return;
  6441. }
  6442. endname = p;
  6443. if (name < start) {
  6444. p = name;
  6445. do {
  6446. if (*p == '\\')
  6447. p++;
  6448. *enddir++ = *p++;
  6449. } while (p < start);
  6450. }
  6451. if (enddir == expdir) {
  6452. cp = ".";
  6453. } else if (enddir == expdir + 1 && *expdir == '/') {
  6454. cp = "/";
  6455. } else {
  6456. cp = expdir;
  6457. enddir[-1] = '\0';
  6458. }
  6459. dirp = opendir(cp);
  6460. if (dirp == NULL)
  6461. return;
  6462. if (enddir != expdir)
  6463. enddir[-1] = '/';
  6464. if (*endname == 0) {
  6465. atend = 1;
  6466. } else {
  6467. atend = 0;
  6468. *endname++ = '\0';
  6469. }
  6470. matchdot = 0;
  6471. p = start;
  6472. if (*p == '\\')
  6473. p++;
  6474. if (*p == '.')
  6475. matchdot++;
  6476. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6477. if (dp->d_name[0] == '.' && !matchdot)
  6478. continue;
  6479. if (pmatch(start, dp->d_name)) {
  6480. if (atend) {
  6481. strcpy(enddir, dp->d_name);
  6482. addfname(expdir);
  6483. } else {
  6484. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6485. continue;
  6486. p[-1] = '/';
  6487. expmeta(expdir, p, endname);
  6488. }
  6489. }
  6490. }
  6491. closedir(dirp);
  6492. if (!atend)
  6493. endname[-1] = '/';
  6494. }
  6495. static struct strlist *
  6496. msort(struct strlist *list, int len)
  6497. {
  6498. struct strlist *p, *q = NULL;
  6499. struct strlist **lpp;
  6500. int half;
  6501. int n;
  6502. if (len <= 1)
  6503. return list;
  6504. half = len >> 1;
  6505. p = list;
  6506. for (n = half; --n >= 0;) {
  6507. q = p;
  6508. p = p->next;
  6509. }
  6510. q->next = NULL; /* terminate first half of list */
  6511. q = msort(list, half); /* sort first half of list */
  6512. p = msort(p, len - half); /* sort second half */
  6513. lpp = &list;
  6514. for (;;) {
  6515. #if ENABLE_LOCALE_SUPPORT
  6516. if (strcoll(p->text, q->text) < 0)
  6517. #else
  6518. if (strcmp(p->text, q->text) < 0)
  6519. #endif
  6520. {
  6521. *lpp = p;
  6522. lpp = &p->next;
  6523. p = *lpp;
  6524. if (p == NULL) {
  6525. *lpp = q;
  6526. break;
  6527. }
  6528. } else {
  6529. *lpp = q;
  6530. lpp = &q->next;
  6531. q = *lpp;
  6532. if (q == NULL) {
  6533. *lpp = p;
  6534. break;
  6535. }
  6536. }
  6537. }
  6538. return list;
  6539. }
  6540. /*
  6541. * Sort the results of file name expansion. It calculates the number of
  6542. * strings to sort and then calls msort (short for merge sort) to do the
  6543. * work.
  6544. */
  6545. static struct strlist *
  6546. expsort(struct strlist *str)
  6547. {
  6548. int len;
  6549. struct strlist *sp;
  6550. len = 0;
  6551. for (sp = str; sp; sp = sp->next)
  6552. len++;
  6553. return msort(str, len);
  6554. }
  6555. static void
  6556. expandmeta(struct strlist *str /*, int flag*/)
  6557. {
  6558. static const char metachars[] ALIGN1 = {
  6559. '*', '?', '[', 0
  6560. };
  6561. /* TODO - EXP_REDIR */
  6562. while (str) {
  6563. char *expdir;
  6564. struct strlist **savelastp;
  6565. struct strlist *sp;
  6566. char *p;
  6567. if (fflag)
  6568. goto nometa;
  6569. if (!strpbrk(str->text, metachars))
  6570. goto nometa;
  6571. savelastp = exparg.lastp;
  6572. INT_OFF;
  6573. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6574. {
  6575. int i = strlen(str->text);
  6576. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6577. }
  6578. expmeta(expdir, expdir, p);
  6579. free(expdir);
  6580. if (p != str->text)
  6581. free(p);
  6582. INT_ON;
  6583. if (exparg.lastp == savelastp) {
  6584. /*
  6585. * no matches
  6586. */
  6587. nometa:
  6588. *exparg.lastp = str;
  6589. rmescapes(str->text, 0);
  6590. exparg.lastp = &str->next;
  6591. } else {
  6592. *exparg.lastp = NULL;
  6593. *savelastp = sp = expsort(*savelastp);
  6594. while (sp->next != NULL)
  6595. sp = sp->next;
  6596. exparg.lastp = &sp->next;
  6597. }
  6598. str = str->next;
  6599. }
  6600. }
  6601. /*
  6602. * Perform variable substitution and command substitution on an argument,
  6603. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6604. * perform splitting and file name expansion. When arglist is NULL, perform
  6605. * here document expansion.
  6606. */
  6607. static void
  6608. expandarg(union node *arg, struct arglist *arglist, int flag)
  6609. {
  6610. struct strlist *sp;
  6611. char *p;
  6612. argbackq = arg->narg.backquote;
  6613. STARTSTACKSTR(expdest);
  6614. ifsfirst.next = NULL;
  6615. ifslastp = NULL;
  6616. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  6617. argstr(arg->narg.text, flag,
  6618. /* var_str_list: */ arglist ? arglist->list : NULL);
  6619. p = _STPUTC('\0', expdest);
  6620. expdest = p - 1;
  6621. if (arglist == NULL) {
  6622. return; /* here document expanded */
  6623. }
  6624. p = grabstackstr(p);
  6625. TRACE(("expandarg: p:'%s'\n", p));
  6626. exparg.lastp = &exparg.list;
  6627. /*
  6628. * TODO - EXP_REDIR
  6629. */
  6630. if (flag & EXP_FULL) {
  6631. ifsbreakup(p, &exparg);
  6632. *exparg.lastp = NULL;
  6633. exparg.lastp = &exparg.list;
  6634. expandmeta(exparg.list /*, flag*/);
  6635. } else {
  6636. if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
  6637. rmescapes(p, 0);
  6638. TRACE(("expandarg: rmescapes:'%s'\n", p));
  6639. }
  6640. sp = stzalloc(sizeof(*sp));
  6641. sp->text = p;
  6642. *exparg.lastp = sp;
  6643. exparg.lastp = &sp->next;
  6644. }
  6645. if (ifsfirst.next)
  6646. ifsfree();
  6647. *exparg.lastp = NULL;
  6648. if (exparg.list) {
  6649. *arglist->lastp = exparg.list;
  6650. arglist->lastp = exparg.lastp;
  6651. }
  6652. }
  6653. /*
  6654. * Expand shell variables and backquotes inside a here document.
  6655. */
  6656. static void
  6657. expandhere(union node *arg, int fd)
  6658. {
  6659. herefd = fd;
  6660. expandarg(arg, (struct arglist *)NULL, 0);
  6661. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6662. }
  6663. /*
  6664. * Returns true if the pattern matches the string.
  6665. */
  6666. static int
  6667. patmatch(char *pattern, const char *string)
  6668. {
  6669. return pmatch(preglob(pattern, 0, 0), string);
  6670. }
  6671. /*
  6672. * See if a pattern matches in a case statement.
  6673. */
  6674. static int
  6675. casematch(union node *pattern, char *val)
  6676. {
  6677. struct stackmark smark;
  6678. int result;
  6679. setstackmark(&smark);
  6680. argbackq = pattern->narg.backquote;
  6681. STARTSTACKSTR(expdest);
  6682. ifslastp = NULL;
  6683. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6684. /* var_str_list: */ NULL);
  6685. STACKSTRNUL(expdest);
  6686. result = patmatch(stackblock(), val);
  6687. popstackmark(&smark);
  6688. return result;
  6689. }
  6690. /* ============ find_command */
  6691. struct builtincmd {
  6692. const char *name;
  6693. int (*builtin)(int, char **) FAST_FUNC;
  6694. /* unsigned flags; */
  6695. };
  6696. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6697. /* "regular" builtins always take precedence over commands,
  6698. * regardless of PATH=....%builtin... position */
  6699. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6700. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6701. struct cmdentry {
  6702. smallint cmdtype; /* CMDxxx */
  6703. union param {
  6704. int index;
  6705. /* index >= 0 for commands without path (slashes) */
  6706. /* (TODO: what exactly does the value mean? PATH position?) */
  6707. /* index == -1 for commands with slashes */
  6708. /* index == (-2 - applet_no) for NOFORK applets */
  6709. const struct builtincmd *cmd;
  6710. struct funcnode *func;
  6711. } u;
  6712. };
  6713. /* values of cmdtype */
  6714. #define CMDUNKNOWN -1 /* no entry in table for command */
  6715. #define CMDNORMAL 0 /* command is an executable program */
  6716. #define CMDFUNCTION 1 /* command is a shell function */
  6717. #define CMDBUILTIN 2 /* command is a shell builtin */
  6718. /* action to find_command() */
  6719. #define DO_ERR 0x01 /* prints errors */
  6720. #define DO_ABS 0x02 /* checks absolute paths */
  6721. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6722. #define DO_ALTPATH 0x08 /* using alternate path */
  6723. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6724. static void find_command(char *, struct cmdentry *, int, const char *);
  6725. /* ============ Hashing commands */
  6726. /*
  6727. * When commands are first encountered, they are entered in a hash table.
  6728. * This ensures that a full path search will not have to be done for them
  6729. * on each invocation.
  6730. *
  6731. * We should investigate converting to a linear search, even though that
  6732. * would make the command name "hash" a misnomer.
  6733. */
  6734. struct tblentry {
  6735. struct tblentry *next; /* next entry in hash chain */
  6736. union param param; /* definition of builtin function */
  6737. smallint cmdtype; /* CMDxxx */
  6738. char rehash; /* if set, cd done since entry created */
  6739. char cmdname[1]; /* name of command */
  6740. };
  6741. static struct tblentry **cmdtable;
  6742. #define INIT_G_cmdtable() do { \
  6743. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6744. } while (0)
  6745. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6746. static void
  6747. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6748. {
  6749. #if ENABLE_FEATURE_SH_STANDALONE
  6750. if (applet_no >= 0) {
  6751. if (APPLET_IS_NOEXEC(applet_no)) {
  6752. clearenv();
  6753. while (*envp)
  6754. putenv(*envp++);
  6755. run_applet_no_and_exit(applet_no, argv);
  6756. }
  6757. /* re-exec ourselves with the new arguments */
  6758. execve(bb_busybox_exec_path, argv, envp);
  6759. /* If they called chroot or otherwise made the binary no longer
  6760. * executable, fall through */
  6761. }
  6762. #endif
  6763. repeat:
  6764. #ifdef SYSV
  6765. do {
  6766. execve(cmd, argv, envp);
  6767. } while (errno == EINTR);
  6768. #else
  6769. execve(cmd, argv, envp);
  6770. #endif
  6771. if (cmd == (char*) bb_busybox_exec_path) {
  6772. /* We already visited ENOEXEC branch below, don't do it again */
  6773. //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
  6774. free(argv);
  6775. return;
  6776. }
  6777. if (errno == ENOEXEC) {
  6778. /* Run "cmd" as a shell script:
  6779. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  6780. * "If the execve() function fails with ENOEXEC, the shell
  6781. * shall execute a command equivalent to having a shell invoked
  6782. * with the command name as its first operand,
  6783. * with any remaining arguments passed to the new shell"
  6784. *
  6785. * That is, do not use $SHELL, user's shell, or /bin/sh;
  6786. * just call ourselves.
  6787. *
  6788. * Note that bash reads ~80 chars of the file, and if it sees
  6789. * a zero byte before it sees newline, it doesn't try to
  6790. * interpret it, but fails with "cannot execute binary file"
  6791. * message and exit code 126. For one, this prevents attempts
  6792. * to interpret foreign ELF binaries as shell scripts.
  6793. */
  6794. char **ap;
  6795. char **new;
  6796. for (ap = argv; *ap; ap++)
  6797. continue;
  6798. new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
  6799. new[0] = (char*) "ash";
  6800. new[1] = cmd;
  6801. ap = new + 2;
  6802. while ((*ap++ = *++argv) != NULL)
  6803. continue;
  6804. cmd = (char*) bb_busybox_exec_path;
  6805. argv = new;
  6806. goto repeat;
  6807. }
  6808. }
  6809. /*
  6810. * Exec a program. Never returns. If you change this routine, you may
  6811. * have to change the find_command routine as well.
  6812. */
  6813. static void shellexec(char **, const char *, int) NORETURN;
  6814. static void
  6815. shellexec(char **argv, const char *path, int idx)
  6816. {
  6817. char *cmdname;
  6818. int e;
  6819. char **envp;
  6820. int exerrno;
  6821. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  6822. clearredir(/*drop:*/ 1);
  6823. envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
  6824. if (strchr(argv[0], '/') != NULL
  6825. #if ENABLE_FEATURE_SH_STANDALONE
  6826. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6827. #endif
  6828. ) {
  6829. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6830. if (applet_no >= 0) {
  6831. /* We tried execing ourself, but it didn't work.
  6832. * Maybe /proc/self/exe doesn't exist?
  6833. * Try $PATH search.
  6834. */
  6835. goto try_PATH;
  6836. }
  6837. e = errno;
  6838. } else {
  6839. try_PATH:
  6840. e = ENOENT;
  6841. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6842. if (--idx < 0 && pathopt == NULL) {
  6843. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6844. if (errno != ENOENT && errno != ENOTDIR)
  6845. e = errno;
  6846. }
  6847. stunalloc(cmdname);
  6848. }
  6849. }
  6850. /* Map to POSIX errors */
  6851. switch (e) {
  6852. case EACCES:
  6853. exerrno = 126;
  6854. break;
  6855. case ENOENT:
  6856. exerrno = 127;
  6857. break;
  6858. default:
  6859. exerrno = 2;
  6860. break;
  6861. }
  6862. exitstatus = exerrno;
  6863. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6864. argv[0], e, suppress_int));
  6865. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6866. /* NOTREACHED */
  6867. }
  6868. static void
  6869. printentry(struct tblentry *cmdp)
  6870. {
  6871. int idx;
  6872. const char *path;
  6873. char *name;
  6874. idx = cmdp->param.index;
  6875. path = pathval();
  6876. do {
  6877. name = path_advance(&path, cmdp->cmdname);
  6878. stunalloc(name);
  6879. } while (--idx >= 0);
  6880. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6881. }
  6882. /*
  6883. * Clear out command entries. The argument specifies the first entry in
  6884. * PATH which has changed.
  6885. */
  6886. static void
  6887. clearcmdentry(int firstchange)
  6888. {
  6889. struct tblentry **tblp;
  6890. struct tblentry **pp;
  6891. struct tblentry *cmdp;
  6892. INT_OFF;
  6893. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6894. pp = tblp;
  6895. while ((cmdp = *pp) != NULL) {
  6896. if ((cmdp->cmdtype == CMDNORMAL &&
  6897. cmdp->param.index >= firstchange)
  6898. || (cmdp->cmdtype == CMDBUILTIN &&
  6899. builtinloc >= firstchange)
  6900. ) {
  6901. *pp = cmdp->next;
  6902. free(cmdp);
  6903. } else {
  6904. pp = &cmdp->next;
  6905. }
  6906. }
  6907. }
  6908. INT_ON;
  6909. }
  6910. /*
  6911. * Locate a command in the command hash table. If "add" is nonzero,
  6912. * add the command to the table if it is not already present. The
  6913. * variable "lastcmdentry" is set to point to the address of the link
  6914. * pointing to the entry, so that delete_cmd_entry can delete the
  6915. * entry.
  6916. *
  6917. * Interrupts must be off if called with add != 0.
  6918. */
  6919. static struct tblentry **lastcmdentry;
  6920. static struct tblentry *
  6921. cmdlookup(const char *name, int add)
  6922. {
  6923. unsigned int hashval;
  6924. const char *p;
  6925. struct tblentry *cmdp;
  6926. struct tblentry **pp;
  6927. p = name;
  6928. hashval = (unsigned char)*p << 4;
  6929. while (*p)
  6930. hashval += (unsigned char)*p++;
  6931. hashval &= 0x7FFF;
  6932. pp = &cmdtable[hashval % CMDTABLESIZE];
  6933. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6934. if (strcmp(cmdp->cmdname, name) == 0)
  6935. break;
  6936. pp = &cmdp->next;
  6937. }
  6938. if (add && cmdp == NULL) {
  6939. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6940. + strlen(name)
  6941. /* + 1 - already done because
  6942. * tblentry::cmdname is char[1] */);
  6943. /*cmdp->next = NULL; - ckzalloc did it */
  6944. cmdp->cmdtype = CMDUNKNOWN;
  6945. strcpy(cmdp->cmdname, name);
  6946. }
  6947. lastcmdentry = pp;
  6948. return cmdp;
  6949. }
  6950. /*
  6951. * Delete the command entry returned on the last lookup.
  6952. */
  6953. static void
  6954. delete_cmd_entry(void)
  6955. {
  6956. struct tblentry *cmdp;
  6957. INT_OFF;
  6958. cmdp = *lastcmdentry;
  6959. *lastcmdentry = cmdp->next;
  6960. if (cmdp->cmdtype == CMDFUNCTION)
  6961. freefunc(cmdp->param.func);
  6962. free(cmdp);
  6963. INT_ON;
  6964. }
  6965. /*
  6966. * Add a new command entry, replacing any existing command entry for
  6967. * the same name - except special builtins.
  6968. */
  6969. static void
  6970. addcmdentry(char *name, struct cmdentry *entry)
  6971. {
  6972. struct tblentry *cmdp;
  6973. cmdp = cmdlookup(name, 1);
  6974. if (cmdp->cmdtype == CMDFUNCTION) {
  6975. freefunc(cmdp->param.func);
  6976. }
  6977. cmdp->cmdtype = entry->cmdtype;
  6978. cmdp->param = entry->u;
  6979. cmdp->rehash = 0;
  6980. }
  6981. static int FAST_FUNC
  6982. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6983. {
  6984. struct tblentry **pp;
  6985. struct tblentry *cmdp;
  6986. int c;
  6987. struct cmdentry entry;
  6988. char *name;
  6989. if (nextopt("r") != '\0') {
  6990. clearcmdentry(0);
  6991. return 0;
  6992. }
  6993. if (*argptr == NULL) {
  6994. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6995. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6996. if (cmdp->cmdtype == CMDNORMAL)
  6997. printentry(cmdp);
  6998. }
  6999. }
  7000. return 0;
  7001. }
  7002. c = 0;
  7003. while ((name = *argptr) != NULL) {
  7004. cmdp = cmdlookup(name, 0);
  7005. if (cmdp != NULL
  7006. && (cmdp->cmdtype == CMDNORMAL
  7007. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7008. ) {
  7009. delete_cmd_entry();
  7010. }
  7011. find_command(name, &entry, DO_ERR, pathval());
  7012. if (entry.cmdtype == CMDUNKNOWN)
  7013. c = 1;
  7014. argptr++;
  7015. }
  7016. return c;
  7017. }
  7018. /*
  7019. * Called when a cd is done. Marks all commands so the next time they
  7020. * are executed they will be rehashed.
  7021. */
  7022. static void
  7023. hashcd(void)
  7024. {
  7025. struct tblentry **pp;
  7026. struct tblentry *cmdp;
  7027. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7028. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7029. if (cmdp->cmdtype == CMDNORMAL
  7030. || (cmdp->cmdtype == CMDBUILTIN
  7031. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7032. && builtinloc > 0)
  7033. ) {
  7034. cmdp->rehash = 1;
  7035. }
  7036. }
  7037. }
  7038. }
  7039. /*
  7040. * Fix command hash table when PATH changed.
  7041. * Called before PATH is changed. The argument is the new value of PATH;
  7042. * pathval() still returns the old value at this point.
  7043. * Called with interrupts off.
  7044. */
  7045. static void FAST_FUNC
  7046. changepath(const char *new)
  7047. {
  7048. const char *old;
  7049. int firstchange;
  7050. int idx;
  7051. int idx_bltin;
  7052. old = pathval();
  7053. firstchange = 9999; /* assume no change */
  7054. idx = 0;
  7055. idx_bltin = -1;
  7056. for (;;) {
  7057. if (*old != *new) {
  7058. firstchange = idx;
  7059. if ((*old == '\0' && *new == ':')
  7060. || (*old == ':' && *new == '\0')
  7061. ) {
  7062. firstchange++;
  7063. }
  7064. old = new; /* ignore subsequent differences */
  7065. }
  7066. if (*new == '\0')
  7067. break;
  7068. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7069. idx_bltin = idx;
  7070. if (*new == ':')
  7071. idx++;
  7072. new++;
  7073. old++;
  7074. }
  7075. if (builtinloc < 0 && idx_bltin >= 0)
  7076. builtinloc = idx_bltin; /* zap builtins */
  7077. if (builtinloc >= 0 && idx_bltin < 0)
  7078. firstchange = 0;
  7079. clearcmdentry(firstchange);
  7080. builtinloc = idx_bltin;
  7081. }
  7082. #define TEOF 0
  7083. #define TNL 1
  7084. #define TREDIR 2
  7085. #define TWORD 3
  7086. #define TSEMI 4
  7087. #define TBACKGND 5
  7088. #define TAND 6
  7089. #define TOR 7
  7090. #define TPIPE 8
  7091. #define TLP 9
  7092. #define TRP 10
  7093. #define TENDCASE 11
  7094. #define TENDBQUOTE 12
  7095. #define TNOT 13
  7096. #define TCASE 14
  7097. #define TDO 15
  7098. #define TDONE 16
  7099. #define TELIF 17
  7100. #define TELSE 18
  7101. #define TESAC 19
  7102. #define TFI 20
  7103. #define TFOR 21
  7104. #define TIF 22
  7105. #define TIN 23
  7106. #define TTHEN 24
  7107. #define TUNTIL 25
  7108. #define TWHILE 26
  7109. #define TBEGIN 27
  7110. #define TEND 28
  7111. typedef smallint token_id_t;
  7112. /* first char is indicating which tokens mark the end of a list */
  7113. static const char *const tokname_array[] = {
  7114. "\1end of file",
  7115. "\0newline",
  7116. "\0redirection",
  7117. "\0word",
  7118. "\0;",
  7119. "\0&",
  7120. "\0&&",
  7121. "\0||",
  7122. "\0|",
  7123. "\0(",
  7124. "\1)",
  7125. "\1;;",
  7126. "\1`",
  7127. #define KWDOFFSET 13
  7128. /* the following are keywords */
  7129. "\0!",
  7130. "\0case",
  7131. "\1do",
  7132. "\1done",
  7133. "\1elif",
  7134. "\1else",
  7135. "\1esac",
  7136. "\1fi",
  7137. "\0for",
  7138. "\0if",
  7139. "\0in",
  7140. "\1then",
  7141. "\0until",
  7142. "\0while",
  7143. "\0{",
  7144. "\1}",
  7145. };
  7146. /* Wrapper around strcmp for qsort/bsearch/... */
  7147. static int
  7148. pstrcmp(const void *a, const void *b)
  7149. {
  7150. return strcmp((char*) a, (*(char**) b) + 1);
  7151. }
  7152. static const char *const *
  7153. findkwd(const char *s)
  7154. {
  7155. return bsearch(s, tokname_array + KWDOFFSET,
  7156. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7157. sizeof(tokname_array[0]), pstrcmp);
  7158. }
  7159. /*
  7160. * Locate and print what a word is...
  7161. */
  7162. static int
  7163. describe_command(char *command, int describe_command_verbose)
  7164. {
  7165. struct cmdentry entry;
  7166. struct tblentry *cmdp;
  7167. #if ENABLE_ASH_ALIAS
  7168. const struct alias *ap;
  7169. #endif
  7170. const char *path = pathval();
  7171. if (describe_command_verbose) {
  7172. out1str(command);
  7173. }
  7174. /* First look at the keywords */
  7175. if (findkwd(command)) {
  7176. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7177. goto out;
  7178. }
  7179. #if ENABLE_ASH_ALIAS
  7180. /* Then look at the aliases */
  7181. ap = lookupalias(command, 0);
  7182. if (ap != NULL) {
  7183. if (!describe_command_verbose) {
  7184. out1str("alias ");
  7185. printalias(ap);
  7186. return 0;
  7187. }
  7188. out1fmt(" is an alias for %s", ap->val);
  7189. goto out;
  7190. }
  7191. #endif
  7192. /* Then check if it is a tracked alias */
  7193. cmdp = cmdlookup(command, 0);
  7194. if (cmdp != NULL) {
  7195. entry.cmdtype = cmdp->cmdtype;
  7196. entry.u = cmdp->param;
  7197. } else {
  7198. /* Finally use brute force */
  7199. find_command(command, &entry, DO_ABS, path);
  7200. }
  7201. switch (entry.cmdtype) {
  7202. case CMDNORMAL: {
  7203. int j = entry.u.index;
  7204. char *p;
  7205. if (j < 0) {
  7206. p = command;
  7207. } else {
  7208. do {
  7209. p = path_advance(&path, command);
  7210. stunalloc(p);
  7211. } while (--j >= 0);
  7212. }
  7213. if (describe_command_verbose) {
  7214. out1fmt(" is%s %s",
  7215. (cmdp ? " a tracked alias for" : nullstr), p
  7216. );
  7217. } else {
  7218. out1str(p);
  7219. }
  7220. break;
  7221. }
  7222. case CMDFUNCTION:
  7223. if (describe_command_verbose) {
  7224. out1str(" is a shell function");
  7225. } else {
  7226. out1str(command);
  7227. }
  7228. break;
  7229. case CMDBUILTIN:
  7230. if (describe_command_verbose) {
  7231. out1fmt(" is a %sshell builtin",
  7232. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7233. "special " : nullstr
  7234. );
  7235. } else {
  7236. out1str(command);
  7237. }
  7238. break;
  7239. default:
  7240. if (describe_command_verbose) {
  7241. out1str(": not found\n");
  7242. }
  7243. return 127;
  7244. }
  7245. out:
  7246. out1str("\n");
  7247. return 0;
  7248. }
  7249. static int FAST_FUNC
  7250. typecmd(int argc UNUSED_PARAM, char **argv)
  7251. {
  7252. int i = 1;
  7253. int err = 0;
  7254. int verbose = 1;
  7255. /* type -p ... ? (we don't bother checking for 'p') */
  7256. if (argv[1] && argv[1][0] == '-') {
  7257. i++;
  7258. verbose = 0;
  7259. }
  7260. while (argv[i]) {
  7261. err |= describe_command(argv[i++], verbose);
  7262. }
  7263. return err;
  7264. }
  7265. #if ENABLE_ASH_CMDCMD
  7266. static int FAST_FUNC
  7267. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7268. {
  7269. int c;
  7270. enum {
  7271. VERIFY_BRIEF = 1,
  7272. VERIFY_VERBOSE = 2,
  7273. } verify = 0;
  7274. while ((c = nextopt("pvV")) != '\0')
  7275. if (c == 'V')
  7276. verify |= VERIFY_VERBOSE;
  7277. else if (c == 'v')
  7278. verify |= VERIFY_BRIEF;
  7279. #if DEBUG
  7280. else if (c != 'p')
  7281. abort();
  7282. #endif
  7283. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7284. if (verify && (*argptr != NULL)) {
  7285. return describe_command(*argptr, verify - VERIFY_BRIEF);
  7286. }
  7287. return 0;
  7288. }
  7289. #endif
  7290. /* ============ eval.c */
  7291. static int funcblocksize; /* size of structures in function */
  7292. static int funcstringsize; /* size of strings in node */
  7293. static void *funcblock; /* block to allocate function from */
  7294. static char *funcstring; /* block to allocate strings from */
  7295. /* flags in argument to evaltree */
  7296. #define EV_EXIT 01 /* exit after evaluating tree */
  7297. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7298. #define EV_BACKCMD 04 /* command executing within back quotes */
  7299. static const uint8_t nodesize[N_NUMBER] = {
  7300. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7301. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7302. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7303. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7304. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7305. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7306. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7307. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7308. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7309. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7310. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7311. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7312. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7313. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7314. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7315. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7316. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7317. #if ENABLE_ASH_BASH_COMPAT
  7318. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7319. #endif
  7320. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7321. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7322. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7323. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7324. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7325. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7326. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7327. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7328. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7329. };
  7330. static void calcsize(union node *n);
  7331. static void
  7332. sizenodelist(struct nodelist *lp)
  7333. {
  7334. while (lp) {
  7335. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7336. calcsize(lp->n);
  7337. lp = lp->next;
  7338. }
  7339. }
  7340. static void
  7341. calcsize(union node *n)
  7342. {
  7343. if (n == NULL)
  7344. return;
  7345. funcblocksize += nodesize[n->type];
  7346. switch (n->type) {
  7347. case NCMD:
  7348. calcsize(n->ncmd.redirect);
  7349. calcsize(n->ncmd.args);
  7350. calcsize(n->ncmd.assign);
  7351. break;
  7352. case NPIPE:
  7353. sizenodelist(n->npipe.cmdlist);
  7354. break;
  7355. case NREDIR:
  7356. case NBACKGND:
  7357. case NSUBSHELL:
  7358. calcsize(n->nredir.redirect);
  7359. calcsize(n->nredir.n);
  7360. break;
  7361. case NAND:
  7362. case NOR:
  7363. case NSEMI:
  7364. case NWHILE:
  7365. case NUNTIL:
  7366. calcsize(n->nbinary.ch2);
  7367. calcsize(n->nbinary.ch1);
  7368. break;
  7369. case NIF:
  7370. calcsize(n->nif.elsepart);
  7371. calcsize(n->nif.ifpart);
  7372. calcsize(n->nif.test);
  7373. break;
  7374. case NFOR:
  7375. funcstringsize += strlen(n->nfor.var) + 1;
  7376. calcsize(n->nfor.body);
  7377. calcsize(n->nfor.args);
  7378. break;
  7379. case NCASE:
  7380. calcsize(n->ncase.cases);
  7381. calcsize(n->ncase.expr);
  7382. break;
  7383. case NCLIST:
  7384. calcsize(n->nclist.body);
  7385. calcsize(n->nclist.pattern);
  7386. calcsize(n->nclist.next);
  7387. break;
  7388. case NDEFUN:
  7389. case NARG:
  7390. sizenodelist(n->narg.backquote);
  7391. funcstringsize += strlen(n->narg.text) + 1;
  7392. calcsize(n->narg.next);
  7393. break;
  7394. case NTO:
  7395. #if ENABLE_ASH_BASH_COMPAT
  7396. case NTO2:
  7397. #endif
  7398. case NCLOBBER:
  7399. case NFROM:
  7400. case NFROMTO:
  7401. case NAPPEND:
  7402. calcsize(n->nfile.fname);
  7403. calcsize(n->nfile.next);
  7404. break;
  7405. case NTOFD:
  7406. case NFROMFD:
  7407. calcsize(n->ndup.vname);
  7408. calcsize(n->ndup.next);
  7409. break;
  7410. case NHERE:
  7411. case NXHERE:
  7412. calcsize(n->nhere.doc);
  7413. calcsize(n->nhere.next);
  7414. break;
  7415. case NNOT:
  7416. calcsize(n->nnot.com);
  7417. break;
  7418. };
  7419. }
  7420. static char *
  7421. nodeckstrdup(char *s)
  7422. {
  7423. char *rtn = funcstring;
  7424. strcpy(funcstring, s);
  7425. funcstring += strlen(s) + 1;
  7426. return rtn;
  7427. }
  7428. static union node *copynode(union node *);
  7429. static struct nodelist *
  7430. copynodelist(struct nodelist *lp)
  7431. {
  7432. struct nodelist *start;
  7433. struct nodelist **lpp;
  7434. lpp = &start;
  7435. while (lp) {
  7436. *lpp = funcblock;
  7437. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7438. (*lpp)->n = copynode(lp->n);
  7439. lp = lp->next;
  7440. lpp = &(*lpp)->next;
  7441. }
  7442. *lpp = NULL;
  7443. return start;
  7444. }
  7445. static union node *
  7446. copynode(union node *n)
  7447. {
  7448. union node *new;
  7449. if (n == NULL)
  7450. return NULL;
  7451. new = funcblock;
  7452. funcblock = (char *) funcblock + nodesize[n->type];
  7453. switch (n->type) {
  7454. case NCMD:
  7455. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7456. new->ncmd.args = copynode(n->ncmd.args);
  7457. new->ncmd.assign = copynode(n->ncmd.assign);
  7458. break;
  7459. case NPIPE:
  7460. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7461. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7462. break;
  7463. case NREDIR:
  7464. case NBACKGND:
  7465. case NSUBSHELL:
  7466. new->nredir.redirect = copynode(n->nredir.redirect);
  7467. new->nredir.n = copynode(n->nredir.n);
  7468. break;
  7469. case NAND:
  7470. case NOR:
  7471. case NSEMI:
  7472. case NWHILE:
  7473. case NUNTIL:
  7474. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7475. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7476. break;
  7477. case NIF:
  7478. new->nif.elsepart = copynode(n->nif.elsepart);
  7479. new->nif.ifpart = copynode(n->nif.ifpart);
  7480. new->nif.test = copynode(n->nif.test);
  7481. break;
  7482. case NFOR:
  7483. new->nfor.var = nodeckstrdup(n->nfor.var);
  7484. new->nfor.body = copynode(n->nfor.body);
  7485. new->nfor.args = copynode(n->nfor.args);
  7486. break;
  7487. case NCASE:
  7488. new->ncase.cases = copynode(n->ncase.cases);
  7489. new->ncase.expr = copynode(n->ncase.expr);
  7490. break;
  7491. case NCLIST:
  7492. new->nclist.body = copynode(n->nclist.body);
  7493. new->nclist.pattern = copynode(n->nclist.pattern);
  7494. new->nclist.next = copynode(n->nclist.next);
  7495. break;
  7496. case NDEFUN:
  7497. case NARG:
  7498. new->narg.backquote = copynodelist(n->narg.backquote);
  7499. new->narg.text = nodeckstrdup(n->narg.text);
  7500. new->narg.next = copynode(n->narg.next);
  7501. break;
  7502. case NTO:
  7503. #if ENABLE_ASH_BASH_COMPAT
  7504. case NTO2:
  7505. #endif
  7506. case NCLOBBER:
  7507. case NFROM:
  7508. case NFROMTO:
  7509. case NAPPEND:
  7510. new->nfile.fname = copynode(n->nfile.fname);
  7511. new->nfile.fd = n->nfile.fd;
  7512. new->nfile.next = copynode(n->nfile.next);
  7513. break;
  7514. case NTOFD:
  7515. case NFROMFD:
  7516. new->ndup.vname = copynode(n->ndup.vname);
  7517. new->ndup.dupfd = n->ndup.dupfd;
  7518. new->ndup.fd = n->ndup.fd;
  7519. new->ndup.next = copynode(n->ndup.next);
  7520. break;
  7521. case NHERE:
  7522. case NXHERE:
  7523. new->nhere.doc = copynode(n->nhere.doc);
  7524. new->nhere.fd = n->nhere.fd;
  7525. new->nhere.next = copynode(n->nhere.next);
  7526. break;
  7527. case NNOT:
  7528. new->nnot.com = copynode(n->nnot.com);
  7529. break;
  7530. };
  7531. new->type = n->type;
  7532. return new;
  7533. }
  7534. /*
  7535. * Make a copy of a parse tree.
  7536. */
  7537. static struct funcnode *
  7538. copyfunc(union node *n)
  7539. {
  7540. struct funcnode *f;
  7541. size_t blocksize;
  7542. funcblocksize = offsetof(struct funcnode, n);
  7543. funcstringsize = 0;
  7544. calcsize(n);
  7545. blocksize = funcblocksize;
  7546. f = ckmalloc(blocksize + funcstringsize);
  7547. funcblock = (char *) f + offsetof(struct funcnode, n);
  7548. funcstring = (char *) f + blocksize;
  7549. copynode(n);
  7550. f->count = 0;
  7551. return f;
  7552. }
  7553. /*
  7554. * Define a shell function.
  7555. */
  7556. static void
  7557. defun(char *name, union node *func)
  7558. {
  7559. struct cmdentry entry;
  7560. INT_OFF;
  7561. entry.cmdtype = CMDFUNCTION;
  7562. entry.u.func = copyfunc(func);
  7563. addcmdentry(name, &entry);
  7564. INT_ON;
  7565. }
  7566. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7567. #define SKIPBREAK (1 << 0)
  7568. #define SKIPCONT (1 << 1)
  7569. #define SKIPFUNC (1 << 2)
  7570. #define SKIPFILE (1 << 3)
  7571. #define SKIPEVAL (1 << 4)
  7572. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7573. static int skipcount; /* number of levels to skip */
  7574. static int funcnest; /* depth of function calls */
  7575. static int loopnest; /* current loop nesting level */
  7576. /* Forward decl way out to parsing code - dotrap needs it */
  7577. static int evalstring(char *s, int mask);
  7578. /* Called to execute a trap.
  7579. * Single callsite - at the end of evaltree().
  7580. * If we return non-zero, evaltree raises EXEXIT exception.
  7581. *
  7582. * Perhaps we should avoid entering new trap handlers
  7583. * while we are executing a trap handler. [is it a TODO?]
  7584. */
  7585. static int
  7586. dotrap(void)
  7587. {
  7588. uint8_t *g;
  7589. int sig;
  7590. uint8_t savestatus;
  7591. savestatus = exitstatus;
  7592. pending_sig = 0;
  7593. xbarrier();
  7594. TRACE(("dotrap entered\n"));
  7595. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7596. int want_exexit;
  7597. char *t;
  7598. if (*g == 0)
  7599. continue;
  7600. t = trap[sig];
  7601. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7602. * don't upset it by resetting gotsig[SIGINT-1] */
  7603. if (sig == SIGINT && !t)
  7604. continue;
  7605. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7606. *g = 0;
  7607. if (!t)
  7608. continue;
  7609. want_exexit = evalstring(t, SKIPEVAL);
  7610. exitstatus = savestatus;
  7611. if (want_exexit) {
  7612. TRACE(("dotrap returns %d\n", want_exexit));
  7613. return want_exexit;
  7614. }
  7615. }
  7616. TRACE(("dotrap returns 0\n"));
  7617. return 0;
  7618. }
  7619. /* forward declarations - evaluation is fairly recursive business... */
  7620. static void evalloop(union node *, int);
  7621. static void evalfor(union node *, int);
  7622. static void evalcase(union node *, int);
  7623. static void evalsubshell(union node *, int);
  7624. static void expredir(union node *);
  7625. static void evalpipe(union node *, int);
  7626. static void evalcommand(union node *, int);
  7627. static int evalbltin(const struct builtincmd *, int, char **);
  7628. static void prehash(union node *);
  7629. /*
  7630. * Evaluate a parse tree. The value is left in the global variable
  7631. * exitstatus.
  7632. */
  7633. static void
  7634. evaltree(union node *n, int flags)
  7635. {
  7636. struct jmploc *volatile savehandler = exception_handler;
  7637. struct jmploc jmploc;
  7638. int checkexit = 0;
  7639. void (*evalfn)(union node *, int);
  7640. int status;
  7641. int int_level;
  7642. SAVE_INT(int_level);
  7643. if (n == NULL) {
  7644. TRACE(("evaltree(NULL) called\n"));
  7645. goto out1;
  7646. }
  7647. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7648. exception_handler = &jmploc;
  7649. {
  7650. int err = setjmp(jmploc.loc);
  7651. if (err) {
  7652. /* if it was a signal, check for trap handlers */
  7653. if (exception_type == EXSIG) {
  7654. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7655. exception_type, err));
  7656. goto out;
  7657. }
  7658. /* continue on the way out */
  7659. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7660. exception_type, err));
  7661. exception_handler = savehandler;
  7662. longjmp(exception_handler->loc, err);
  7663. }
  7664. }
  7665. switch (n->type) {
  7666. default:
  7667. #if DEBUG
  7668. out1fmt("Node type = %d\n", n->type);
  7669. fflush_all();
  7670. break;
  7671. #endif
  7672. case NNOT:
  7673. evaltree(n->nnot.com, EV_TESTED);
  7674. status = !exitstatus;
  7675. goto setstatus;
  7676. case NREDIR:
  7677. expredir(n->nredir.redirect);
  7678. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7679. if (!status) {
  7680. evaltree(n->nredir.n, flags & EV_TESTED);
  7681. status = exitstatus;
  7682. }
  7683. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7684. goto setstatus;
  7685. case NCMD:
  7686. evalfn = evalcommand;
  7687. checkexit:
  7688. if (eflag && !(flags & EV_TESTED))
  7689. checkexit = ~0;
  7690. goto calleval;
  7691. case NFOR:
  7692. evalfn = evalfor;
  7693. goto calleval;
  7694. case NWHILE:
  7695. case NUNTIL:
  7696. evalfn = evalloop;
  7697. goto calleval;
  7698. case NSUBSHELL:
  7699. case NBACKGND:
  7700. evalfn = evalsubshell;
  7701. goto calleval;
  7702. case NPIPE:
  7703. evalfn = evalpipe;
  7704. goto checkexit;
  7705. case NCASE:
  7706. evalfn = evalcase;
  7707. goto calleval;
  7708. case NAND:
  7709. case NOR:
  7710. case NSEMI: {
  7711. #if NAND + 1 != NOR
  7712. #error NAND + 1 != NOR
  7713. #endif
  7714. #if NOR + 1 != NSEMI
  7715. #error NOR + 1 != NSEMI
  7716. #endif
  7717. unsigned is_or = n->type - NAND;
  7718. evaltree(
  7719. n->nbinary.ch1,
  7720. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7721. );
  7722. if (!exitstatus == is_or)
  7723. break;
  7724. if (!evalskip) {
  7725. n = n->nbinary.ch2;
  7726. evaln:
  7727. evalfn = evaltree;
  7728. calleval:
  7729. evalfn(n, flags);
  7730. break;
  7731. }
  7732. break;
  7733. }
  7734. case NIF:
  7735. evaltree(n->nif.test, EV_TESTED);
  7736. if (evalskip)
  7737. break;
  7738. if (exitstatus == 0) {
  7739. n = n->nif.ifpart;
  7740. goto evaln;
  7741. }
  7742. if (n->nif.elsepart) {
  7743. n = n->nif.elsepart;
  7744. goto evaln;
  7745. }
  7746. goto success;
  7747. case NDEFUN:
  7748. defun(n->narg.text, n->narg.next);
  7749. success:
  7750. status = 0;
  7751. setstatus:
  7752. exitstatus = status;
  7753. break;
  7754. }
  7755. out:
  7756. exception_handler = savehandler;
  7757. out1:
  7758. /* Order of checks below is important:
  7759. * signal handlers trigger before exit caused by "set -e".
  7760. */
  7761. if (pending_sig && dotrap())
  7762. goto exexit;
  7763. if (checkexit & exitstatus)
  7764. evalskip |= SKIPEVAL;
  7765. if (flags & EV_EXIT) {
  7766. exexit:
  7767. raise_exception(EXEXIT);
  7768. }
  7769. RESTORE_INT(int_level);
  7770. TRACE(("leaving evaltree (no interrupts)\n"));
  7771. }
  7772. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7773. static
  7774. #endif
  7775. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7776. static void
  7777. evalloop(union node *n, int flags)
  7778. {
  7779. int status;
  7780. loopnest++;
  7781. status = 0;
  7782. flags &= EV_TESTED;
  7783. for (;;) {
  7784. int i;
  7785. evaltree(n->nbinary.ch1, EV_TESTED);
  7786. if (evalskip) {
  7787. skipping:
  7788. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7789. evalskip = 0;
  7790. continue;
  7791. }
  7792. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7793. evalskip = 0;
  7794. break;
  7795. }
  7796. i = exitstatus;
  7797. if (n->type != NWHILE)
  7798. i = !i;
  7799. if (i != 0)
  7800. break;
  7801. evaltree(n->nbinary.ch2, flags);
  7802. status = exitstatus;
  7803. if (evalskip)
  7804. goto skipping;
  7805. }
  7806. loopnest--;
  7807. exitstatus = status;
  7808. }
  7809. static void
  7810. evalfor(union node *n, int flags)
  7811. {
  7812. struct arglist arglist;
  7813. union node *argp;
  7814. struct strlist *sp;
  7815. struct stackmark smark;
  7816. setstackmark(&smark);
  7817. arglist.list = NULL;
  7818. arglist.lastp = &arglist.list;
  7819. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7820. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7821. /* XXX */
  7822. if (evalskip)
  7823. goto out;
  7824. }
  7825. *arglist.lastp = NULL;
  7826. exitstatus = 0;
  7827. loopnest++;
  7828. flags &= EV_TESTED;
  7829. for (sp = arglist.list; sp; sp = sp->next) {
  7830. setvar(n->nfor.var, sp->text, 0);
  7831. evaltree(n->nfor.body, flags);
  7832. if (evalskip) {
  7833. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7834. evalskip = 0;
  7835. continue;
  7836. }
  7837. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7838. evalskip = 0;
  7839. break;
  7840. }
  7841. }
  7842. loopnest--;
  7843. out:
  7844. popstackmark(&smark);
  7845. }
  7846. static void
  7847. evalcase(union node *n, int flags)
  7848. {
  7849. union node *cp;
  7850. union node *patp;
  7851. struct arglist arglist;
  7852. struct stackmark smark;
  7853. setstackmark(&smark);
  7854. arglist.list = NULL;
  7855. arglist.lastp = &arglist.list;
  7856. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7857. exitstatus = 0;
  7858. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7859. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7860. if (casematch(patp, arglist.list->text)) {
  7861. if (evalskip == 0) {
  7862. evaltree(cp->nclist.body, flags);
  7863. }
  7864. goto out;
  7865. }
  7866. }
  7867. }
  7868. out:
  7869. popstackmark(&smark);
  7870. }
  7871. /*
  7872. * Kick off a subshell to evaluate a tree.
  7873. */
  7874. static void
  7875. evalsubshell(union node *n, int flags)
  7876. {
  7877. struct job *jp;
  7878. int backgnd = (n->type == NBACKGND);
  7879. int status;
  7880. expredir(n->nredir.redirect);
  7881. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  7882. goto nofork;
  7883. INT_OFF;
  7884. jp = makejob(/*n,*/ 1);
  7885. if (forkshell(jp, n, backgnd) == 0) {
  7886. /* child */
  7887. INT_ON;
  7888. flags |= EV_EXIT;
  7889. if (backgnd)
  7890. flags &= ~EV_TESTED;
  7891. nofork:
  7892. redirect(n->nredir.redirect, 0);
  7893. evaltreenr(n->nredir.n, flags);
  7894. /* never returns */
  7895. }
  7896. status = 0;
  7897. if (!backgnd)
  7898. status = waitforjob(jp);
  7899. exitstatus = status;
  7900. INT_ON;
  7901. }
  7902. /*
  7903. * Compute the names of the files in a redirection list.
  7904. */
  7905. static void fixredir(union node *, const char *, int);
  7906. static void
  7907. expredir(union node *n)
  7908. {
  7909. union node *redir;
  7910. for (redir = n; redir; redir = redir->nfile.next) {
  7911. struct arglist fn;
  7912. fn.list = NULL;
  7913. fn.lastp = &fn.list;
  7914. switch (redir->type) {
  7915. case NFROMTO:
  7916. case NFROM:
  7917. case NTO:
  7918. #if ENABLE_ASH_BASH_COMPAT
  7919. case NTO2:
  7920. #endif
  7921. case NCLOBBER:
  7922. case NAPPEND:
  7923. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7924. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  7925. #if ENABLE_ASH_BASH_COMPAT
  7926. store_expfname:
  7927. #endif
  7928. #if 0
  7929. // By the design of stack allocator, the loop of this kind:
  7930. // while true; do while true; do break; done </dev/null; done
  7931. // will look like a memory leak: ash plans to free expfname's
  7932. // of "/dev/null" as soon as it finishes running the loop
  7933. // (in this case, never).
  7934. // This "fix" is wrong:
  7935. if (redir->nfile.expfname)
  7936. stunalloc(redir->nfile.expfname);
  7937. // It results in corrupted state of stacked allocations.
  7938. #endif
  7939. redir->nfile.expfname = fn.list->text;
  7940. break;
  7941. case NFROMFD:
  7942. case NTOFD: /* >& */
  7943. if (redir->ndup.vname) {
  7944. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7945. if (fn.list == NULL)
  7946. ash_msg_and_raise_error("redir error");
  7947. #if ENABLE_ASH_BASH_COMPAT
  7948. //FIXME: we used expandarg with different args!
  7949. if (!isdigit_str9(fn.list->text)) {
  7950. /* >&file, not >&fd */
  7951. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7952. ash_msg_and_raise_error("redir error");
  7953. redir->type = NTO2;
  7954. goto store_expfname;
  7955. }
  7956. #endif
  7957. fixredir(redir, fn.list->text, 1);
  7958. }
  7959. break;
  7960. }
  7961. }
  7962. }
  7963. /*
  7964. * Evaluate a pipeline. All the processes in the pipeline are children
  7965. * of the process creating the pipeline. (This differs from some versions
  7966. * of the shell, which make the last process in a pipeline the parent
  7967. * of all the rest.)
  7968. */
  7969. static void
  7970. evalpipe(union node *n, int flags)
  7971. {
  7972. struct job *jp;
  7973. struct nodelist *lp;
  7974. int pipelen;
  7975. int prevfd;
  7976. int pip[2];
  7977. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7978. pipelen = 0;
  7979. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7980. pipelen++;
  7981. flags |= EV_EXIT;
  7982. INT_OFF;
  7983. jp = makejob(/*n,*/ pipelen);
  7984. prevfd = -1;
  7985. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7986. prehash(lp->n);
  7987. pip[1] = -1;
  7988. if (lp->next) {
  7989. if (pipe(pip) < 0) {
  7990. close(prevfd);
  7991. ash_msg_and_raise_error("pipe call failed");
  7992. }
  7993. }
  7994. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7995. INT_ON;
  7996. if (pip[1] >= 0) {
  7997. close(pip[0]);
  7998. }
  7999. if (prevfd > 0) {
  8000. dup2(prevfd, 0);
  8001. close(prevfd);
  8002. }
  8003. if (pip[1] > 1) {
  8004. dup2(pip[1], 1);
  8005. close(pip[1]);
  8006. }
  8007. evaltreenr(lp->n, flags);
  8008. /* never returns */
  8009. }
  8010. if (prevfd >= 0)
  8011. close(prevfd);
  8012. prevfd = pip[0];
  8013. /* Don't want to trigger debugging */
  8014. if (pip[1] != -1)
  8015. close(pip[1]);
  8016. }
  8017. if (n->npipe.pipe_backgnd == 0) {
  8018. exitstatus = waitforjob(jp);
  8019. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  8020. }
  8021. INT_ON;
  8022. }
  8023. /*
  8024. * Controls whether the shell is interactive or not.
  8025. */
  8026. static void
  8027. setinteractive(int on)
  8028. {
  8029. static smallint is_interactive;
  8030. if (++on == is_interactive)
  8031. return;
  8032. is_interactive = on;
  8033. setsignal(SIGINT);
  8034. setsignal(SIGQUIT);
  8035. setsignal(SIGTERM);
  8036. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8037. if (is_interactive > 1) {
  8038. /* Looks like they want an interactive shell */
  8039. static smallint did_banner;
  8040. if (!did_banner) {
  8041. /* note: ash and hush share this string */
  8042. out1fmt("\n\n%s %s\n"
  8043. "Enter 'help' for a list of built-in commands."
  8044. "\n\n",
  8045. bb_banner,
  8046. "built-in shell (ash)"
  8047. );
  8048. did_banner = 1;
  8049. }
  8050. }
  8051. #endif
  8052. }
  8053. static void
  8054. optschanged(void)
  8055. {
  8056. #if DEBUG
  8057. opentrace();
  8058. #endif
  8059. setinteractive(iflag);
  8060. setjobctl(mflag);
  8061. #if ENABLE_FEATURE_EDITING_VI
  8062. if (viflag)
  8063. line_input_state->flags |= VI_MODE;
  8064. else
  8065. line_input_state->flags &= ~VI_MODE;
  8066. #else
  8067. viflag = 0; /* forcibly keep the option off */
  8068. #endif
  8069. }
  8070. static struct localvar *localvars;
  8071. /*
  8072. * Called after a function returns.
  8073. * Interrupts must be off.
  8074. */
  8075. static void
  8076. poplocalvars(void)
  8077. {
  8078. struct localvar *lvp;
  8079. struct var *vp;
  8080. while ((lvp = localvars) != NULL) {
  8081. localvars = lvp->next;
  8082. vp = lvp->vp;
  8083. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8084. if (vp == NULL) { /* $- saved */
  8085. memcpy(optlist, lvp->text, sizeof(optlist));
  8086. free((char*)lvp->text);
  8087. optschanged();
  8088. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  8089. unsetvar(vp->var_text);
  8090. } else {
  8091. if (vp->var_func)
  8092. vp->var_func(var_end(lvp->text));
  8093. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8094. free((char*)vp->var_text);
  8095. vp->flags = lvp->flags;
  8096. vp->var_text = lvp->text;
  8097. }
  8098. free(lvp);
  8099. }
  8100. }
  8101. static int
  8102. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8103. {
  8104. volatile struct shparam saveparam;
  8105. struct localvar *volatile savelocalvars;
  8106. struct jmploc *volatile savehandler;
  8107. struct jmploc jmploc;
  8108. int e;
  8109. saveparam = shellparam;
  8110. savelocalvars = localvars;
  8111. e = setjmp(jmploc.loc);
  8112. if (e) {
  8113. goto funcdone;
  8114. }
  8115. INT_OFF;
  8116. savehandler = exception_handler;
  8117. exception_handler = &jmploc;
  8118. localvars = NULL;
  8119. shellparam.malloced = 0;
  8120. func->count++;
  8121. funcnest++;
  8122. INT_ON;
  8123. shellparam.nparam = argc - 1;
  8124. shellparam.p = argv + 1;
  8125. #if ENABLE_ASH_GETOPTS
  8126. shellparam.optind = 1;
  8127. shellparam.optoff = -1;
  8128. #endif
  8129. evaltree(&func->n, flags & EV_TESTED);
  8130. funcdone:
  8131. INT_OFF;
  8132. funcnest--;
  8133. freefunc(func);
  8134. poplocalvars();
  8135. localvars = savelocalvars;
  8136. freeparam(&shellparam);
  8137. shellparam = saveparam;
  8138. exception_handler = savehandler;
  8139. INT_ON;
  8140. evalskip &= ~SKIPFUNC;
  8141. return e;
  8142. }
  8143. #if ENABLE_ASH_CMDCMD
  8144. static char **
  8145. parse_command_args(char **argv, const char **path)
  8146. {
  8147. char *cp, c;
  8148. for (;;) {
  8149. cp = *++argv;
  8150. if (!cp)
  8151. return 0;
  8152. if (*cp++ != '-')
  8153. break;
  8154. c = *cp++;
  8155. if (!c)
  8156. break;
  8157. if (c == '-' && !*cp) {
  8158. argv++;
  8159. break;
  8160. }
  8161. do {
  8162. switch (c) {
  8163. case 'p':
  8164. *path = bb_default_path;
  8165. break;
  8166. default:
  8167. /* run 'typecmd' for other options */
  8168. return 0;
  8169. }
  8170. c = *cp++;
  8171. } while (c);
  8172. }
  8173. return argv;
  8174. }
  8175. #endif
  8176. /*
  8177. * Make a variable a local variable. When a variable is made local, it's
  8178. * value and flags are saved in a localvar structure. The saved values
  8179. * will be restored when the shell function returns. We handle the name
  8180. * "-" as a special case.
  8181. */
  8182. static void
  8183. mklocal(char *name)
  8184. {
  8185. struct localvar *lvp;
  8186. struct var **vpp;
  8187. struct var *vp;
  8188. INT_OFF;
  8189. lvp = ckzalloc(sizeof(struct localvar));
  8190. if (LONE_DASH(name)) {
  8191. char *p;
  8192. p = ckmalloc(sizeof(optlist));
  8193. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8194. vp = NULL;
  8195. } else {
  8196. char *eq;
  8197. vpp = hashvar(name);
  8198. vp = *findvar(vpp, name);
  8199. eq = strchr(name, '=');
  8200. if (vp == NULL) {
  8201. if (eq)
  8202. setvareq(name, VSTRFIXED);
  8203. else
  8204. setvar(name, NULL, VSTRFIXED);
  8205. vp = *vpp; /* the new variable */
  8206. lvp->flags = VUNSET;
  8207. } else {
  8208. lvp->text = vp->var_text;
  8209. lvp->flags = vp->flags;
  8210. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8211. if (eq)
  8212. setvareq(name, 0);
  8213. }
  8214. }
  8215. lvp->vp = vp;
  8216. lvp->next = localvars;
  8217. localvars = lvp;
  8218. INT_ON;
  8219. }
  8220. /*
  8221. * The "local" command.
  8222. */
  8223. static int FAST_FUNC
  8224. localcmd(int argc UNUSED_PARAM, char **argv)
  8225. {
  8226. char *name;
  8227. argv = argptr;
  8228. while ((name = *argv++) != NULL) {
  8229. mklocal(name);
  8230. }
  8231. return 0;
  8232. }
  8233. static int FAST_FUNC
  8234. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8235. {
  8236. return 1;
  8237. }
  8238. static int FAST_FUNC
  8239. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8240. {
  8241. return 0;
  8242. }
  8243. static int FAST_FUNC
  8244. execcmd(int argc UNUSED_PARAM, char **argv)
  8245. {
  8246. if (argv[1]) {
  8247. iflag = 0; /* exit on error */
  8248. mflag = 0;
  8249. optschanged();
  8250. shellexec(argv + 1, pathval(), 0);
  8251. }
  8252. return 0;
  8253. }
  8254. /*
  8255. * The return command.
  8256. */
  8257. static int FAST_FUNC
  8258. returncmd(int argc UNUSED_PARAM, char **argv)
  8259. {
  8260. /*
  8261. * If called outside a function, do what ksh does;
  8262. * skip the rest of the file.
  8263. */
  8264. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8265. return argv[1] ? number(argv[1]) : exitstatus;
  8266. }
  8267. /* Forward declarations for builtintab[] */
  8268. static int breakcmd(int, char **) FAST_FUNC;
  8269. static int dotcmd(int, char **) FAST_FUNC;
  8270. static int evalcmd(int, char **) FAST_FUNC;
  8271. static int exitcmd(int, char **) FAST_FUNC;
  8272. static int exportcmd(int, char **) FAST_FUNC;
  8273. #if ENABLE_ASH_GETOPTS
  8274. static int getoptscmd(int, char **) FAST_FUNC;
  8275. #endif
  8276. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8277. static int helpcmd(int, char **) FAST_FUNC;
  8278. #endif
  8279. #if ENABLE_SH_MATH_SUPPORT
  8280. static int letcmd(int, char **) FAST_FUNC;
  8281. #endif
  8282. static int readcmd(int, char **) FAST_FUNC;
  8283. static int setcmd(int, char **) FAST_FUNC;
  8284. static int shiftcmd(int, char **) FAST_FUNC;
  8285. static int timescmd(int, char **) FAST_FUNC;
  8286. static int trapcmd(int, char **) FAST_FUNC;
  8287. static int umaskcmd(int, char **) FAST_FUNC;
  8288. static int unsetcmd(int, char **) FAST_FUNC;
  8289. static int ulimitcmd(int, char **) FAST_FUNC;
  8290. #define BUILTIN_NOSPEC "0"
  8291. #define BUILTIN_SPECIAL "1"
  8292. #define BUILTIN_REGULAR "2"
  8293. #define BUILTIN_SPEC_REG "3"
  8294. #define BUILTIN_ASSIGN "4"
  8295. #define BUILTIN_SPEC_ASSG "5"
  8296. #define BUILTIN_REG_ASSG "6"
  8297. #define BUILTIN_SPEC_REG_ASSG "7"
  8298. /* Stubs for calling non-FAST_FUNC's */
  8299. #if ENABLE_ASH_BUILTIN_ECHO
  8300. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8301. #endif
  8302. #if ENABLE_ASH_BUILTIN_PRINTF
  8303. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8304. #endif
  8305. #if ENABLE_ASH_BUILTIN_TEST
  8306. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8307. #endif
  8308. /* Keep these in proper order since it is searched via bsearch() */
  8309. static const struct builtincmd builtintab[] = {
  8310. { BUILTIN_SPEC_REG "." , dotcmd },
  8311. { BUILTIN_SPEC_REG ":" , truecmd },
  8312. #if ENABLE_ASH_BUILTIN_TEST
  8313. { BUILTIN_REGULAR "[" , testcmd },
  8314. #if ENABLE_ASH_BASH_COMPAT
  8315. { BUILTIN_REGULAR "[[" , testcmd },
  8316. #endif
  8317. #endif
  8318. #if ENABLE_ASH_ALIAS
  8319. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8320. #endif
  8321. #if JOBS
  8322. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8323. #endif
  8324. { BUILTIN_SPEC_REG "break" , breakcmd },
  8325. { BUILTIN_REGULAR "cd" , cdcmd },
  8326. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8327. #if ENABLE_ASH_CMDCMD
  8328. { BUILTIN_REGULAR "command" , commandcmd },
  8329. #endif
  8330. { BUILTIN_SPEC_REG "continue", breakcmd },
  8331. #if ENABLE_ASH_BUILTIN_ECHO
  8332. { BUILTIN_REGULAR "echo" , echocmd },
  8333. #endif
  8334. { BUILTIN_SPEC_REG "eval" , evalcmd },
  8335. { BUILTIN_SPEC_REG "exec" , execcmd },
  8336. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8337. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8338. { BUILTIN_REGULAR "false" , falsecmd },
  8339. #if JOBS
  8340. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8341. #endif
  8342. #if ENABLE_ASH_GETOPTS
  8343. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8344. #endif
  8345. { BUILTIN_NOSPEC "hash" , hashcmd },
  8346. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8347. { BUILTIN_NOSPEC "help" , helpcmd },
  8348. #endif
  8349. #if JOBS
  8350. { BUILTIN_REGULAR "jobs" , jobscmd },
  8351. { BUILTIN_REGULAR "kill" , killcmd },
  8352. #endif
  8353. #if ENABLE_SH_MATH_SUPPORT
  8354. { BUILTIN_NOSPEC "let" , letcmd },
  8355. #endif
  8356. { BUILTIN_ASSIGN "local" , localcmd },
  8357. #if ENABLE_ASH_BUILTIN_PRINTF
  8358. { BUILTIN_REGULAR "printf" , printfcmd },
  8359. #endif
  8360. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8361. { BUILTIN_REGULAR "read" , readcmd },
  8362. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8363. { BUILTIN_SPEC_REG "return" , returncmd },
  8364. { BUILTIN_SPEC_REG "set" , setcmd },
  8365. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8366. #if ENABLE_ASH_BASH_COMPAT
  8367. { BUILTIN_SPEC_REG "source" , dotcmd },
  8368. #endif
  8369. #if ENABLE_ASH_BUILTIN_TEST
  8370. { BUILTIN_REGULAR "test" , testcmd },
  8371. #endif
  8372. { BUILTIN_SPEC_REG "times" , timescmd },
  8373. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8374. { BUILTIN_REGULAR "true" , truecmd },
  8375. { BUILTIN_NOSPEC "type" , typecmd },
  8376. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8377. { BUILTIN_REGULAR "umask" , umaskcmd },
  8378. #if ENABLE_ASH_ALIAS
  8379. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8380. #endif
  8381. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8382. { BUILTIN_REGULAR "wait" , waitcmd },
  8383. };
  8384. /* Should match the above table! */
  8385. #define COMMANDCMD (builtintab + \
  8386. 2 + \
  8387. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8388. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8389. 1 * ENABLE_ASH_ALIAS + \
  8390. 1 * ENABLE_ASH_JOB_CONTROL + \
  8391. 3)
  8392. #define EXECCMD (builtintab + \
  8393. 2 + \
  8394. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8395. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8396. 1 * ENABLE_ASH_ALIAS + \
  8397. 1 * ENABLE_ASH_JOB_CONTROL + \
  8398. 3 + \
  8399. 1 * ENABLE_ASH_CMDCMD + \
  8400. 1 + \
  8401. ENABLE_ASH_BUILTIN_ECHO + \
  8402. 1)
  8403. /*
  8404. * Search the table of builtin commands.
  8405. */
  8406. static struct builtincmd *
  8407. find_builtin(const char *name)
  8408. {
  8409. struct builtincmd *bp;
  8410. bp = bsearch(
  8411. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8412. pstrcmp
  8413. );
  8414. return bp;
  8415. }
  8416. /*
  8417. * Execute a simple command.
  8418. */
  8419. static int
  8420. isassignment(const char *p)
  8421. {
  8422. const char *q = endofname(p);
  8423. if (p == q)
  8424. return 0;
  8425. return *q == '=';
  8426. }
  8427. static int FAST_FUNC
  8428. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8429. {
  8430. /* Preserve exitstatus of a previous possible redirection
  8431. * as POSIX mandates */
  8432. return back_exitstatus;
  8433. }
  8434. static void
  8435. evalcommand(union node *cmd, int flags)
  8436. {
  8437. static const struct builtincmd null_bltin = {
  8438. "\0\0", bltincmd /* why three NULs? */
  8439. };
  8440. struct stackmark smark;
  8441. union node *argp;
  8442. struct arglist arglist;
  8443. struct arglist varlist;
  8444. char **argv;
  8445. int argc;
  8446. const struct strlist *sp;
  8447. struct cmdentry cmdentry;
  8448. struct job *jp;
  8449. char *lastarg;
  8450. const char *path;
  8451. int spclbltin;
  8452. int status;
  8453. char **nargv;
  8454. struct builtincmd *bcmd;
  8455. smallint cmd_is_exec;
  8456. smallint pseudovarflag = 0;
  8457. /* First expand the arguments. */
  8458. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8459. setstackmark(&smark);
  8460. back_exitstatus = 0;
  8461. cmdentry.cmdtype = CMDBUILTIN;
  8462. cmdentry.u.cmd = &null_bltin;
  8463. varlist.lastp = &varlist.list;
  8464. *varlist.lastp = NULL;
  8465. arglist.lastp = &arglist.list;
  8466. *arglist.lastp = NULL;
  8467. argc = 0;
  8468. if (cmd->ncmd.args) {
  8469. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8470. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8471. }
  8472. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8473. struct strlist **spp;
  8474. spp = arglist.lastp;
  8475. if (pseudovarflag && isassignment(argp->narg.text))
  8476. expandarg(argp, &arglist, EXP_VARTILDE);
  8477. else
  8478. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8479. for (sp = *spp; sp; sp = sp->next)
  8480. argc++;
  8481. }
  8482. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8483. for (sp = arglist.list; sp; sp = sp->next) {
  8484. TRACE(("evalcommand arg: %s\n", sp->text));
  8485. *nargv++ = sp->text;
  8486. }
  8487. *nargv = NULL;
  8488. lastarg = NULL;
  8489. if (iflag && funcnest == 0 && argc > 0)
  8490. lastarg = nargv[-1];
  8491. preverrout_fd = 2;
  8492. expredir(cmd->ncmd.redirect);
  8493. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8494. path = vpath.var_text;
  8495. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8496. struct strlist **spp;
  8497. char *p;
  8498. spp = varlist.lastp;
  8499. expandarg(argp, &varlist, EXP_VARTILDE);
  8500. /*
  8501. * Modify the command lookup path, if a PATH= assignment
  8502. * is present
  8503. */
  8504. p = (*spp)->text;
  8505. if (varcmp(p, path) == 0)
  8506. path = p;
  8507. }
  8508. /* Print the command if xflag is set. */
  8509. if (xflag) {
  8510. int n;
  8511. const char *p = " %s" + 1;
  8512. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8513. sp = varlist.list;
  8514. for (n = 0; n < 2; n++) {
  8515. while (sp) {
  8516. fdprintf(preverrout_fd, p, sp->text);
  8517. sp = sp->next;
  8518. p = " %s";
  8519. }
  8520. sp = arglist.list;
  8521. }
  8522. safe_write(preverrout_fd, "\n", 1);
  8523. }
  8524. cmd_is_exec = 0;
  8525. spclbltin = -1;
  8526. /* Now locate the command. */
  8527. if (argc) {
  8528. int cmd_flag = DO_ERR;
  8529. #if ENABLE_ASH_CMDCMD
  8530. const char *oldpath = path + 5;
  8531. #endif
  8532. path += 5;
  8533. for (;;) {
  8534. find_command(argv[0], &cmdentry, cmd_flag, path);
  8535. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8536. flush_stdout_stderr();
  8537. status = 127;
  8538. goto bail;
  8539. }
  8540. /* implement bltin and command here */
  8541. if (cmdentry.cmdtype != CMDBUILTIN)
  8542. break;
  8543. if (spclbltin < 0)
  8544. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8545. if (cmdentry.u.cmd == EXECCMD)
  8546. cmd_is_exec = 1;
  8547. #if ENABLE_ASH_CMDCMD
  8548. if (cmdentry.u.cmd == COMMANDCMD) {
  8549. path = oldpath;
  8550. nargv = parse_command_args(argv, &path);
  8551. if (!nargv)
  8552. break;
  8553. argc -= nargv - argv;
  8554. argv = nargv;
  8555. cmd_flag |= DO_NOFUNC;
  8556. } else
  8557. #endif
  8558. break;
  8559. }
  8560. }
  8561. if (status) {
  8562. /* We have a redirection error. */
  8563. if (spclbltin > 0)
  8564. raise_exception(EXERROR);
  8565. bail:
  8566. exitstatus = status;
  8567. goto out;
  8568. }
  8569. /* Execute the command. */
  8570. switch (cmdentry.cmdtype) {
  8571. default: {
  8572. #if ENABLE_FEATURE_SH_NOFORK
  8573. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  8574. * around run_nofork_applet() call.
  8575. * (2) Should this check also be done in forkshell()?
  8576. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  8577. */
  8578. /* find_command() encodes applet_no as (-2 - applet_no) */
  8579. int applet_no = (- cmdentry.u.index - 2);
  8580. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8581. listsetvar(varlist.list, VEXPORT|VSTACK);
  8582. /* run <applet>_main() */
  8583. exitstatus = run_nofork_applet(applet_no, argv);
  8584. break;
  8585. }
  8586. #endif
  8587. /* Can we avoid forking off? For example, very last command
  8588. * in a script or a subshell does not need forking,
  8589. * we can just exec it.
  8590. */
  8591. if (!(flags & EV_EXIT) || may_have_traps) {
  8592. /* No, forking off a child is necessary */
  8593. INT_OFF;
  8594. jp = makejob(/*cmd,*/ 1);
  8595. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8596. /* parent */
  8597. exitstatus = waitforjob(jp);
  8598. INT_ON;
  8599. TRACE(("forked child exited with %d\n", exitstatus));
  8600. break;
  8601. }
  8602. /* child */
  8603. FORCE_INT_ON;
  8604. /* fall through to exec'ing external program */
  8605. }
  8606. listsetvar(varlist.list, VEXPORT|VSTACK);
  8607. shellexec(argv, path, cmdentry.u.index);
  8608. /* NOTREACHED */
  8609. } /* default */
  8610. case CMDBUILTIN:
  8611. cmdenviron = varlist.list;
  8612. if (cmdenviron) {
  8613. struct strlist *list = cmdenviron;
  8614. int i = VNOSET;
  8615. if (spclbltin > 0 || argc == 0) {
  8616. i = 0;
  8617. if (cmd_is_exec && argc > 1)
  8618. i = VEXPORT;
  8619. }
  8620. listsetvar(list, i);
  8621. }
  8622. /* Tight loop with builtins only:
  8623. * "while kill -0 $child; do true; done"
  8624. * will never exit even if $child died, unless we do this
  8625. * to reap the zombie and make kill detect that it's gone: */
  8626. dowait(DOWAIT_NONBLOCK, NULL);
  8627. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8628. int exit_status;
  8629. int i = exception_type;
  8630. if (i == EXEXIT)
  8631. goto raise;
  8632. exit_status = 2;
  8633. if (i == EXINT)
  8634. exit_status = 128 + SIGINT;
  8635. if (i == EXSIG)
  8636. exit_status = 128 + pending_sig;
  8637. exitstatus = exit_status;
  8638. if (i == EXINT || spclbltin > 0) {
  8639. raise:
  8640. longjmp(exception_handler->loc, 1);
  8641. }
  8642. FORCE_INT_ON;
  8643. }
  8644. break;
  8645. case CMDFUNCTION:
  8646. listsetvar(varlist.list, 0);
  8647. /* See above for the rationale */
  8648. dowait(DOWAIT_NONBLOCK, NULL);
  8649. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8650. goto raise;
  8651. break;
  8652. } /* switch */
  8653. out:
  8654. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8655. if (lastarg) {
  8656. /* dsl: I think this is intended to be used to support
  8657. * '_' in 'vi' command mode during line editing...
  8658. * However I implemented that within libedit itself.
  8659. */
  8660. setvar("_", lastarg, 0);
  8661. }
  8662. popstackmark(&smark);
  8663. }
  8664. static int
  8665. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8666. {
  8667. char *volatile savecmdname;
  8668. struct jmploc *volatile savehandler;
  8669. struct jmploc jmploc;
  8670. int i;
  8671. savecmdname = commandname;
  8672. i = setjmp(jmploc.loc);
  8673. if (i)
  8674. goto cmddone;
  8675. savehandler = exception_handler;
  8676. exception_handler = &jmploc;
  8677. commandname = argv[0];
  8678. argptr = argv + 1;
  8679. optptr = NULL; /* initialize nextopt */
  8680. exitstatus = (*cmd->builtin)(argc, argv);
  8681. flush_stdout_stderr();
  8682. cmddone:
  8683. exitstatus |= ferror(stdout);
  8684. clearerr(stdout);
  8685. commandname = savecmdname;
  8686. exception_handler = savehandler;
  8687. return i;
  8688. }
  8689. static int
  8690. goodname(const char *p)
  8691. {
  8692. return endofname(p)[0] == '\0';
  8693. }
  8694. /*
  8695. * Search for a command. This is called before we fork so that the
  8696. * location of the command will be available in the parent as well as
  8697. * the child. The check for "goodname" is an overly conservative
  8698. * check that the name will not be subject to expansion.
  8699. */
  8700. static void
  8701. prehash(union node *n)
  8702. {
  8703. struct cmdentry entry;
  8704. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8705. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8706. }
  8707. /* ============ Builtin commands
  8708. *
  8709. * Builtin commands whose functions are closely tied to evaluation
  8710. * are implemented here.
  8711. */
  8712. /*
  8713. * Handle break and continue commands. Break, continue, and return are
  8714. * all handled by setting the evalskip flag. The evaluation routines
  8715. * above all check this flag, and if it is set they start skipping
  8716. * commands rather than executing them. The variable skipcount is
  8717. * the number of loops to break/continue, or the number of function
  8718. * levels to return. (The latter is always 1.) It should probably
  8719. * be an error to break out of more loops than exist, but it isn't
  8720. * in the standard shell so we don't make it one here.
  8721. */
  8722. static int FAST_FUNC
  8723. breakcmd(int argc UNUSED_PARAM, char **argv)
  8724. {
  8725. int n = argv[1] ? number(argv[1]) : 1;
  8726. if (n <= 0)
  8727. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8728. if (n > loopnest)
  8729. n = loopnest;
  8730. if (n > 0) {
  8731. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8732. skipcount = n;
  8733. }
  8734. return 0;
  8735. }
  8736. /* ============ input.c
  8737. *
  8738. * This implements the input routines used by the parser.
  8739. */
  8740. enum {
  8741. INPUT_PUSH_FILE = 1,
  8742. INPUT_NOFILE_OK = 2,
  8743. };
  8744. static smallint checkkwd;
  8745. /* values of checkkwd variable */
  8746. #define CHKALIAS 0x1
  8747. #define CHKKWD 0x2
  8748. #define CHKNL 0x4
  8749. /*
  8750. * Push a string back onto the input at this current parsefile level.
  8751. * We handle aliases this way.
  8752. */
  8753. #if !ENABLE_ASH_ALIAS
  8754. #define pushstring(s, ap) pushstring(s)
  8755. #endif
  8756. static void
  8757. pushstring(char *s, struct alias *ap)
  8758. {
  8759. struct strpush *sp;
  8760. int len;
  8761. len = strlen(s);
  8762. INT_OFF;
  8763. if (g_parsefile->strpush) {
  8764. sp = ckzalloc(sizeof(*sp));
  8765. sp->prev = g_parsefile->strpush;
  8766. } else {
  8767. sp = &(g_parsefile->basestrpush);
  8768. }
  8769. g_parsefile->strpush = sp;
  8770. sp->prev_string = g_parsefile->next_to_pgetc;
  8771. sp->prev_left_in_line = g_parsefile->left_in_line;
  8772. #if ENABLE_ASH_ALIAS
  8773. sp->ap = ap;
  8774. if (ap) {
  8775. ap->flag |= ALIASINUSE;
  8776. sp->string = s;
  8777. }
  8778. #endif
  8779. g_parsefile->next_to_pgetc = s;
  8780. g_parsefile->left_in_line = len;
  8781. INT_ON;
  8782. }
  8783. static void
  8784. popstring(void)
  8785. {
  8786. struct strpush *sp = g_parsefile->strpush;
  8787. INT_OFF;
  8788. #if ENABLE_ASH_ALIAS
  8789. if (sp->ap) {
  8790. if (g_parsefile->next_to_pgetc[-1] == ' '
  8791. || g_parsefile->next_to_pgetc[-1] == '\t'
  8792. ) {
  8793. checkkwd |= CHKALIAS;
  8794. }
  8795. if (sp->string != sp->ap->val) {
  8796. free(sp->string);
  8797. }
  8798. sp->ap->flag &= ~ALIASINUSE;
  8799. if (sp->ap->flag & ALIASDEAD) {
  8800. unalias(sp->ap->name);
  8801. }
  8802. }
  8803. #endif
  8804. g_parsefile->next_to_pgetc = sp->prev_string;
  8805. g_parsefile->left_in_line = sp->prev_left_in_line;
  8806. g_parsefile->strpush = sp->prev;
  8807. if (sp != &(g_parsefile->basestrpush))
  8808. free(sp);
  8809. INT_ON;
  8810. }
  8811. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8812. //it peeks whether it is &>, and then pushes back both chars.
  8813. //This function needs to save last *next_to_pgetc to buf[0]
  8814. //to make two pungetc() reliable. Currently,
  8815. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8816. static int
  8817. preadfd(void)
  8818. {
  8819. int nr;
  8820. char *buf = g_parsefile->buf;
  8821. g_parsefile->next_to_pgetc = buf;
  8822. #if ENABLE_FEATURE_EDITING
  8823. retry:
  8824. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  8825. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
  8826. else {
  8827. int timeout = -1;
  8828. # if ENABLE_ASH_IDLE_TIMEOUT
  8829. if (iflag) {
  8830. const char *tmout_var = lookupvar("TMOUT");
  8831. if (tmout_var) {
  8832. timeout = atoi(tmout_var) * 1000;
  8833. if (timeout <= 0)
  8834. timeout = -1;
  8835. }
  8836. }
  8837. # endif
  8838. # if ENABLE_FEATURE_TAB_COMPLETION
  8839. line_input_state->path_lookup = pathval();
  8840. # endif
  8841. /* Unicode support should be activated even if LANG is set
  8842. * _during_ shell execution, not only if it was set when
  8843. * shell was started. Therefore, re-check LANG every time:
  8844. */
  8845. reinit_unicode(lookupvar("LANG"));
  8846. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
  8847. if (nr == 0) {
  8848. /* Ctrl+C pressed */
  8849. if (trap[SIGINT]) {
  8850. buf[0] = '\n';
  8851. buf[1] = '\0';
  8852. raise(SIGINT);
  8853. return 1;
  8854. }
  8855. goto retry;
  8856. }
  8857. if (nr < 0) {
  8858. if (errno == 0) {
  8859. /* Ctrl+D pressed */
  8860. nr = 0;
  8861. }
  8862. # if ENABLE_ASH_IDLE_TIMEOUT
  8863. else if (errno == EAGAIN && timeout > 0) {
  8864. printf("\007timed out waiting for input: auto-logout\n");
  8865. exitshell();
  8866. }
  8867. # endif
  8868. }
  8869. }
  8870. #else
  8871. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1, /*loop_on_EINTR:*/ 1);
  8872. #endif
  8873. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  8874. if (nr < 0) {
  8875. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8876. int flags = fcntl(0, F_GETFL);
  8877. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8878. flags &= ~O_NONBLOCK;
  8879. if (fcntl(0, F_SETFL, flags) >= 0) {
  8880. out2str("sh: turning off NDELAY mode\n");
  8881. goto retry;
  8882. }
  8883. }
  8884. }
  8885. }
  8886. #endif
  8887. return nr;
  8888. }
  8889. /*
  8890. * Refill the input buffer and return the next input character:
  8891. *
  8892. * 1) If a string was pushed back on the input, pop it;
  8893. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8894. * or we are reading from a string so we can't refill the buffer,
  8895. * return EOF.
  8896. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8897. * 4) Process input up to the next newline, deleting nul characters.
  8898. */
  8899. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8900. #define pgetc_debug(...) ((void)0)
  8901. static int
  8902. preadbuffer(void)
  8903. {
  8904. char *q;
  8905. int more;
  8906. while (g_parsefile->strpush) {
  8907. #if ENABLE_ASH_ALIAS
  8908. if (g_parsefile->left_in_line == -1
  8909. && g_parsefile->strpush->ap
  8910. && g_parsefile->next_to_pgetc[-1] != ' '
  8911. && g_parsefile->next_to_pgetc[-1] != '\t'
  8912. ) {
  8913. pgetc_debug("preadbuffer PEOA");
  8914. return PEOA;
  8915. }
  8916. #endif
  8917. popstring();
  8918. /* try "pgetc" now: */
  8919. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8920. g_parsefile->left_in_line,
  8921. g_parsefile->next_to_pgetc,
  8922. g_parsefile->next_to_pgetc);
  8923. if (--g_parsefile->left_in_line >= 0)
  8924. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8925. }
  8926. /* on both branches above g_parsefile->left_in_line < 0.
  8927. * "pgetc" needs refilling.
  8928. */
  8929. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8930. * pungetc() may increment it a few times.
  8931. * Assuming it won't increment it to less than -90.
  8932. */
  8933. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8934. pgetc_debug("preadbuffer PEOF1");
  8935. /* even in failure keep left_in_line and next_to_pgetc
  8936. * in lock step, for correct multi-layer pungetc.
  8937. * left_in_line was decremented before preadbuffer(),
  8938. * must inc next_to_pgetc: */
  8939. g_parsefile->next_to_pgetc++;
  8940. return PEOF;
  8941. }
  8942. more = g_parsefile->left_in_buffer;
  8943. if (more <= 0) {
  8944. flush_stdout_stderr();
  8945. again:
  8946. more = preadfd();
  8947. if (more <= 0) {
  8948. /* don't try reading again */
  8949. g_parsefile->left_in_line = -99;
  8950. pgetc_debug("preadbuffer PEOF2");
  8951. g_parsefile->next_to_pgetc++;
  8952. return PEOF;
  8953. }
  8954. }
  8955. /* Find out where's the end of line.
  8956. * Set g_parsefile->left_in_line
  8957. * and g_parsefile->left_in_buffer acordingly.
  8958. * NUL chars are deleted.
  8959. */
  8960. q = g_parsefile->next_to_pgetc;
  8961. for (;;) {
  8962. char c;
  8963. more--;
  8964. c = *q;
  8965. if (c == '\0') {
  8966. memmove(q, q + 1, more);
  8967. } else {
  8968. q++;
  8969. if (c == '\n') {
  8970. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8971. break;
  8972. }
  8973. }
  8974. if (more <= 0) {
  8975. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8976. if (g_parsefile->left_in_line < 0)
  8977. goto again;
  8978. break;
  8979. }
  8980. }
  8981. g_parsefile->left_in_buffer = more;
  8982. if (vflag) {
  8983. char save = *q;
  8984. *q = '\0';
  8985. out2str(g_parsefile->next_to_pgetc);
  8986. *q = save;
  8987. }
  8988. pgetc_debug("preadbuffer at %d:%p'%s'",
  8989. g_parsefile->left_in_line,
  8990. g_parsefile->next_to_pgetc,
  8991. g_parsefile->next_to_pgetc);
  8992. return (unsigned char)*g_parsefile->next_to_pgetc++;
  8993. }
  8994. #define pgetc_as_macro() \
  8995. (--g_parsefile->left_in_line >= 0 \
  8996. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  8997. : preadbuffer() \
  8998. )
  8999. static int
  9000. pgetc(void)
  9001. {
  9002. pgetc_debug("pgetc_fast at %d:%p'%s'",
  9003. g_parsefile->left_in_line,
  9004. g_parsefile->next_to_pgetc,
  9005. g_parsefile->next_to_pgetc);
  9006. return pgetc_as_macro();
  9007. }
  9008. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  9009. # define pgetc_fast() pgetc()
  9010. #else
  9011. # define pgetc_fast() pgetc_as_macro()
  9012. #endif
  9013. #if ENABLE_ASH_ALIAS
  9014. static int
  9015. pgetc_without_PEOA(void)
  9016. {
  9017. int c;
  9018. do {
  9019. pgetc_debug("pgetc_fast at %d:%p'%s'",
  9020. g_parsefile->left_in_line,
  9021. g_parsefile->next_to_pgetc,
  9022. g_parsefile->next_to_pgetc);
  9023. c = pgetc_fast();
  9024. } while (c == PEOA);
  9025. return c;
  9026. }
  9027. #else
  9028. # define pgetc_without_PEOA() pgetc()
  9029. #endif
  9030. /*
  9031. * Read a line from the script.
  9032. */
  9033. static char *
  9034. pfgets(char *line, int len)
  9035. {
  9036. char *p = line;
  9037. int nleft = len;
  9038. int c;
  9039. while (--nleft > 0) {
  9040. c = pgetc_without_PEOA();
  9041. if (c == PEOF) {
  9042. if (p == line)
  9043. return NULL;
  9044. break;
  9045. }
  9046. *p++ = c;
  9047. if (c == '\n')
  9048. break;
  9049. }
  9050. *p = '\0';
  9051. return line;
  9052. }
  9053. /*
  9054. * Undo the last call to pgetc. Only one character may be pushed back.
  9055. * PEOF may be pushed back.
  9056. */
  9057. static void
  9058. pungetc(void)
  9059. {
  9060. g_parsefile->left_in_line++;
  9061. g_parsefile->next_to_pgetc--;
  9062. pgetc_debug("pushed back to %d:%p'%s'",
  9063. g_parsefile->left_in_line,
  9064. g_parsefile->next_to_pgetc,
  9065. g_parsefile->next_to_pgetc);
  9066. }
  9067. /*
  9068. * To handle the "." command, a stack of input files is used. Pushfile
  9069. * adds a new entry to the stack and popfile restores the previous level.
  9070. */
  9071. static void
  9072. pushfile(void)
  9073. {
  9074. struct parsefile *pf;
  9075. pf = ckzalloc(sizeof(*pf));
  9076. pf->prev = g_parsefile;
  9077. pf->pf_fd = -1;
  9078. /*pf->strpush = NULL; - ckzalloc did it */
  9079. /*pf->basestrpush.prev = NULL;*/
  9080. g_parsefile = pf;
  9081. }
  9082. static void
  9083. popfile(void)
  9084. {
  9085. struct parsefile *pf = g_parsefile;
  9086. INT_OFF;
  9087. if (pf->pf_fd >= 0)
  9088. close(pf->pf_fd);
  9089. free(pf->buf);
  9090. while (pf->strpush)
  9091. popstring();
  9092. g_parsefile = pf->prev;
  9093. free(pf);
  9094. INT_ON;
  9095. }
  9096. /*
  9097. * Return to top level.
  9098. */
  9099. static void
  9100. popallfiles(void)
  9101. {
  9102. while (g_parsefile != &basepf)
  9103. popfile();
  9104. }
  9105. /*
  9106. * Close the file(s) that the shell is reading commands from. Called
  9107. * after a fork is done.
  9108. */
  9109. static void
  9110. closescript(void)
  9111. {
  9112. popallfiles();
  9113. if (g_parsefile->pf_fd > 0) {
  9114. close(g_parsefile->pf_fd);
  9115. g_parsefile->pf_fd = 0;
  9116. }
  9117. }
  9118. /*
  9119. * Like setinputfile, but takes an open file descriptor. Call this with
  9120. * interrupts off.
  9121. */
  9122. static void
  9123. setinputfd(int fd, int push)
  9124. {
  9125. close_on_exec_on(fd);
  9126. if (push) {
  9127. pushfile();
  9128. g_parsefile->buf = NULL;
  9129. }
  9130. g_parsefile->pf_fd = fd;
  9131. if (g_parsefile->buf == NULL)
  9132. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9133. g_parsefile->left_in_buffer = 0;
  9134. g_parsefile->left_in_line = 0;
  9135. g_parsefile->linno = 1;
  9136. }
  9137. /*
  9138. * Set the input to take input from a file. If push is set, push the
  9139. * old input onto the stack first.
  9140. */
  9141. static int
  9142. setinputfile(const char *fname, int flags)
  9143. {
  9144. int fd;
  9145. int fd2;
  9146. INT_OFF;
  9147. fd = open(fname, O_RDONLY);
  9148. if (fd < 0) {
  9149. if (flags & INPUT_NOFILE_OK)
  9150. goto out;
  9151. ash_msg_and_raise_error("can't open '%s'", fname);
  9152. }
  9153. if (fd < 10) {
  9154. fd2 = copyfd(fd, 10);
  9155. close(fd);
  9156. if (fd2 < 0)
  9157. ash_msg_and_raise_error("out of file descriptors");
  9158. fd = fd2;
  9159. }
  9160. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9161. out:
  9162. INT_ON;
  9163. return fd;
  9164. }
  9165. /*
  9166. * Like setinputfile, but takes input from a string.
  9167. */
  9168. static void
  9169. setinputstring(char *string)
  9170. {
  9171. INT_OFF;
  9172. pushfile();
  9173. g_parsefile->next_to_pgetc = string;
  9174. g_parsefile->left_in_line = strlen(string);
  9175. g_parsefile->buf = NULL;
  9176. g_parsefile->linno = 1;
  9177. INT_ON;
  9178. }
  9179. /* ============ mail.c
  9180. *
  9181. * Routines to check for mail.
  9182. */
  9183. #if ENABLE_ASH_MAIL
  9184. #define MAXMBOXES 10
  9185. /* times of mailboxes */
  9186. static time_t mailtime[MAXMBOXES];
  9187. /* Set if MAIL or MAILPATH is changed. */
  9188. static smallint mail_var_path_changed;
  9189. /*
  9190. * Print appropriate message(s) if mail has arrived.
  9191. * If mail_var_path_changed is set,
  9192. * then the value of MAIL has mail_var_path_changed,
  9193. * so we just update the values.
  9194. */
  9195. static void
  9196. chkmail(void)
  9197. {
  9198. const char *mpath;
  9199. char *p;
  9200. char *q;
  9201. time_t *mtp;
  9202. struct stackmark smark;
  9203. struct stat statb;
  9204. setstackmark(&smark);
  9205. mpath = mpathset() ? mpathval() : mailval();
  9206. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  9207. p = path_advance(&mpath, nullstr);
  9208. if (p == NULL)
  9209. break;
  9210. if (*p == '\0')
  9211. continue;
  9212. for (q = p; *q; q++)
  9213. continue;
  9214. #if DEBUG
  9215. if (q[-1] != '/')
  9216. abort();
  9217. #endif
  9218. q[-1] = '\0'; /* delete trailing '/' */
  9219. if (stat(p, &statb) < 0) {
  9220. *mtp = 0;
  9221. continue;
  9222. }
  9223. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  9224. fprintf(
  9225. stderr, "%s\n",
  9226. pathopt ? pathopt : "you have mail"
  9227. );
  9228. }
  9229. *mtp = statb.st_mtime;
  9230. }
  9231. mail_var_path_changed = 0;
  9232. popstackmark(&smark);
  9233. }
  9234. static void FAST_FUNC
  9235. changemail(const char *val UNUSED_PARAM)
  9236. {
  9237. mail_var_path_changed = 1;
  9238. }
  9239. #endif /* ASH_MAIL */
  9240. /* ============ ??? */
  9241. /*
  9242. * Set the shell parameters.
  9243. */
  9244. static void
  9245. setparam(char **argv)
  9246. {
  9247. char **newparam;
  9248. char **ap;
  9249. int nparam;
  9250. for (nparam = 0; argv[nparam]; nparam++)
  9251. continue;
  9252. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9253. while (*argv) {
  9254. *ap++ = ckstrdup(*argv++);
  9255. }
  9256. *ap = NULL;
  9257. freeparam(&shellparam);
  9258. shellparam.malloced = 1;
  9259. shellparam.nparam = nparam;
  9260. shellparam.p = newparam;
  9261. #if ENABLE_ASH_GETOPTS
  9262. shellparam.optind = 1;
  9263. shellparam.optoff = -1;
  9264. #endif
  9265. }
  9266. /*
  9267. * Process shell options. The global variable argptr contains a pointer
  9268. * to the argument list; we advance it past the options.
  9269. *
  9270. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9271. * For a non-interactive shell, an error condition encountered
  9272. * by a special built-in ... shall cause the shell to write a diagnostic message
  9273. * to standard error and exit as shown in the following table:
  9274. * Error Special Built-In
  9275. * ...
  9276. * Utility syntax error (option or operand error) Shall exit
  9277. * ...
  9278. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9279. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9280. * and shell continues), and people rely on this behavior!
  9281. * Testcase:
  9282. * set -o barfoo 2>/dev/null
  9283. * echo $?
  9284. *
  9285. * Oh well. Let's mimic that.
  9286. */
  9287. static int
  9288. plus_minus_o(char *name, int val)
  9289. {
  9290. int i;
  9291. if (name) {
  9292. for (i = 0; i < NOPTS; i++) {
  9293. if (strcmp(name, optnames(i)) == 0) {
  9294. optlist[i] = val;
  9295. return 0;
  9296. }
  9297. }
  9298. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9299. return 1;
  9300. }
  9301. for (i = 0; i < NOPTS; i++) {
  9302. if (val) {
  9303. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9304. } else {
  9305. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9306. }
  9307. }
  9308. return 0;
  9309. }
  9310. static void
  9311. setoption(int flag, int val)
  9312. {
  9313. int i;
  9314. for (i = 0; i < NOPTS; i++) {
  9315. if (optletters(i) == flag) {
  9316. optlist[i] = val;
  9317. return;
  9318. }
  9319. }
  9320. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9321. /* NOTREACHED */
  9322. }
  9323. static int
  9324. options(int cmdline)
  9325. {
  9326. char *p;
  9327. int val;
  9328. int c;
  9329. if (cmdline)
  9330. minusc = NULL;
  9331. while ((p = *argptr) != NULL) {
  9332. c = *p++;
  9333. if (c != '-' && c != '+')
  9334. break;
  9335. argptr++;
  9336. val = 0; /* val = 0 if c == '+' */
  9337. if (c == '-') {
  9338. val = 1;
  9339. if (p[0] == '\0' || LONE_DASH(p)) {
  9340. if (!cmdline) {
  9341. /* "-" means turn off -x and -v */
  9342. if (p[0] == '\0')
  9343. xflag = vflag = 0;
  9344. /* "--" means reset params */
  9345. else if (*argptr == NULL)
  9346. setparam(argptr);
  9347. }
  9348. break; /* "-" or "--" terminates options */
  9349. }
  9350. }
  9351. /* first char was + or - */
  9352. while ((c = *p++) != '\0') {
  9353. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9354. if (c == 'c' && cmdline) {
  9355. minusc = p; /* command is after shell args */
  9356. } else if (c == 'o') {
  9357. if (plus_minus_o(*argptr, val)) {
  9358. /* it already printed err message */
  9359. return 1; /* error */
  9360. }
  9361. if (*argptr)
  9362. argptr++;
  9363. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9364. isloginsh = 1;
  9365. /* bash does not accept +-login, we also won't */
  9366. } else if (cmdline && val && (c == '-')) { /* long options */
  9367. if (strcmp(p, "login") == 0)
  9368. isloginsh = 1;
  9369. break;
  9370. } else {
  9371. setoption(c, val);
  9372. }
  9373. }
  9374. }
  9375. return 0;
  9376. }
  9377. /*
  9378. * The shift builtin command.
  9379. */
  9380. static int FAST_FUNC
  9381. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9382. {
  9383. int n;
  9384. char **ap1, **ap2;
  9385. n = 1;
  9386. if (argv[1])
  9387. n = number(argv[1]);
  9388. if (n > shellparam.nparam)
  9389. n = 0; /* bash compat, was = shellparam.nparam; */
  9390. INT_OFF;
  9391. shellparam.nparam -= n;
  9392. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9393. if (shellparam.malloced)
  9394. free(*ap1);
  9395. }
  9396. ap2 = shellparam.p;
  9397. while ((*ap2++ = *ap1++) != NULL)
  9398. continue;
  9399. #if ENABLE_ASH_GETOPTS
  9400. shellparam.optind = 1;
  9401. shellparam.optoff = -1;
  9402. #endif
  9403. INT_ON;
  9404. return 0;
  9405. }
  9406. /*
  9407. * POSIX requires that 'set' (but not export or readonly) output the
  9408. * variables in lexicographic order - by the locale's collating order (sigh).
  9409. * Maybe we could keep them in an ordered balanced binary tree
  9410. * instead of hashed lists.
  9411. * For now just roll 'em through qsort for printing...
  9412. */
  9413. static int
  9414. showvars(const char *sep_prefix, int on, int off)
  9415. {
  9416. const char *sep;
  9417. char **ep, **epend;
  9418. ep = listvars(on, off, &epend);
  9419. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9420. sep = *sep_prefix ? " " : sep_prefix;
  9421. for (; ep < epend; ep++) {
  9422. const char *p;
  9423. const char *q;
  9424. p = strchrnul(*ep, '=');
  9425. q = nullstr;
  9426. if (*p)
  9427. q = single_quote(++p);
  9428. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9429. }
  9430. return 0;
  9431. }
  9432. /*
  9433. * The set command builtin.
  9434. */
  9435. static int FAST_FUNC
  9436. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9437. {
  9438. int retval;
  9439. if (!argv[1])
  9440. return showvars(nullstr, 0, VUNSET);
  9441. INT_OFF;
  9442. retval = options(/*cmdline:*/ 0);
  9443. if (retval == 0) { /* if no parse error... */
  9444. optschanged();
  9445. if (*argptr != NULL) {
  9446. setparam(argptr);
  9447. }
  9448. }
  9449. INT_ON;
  9450. return retval;
  9451. }
  9452. #if ENABLE_ASH_RANDOM_SUPPORT
  9453. static void FAST_FUNC
  9454. change_random(const char *value)
  9455. {
  9456. uint32_t t;
  9457. if (value == NULL) {
  9458. /* "get", generate */
  9459. t = next_random(&random_gen);
  9460. /* set without recursion */
  9461. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9462. vrandom.flags &= ~VNOFUNC;
  9463. } else {
  9464. /* set/reset */
  9465. t = strtoul(value, NULL, 10);
  9466. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9467. }
  9468. }
  9469. #endif
  9470. #if ENABLE_ASH_GETOPTS
  9471. static int
  9472. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9473. {
  9474. char *p, *q;
  9475. char c = '?';
  9476. int done = 0;
  9477. int err = 0;
  9478. char s[12];
  9479. char **optnext;
  9480. if (*param_optind < 1)
  9481. return 1;
  9482. optnext = optfirst + *param_optind - 1;
  9483. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9484. p = NULL;
  9485. else
  9486. p = optnext[-1] + *optoff;
  9487. if (p == NULL || *p == '\0') {
  9488. /* Current word is done, advance */
  9489. p = *optnext;
  9490. if (p == NULL || *p != '-' || *++p == '\0') {
  9491. atend:
  9492. p = NULL;
  9493. done = 1;
  9494. goto out;
  9495. }
  9496. optnext++;
  9497. if (LONE_DASH(p)) /* check for "--" */
  9498. goto atend;
  9499. }
  9500. c = *p++;
  9501. for (q = optstr; *q != c;) {
  9502. if (*q == '\0') {
  9503. if (optstr[0] == ':') {
  9504. s[0] = c;
  9505. s[1] = '\0';
  9506. err |= setvarsafe("OPTARG", s, 0);
  9507. } else {
  9508. fprintf(stderr, "Illegal option -%c\n", c);
  9509. unsetvar("OPTARG");
  9510. }
  9511. c = '?';
  9512. goto out;
  9513. }
  9514. if (*++q == ':')
  9515. q++;
  9516. }
  9517. if (*++q == ':') {
  9518. if (*p == '\0' && (p = *optnext) == NULL) {
  9519. if (optstr[0] == ':') {
  9520. s[0] = c;
  9521. s[1] = '\0';
  9522. err |= setvarsafe("OPTARG", s, 0);
  9523. c = ':';
  9524. } else {
  9525. fprintf(stderr, "No arg for -%c option\n", c);
  9526. unsetvar("OPTARG");
  9527. c = '?';
  9528. }
  9529. goto out;
  9530. }
  9531. if (p == *optnext)
  9532. optnext++;
  9533. err |= setvarsafe("OPTARG", p, 0);
  9534. p = NULL;
  9535. } else
  9536. err |= setvarsafe("OPTARG", nullstr, 0);
  9537. out:
  9538. *optoff = p ? p - *(optnext - 1) : -1;
  9539. *param_optind = optnext - optfirst + 1;
  9540. fmtstr(s, sizeof(s), "%d", *param_optind);
  9541. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9542. s[0] = c;
  9543. s[1] = '\0';
  9544. err |= setvarsafe(optvar, s, 0);
  9545. if (err) {
  9546. *param_optind = 1;
  9547. *optoff = -1;
  9548. flush_stdout_stderr();
  9549. raise_exception(EXERROR);
  9550. }
  9551. return done;
  9552. }
  9553. /*
  9554. * The getopts builtin. Shellparam.optnext points to the next argument
  9555. * to be processed. Shellparam.optptr points to the next character to
  9556. * be processed in the current argument. If shellparam.optnext is NULL,
  9557. * then it's the first time getopts has been called.
  9558. */
  9559. static int FAST_FUNC
  9560. getoptscmd(int argc, char **argv)
  9561. {
  9562. char **optbase;
  9563. if (argc < 3)
  9564. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9565. if (argc == 3) {
  9566. optbase = shellparam.p;
  9567. if (shellparam.optind > shellparam.nparam + 1) {
  9568. shellparam.optind = 1;
  9569. shellparam.optoff = -1;
  9570. }
  9571. } else {
  9572. optbase = &argv[3];
  9573. if (shellparam.optind > argc - 2) {
  9574. shellparam.optind = 1;
  9575. shellparam.optoff = -1;
  9576. }
  9577. }
  9578. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9579. &shellparam.optoff);
  9580. }
  9581. #endif /* ASH_GETOPTS */
  9582. /* ============ Shell parser */
  9583. struct heredoc {
  9584. struct heredoc *next; /* next here document in list */
  9585. union node *here; /* redirection node */
  9586. char *eofmark; /* string indicating end of input */
  9587. smallint striptabs; /* if set, strip leading tabs */
  9588. };
  9589. static smallint tokpushback; /* last token pushed back */
  9590. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9591. static smallint quoteflag; /* set if (part of) last token was quoted */
  9592. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9593. static struct heredoc *heredoclist; /* list of here documents to read */
  9594. static char *wordtext; /* text of last word returned by readtoken */
  9595. static struct nodelist *backquotelist;
  9596. static union node *redirnode;
  9597. static struct heredoc *heredoc;
  9598. static const char *
  9599. tokname(char *buf, int tok)
  9600. {
  9601. if (tok < TSEMI)
  9602. return tokname_array[tok] + 1;
  9603. sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  9604. return buf;
  9605. }
  9606. /* raise_error_unexpected_syntax:
  9607. * Called when an unexpected token is read during the parse. The argument
  9608. * is the token that is expected, or -1 if more than one type of token can
  9609. * occur at this point.
  9610. */
  9611. static void raise_error_unexpected_syntax(int) NORETURN;
  9612. static void
  9613. raise_error_unexpected_syntax(int token)
  9614. {
  9615. char msg[64];
  9616. char buf[16];
  9617. int l;
  9618. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  9619. if (token >= 0)
  9620. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  9621. raise_error_syntax(msg);
  9622. /* NOTREACHED */
  9623. }
  9624. #define EOFMARKLEN 79
  9625. /* parsing is heavily cross-recursive, need these forward decls */
  9626. static union node *andor(void);
  9627. static union node *pipeline(void);
  9628. static union node *parse_command(void);
  9629. static void parseheredoc(void);
  9630. static char peektoken(void);
  9631. static int readtoken(void);
  9632. static union node *
  9633. list(int nlflag)
  9634. {
  9635. union node *n1, *n2, *n3;
  9636. int tok;
  9637. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9638. if (nlflag == 2 && peektoken())
  9639. return NULL;
  9640. n1 = NULL;
  9641. for (;;) {
  9642. n2 = andor();
  9643. tok = readtoken();
  9644. if (tok == TBACKGND) {
  9645. if (n2->type == NPIPE) {
  9646. n2->npipe.pipe_backgnd = 1;
  9647. } else {
  9648. if (n2->type != NREDIR) {
  9649. n3 = stzalloc(sizeof(struct nredir));
  9650. n3->nredir.n = n2;
  9651. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9652. n2 = n3;
  9653. }
  9654. n2->type = NBACKGND;
  9655. }
  9656. }
  9657. if (n1 == NULL) {
  9658. n1 = n2;
  9659. } else {
  9660. n3 = stzalloc(sizeof(struct nbinary));
  9661. n3->type = NSEMI;
  9662. n3->nbinary.ch1 = n1;
  9663. n3->nbinary.ch2 = n2;
  9664. n1 = n3;
  9665. }
  9666. switch (tok) {
  9667. case TBACKGND:
  9668. case TSEMI:
  9669. tok = readtoken();
  9670. /* fall through */
  9671. case TNL:
  9672. if (tok == TNL) {
  9673. parseheredoc();
  9674. if (nlflag == 1)
  9675. return n1;
  9676. } else {
  9677. tokpushback = 1;
  9678. }
  9679. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9680. if (peektoken())
  9681. return n1;
  9682. break;
  9683. case TEOF:
  9684. if (heredoclist)
  9685. parseheredoc();
  9686. else
  9687. pungetc(); /* push back EOF on input */
  9688. return n1;
  9689. default:
  9690. if (nlflag == 1)
  9691. raise_error_unexpected_syntax(-1);
  9692. tokpushback = 1;
  9693. return n1;
  9694. }
  9695. }
  9696. }
  9697. static union node *
  9698. andor(void)
  9699. {
  9700. union node *n1, *n2, *n3;
  9701. int t;
  9702. n1 = pipeline();
  9703. for (;;) {
  9704. t = readtoken();
  9705. if (t == TAND) {
  9706. t = NAND;
  9707. } else if (t == TOR) {
  9708. t = NOR;
  9709. } else {
  9710. tokpushback = 1;
  9711. return n1;
  9712. }
  9713. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9714. n2 = pipeline();
  9715. n3 = stzalloc(sizeof(struct nbinary));
  9716. n3->type = t;
  9717. n3->nbinary.ch1 = n1;
  9718. n3->nbinary.ch2 = n2;
  9719. n1 = n3;
  9720. }
  9721. }
  9722. static union node *
  9723. pipeline(void)
  9724. {
  9725. union node *n1, *n2, *pipenode;
  9726. struct nodelist *lp, *prev;
  9727. int negate;
  9728. negate = 0;
  9729. TRACE(("pipeline: entered\n"));
  9730. if (readtoken() == TNOT) {
  9731. negate = !negate;
  9732. checkkwd = CHKKWD | CHKALIAS;
  9733. } else
  9734. tokpushback = 1;
  9735. n1 = parse_command();
  9736. if (readtoken() == TPIPE) {
  9737. pipenode = stzalloc(sizeof(struct npipe));
  9738. pipenode->type = NPIPE;
  9739. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9740. lp = stzalloc(sizeof(struct nodelist));
  9741. pipenode->npipe.cmdlist = lp;
  9742. lp->n = n1;
  9743. do {
  9744. prev = lp;
  9745. lp = stzalloc(sizeof(struct nodelist));
  9746. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9747. lp->n = parse_command();
  9748. prev->next = lp;
  9749. } while (readtoken() == TPIPE);
  9750. lp->next = NULL;
  9751. n1 = pipenode;
  9752. }
  9753. tokpushback = 1;
  9754. if (negate) {
  9755. n2 = stzalloc(sizeof(struct nnot));
  9756. n2->type = NNOT;
  9757. n2->nnot.com = n1;
  9758. return n2;
  9759. }
  9760. return n1;
  9761. }
  9762. static union node *
  9763. makename(void)
  9764. {
  9765. union node *n;
  9766. n = stzalloc(sizeof(struct narg));
  9767. n->type = NARG;
  9768. /*n->narg.next = NULL; - stzalloc did it */
  9769. n->narg.text = wordtext;
  9770. n->narg.backquote = backquotelist;
  9771. return n;
  9772. }
  9773. static void
  9774. fixredir(union node *n, const char *text, int err)
  9775. {
  9776. int fd;
  9777. TRACE(("Fix redir %s %d\n", text, err));
  9778. if (!err)
  9779. n->ndup.vname = NULL;
  9780. fd = bb_strtou(text, NULL, 10);
  9781. if (!errno && fd >= 0)
  9782. n->ndup.dupfd = fd;
  9783. else if (LONE_DASH(text))
  9784. n->ndup.dupfd = -1;
  9785. else {
  9786. if (err)
  9787. raise_error_syntax("bad fd number");
  9788. n->ndup.vname = makename();
  9789. }
  9790. }
  9791. /*
  9792. * Returns true if the text contains nothing to expand (no dollar signs
  9793. * or backquotes).
  9794. */
  9795. static int
  9796. noexpand(const char *text)
  9797. {
  9798. unsigned char c;
  9799. while ((c = *text++) != '\0') {
  9800. if (c == CTLQUOTEMARK)
  9801. continue;
  9802. if (c == CTLESC)
  9803. text++;
  9804. else if (SIT(c, BASESYNTAX) == CCTL)
  9805. return 0;
  9806. }
  9807. return 1;
  9808. }
  9809. static void
  9810. parsefname(void)
  9811. {
  9812. union node *n = redirnode;
  9813. if (readtoken() != TWORD)
  9814. raise_error_unexpected_syntax(-1);
  9815. if (n->type == NHERE) {
  9816. struct heredoc *here = heredoc;
  9817. struct heredoc *p;
  9818. int i;
  9819. if (quoteflag == 0)
  9820. n->type = NXHERE;
  9821. TRACE(("Here document %d\n", n->type));
  9822. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9823. raise_error_syntax("illegal eof marker for << redirection");
  9824. rmescapes(wordtext, 0);
  9825. here->eofmark = wordtext;
  9826. here->next = NULL;
  9827. if (heredoclist == NULL)
  9828. heredoclist = here;
  9829. else {
  9830. for (p = heredoclist; p->next; p = p->next)
  9831. continue;
  9832. p->next = here;
  9833. }
  9834. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9835. fixredir(n, wordtext, 0);
  9836. } else {
  9837. n->nfile.fname = makename();
  9838. }
  9839. }
  9840. static union node *
  9841. simplecmd(void)
  9842. {
  9843. union node *args, **app;
  9844. union node *n = NULL;
  9845. union node *vars, **vpp;
  9846. union node **rpp, *redir;
  9847. int savecheckkwd;
  9848. #if ENABLE_ASH_BASH_COMPAT
  9849. smallint double_brackets_flag = 0;
  9850. #endif
  9851. args = NULL;
  9852. app = &args;
  9853. vars = NULL;
  9854. vpp = &vars;
  9855. redir = NULL;
  9856. rpp = &redir;
  9857. savecheckkwd = CHKALIAS;
  9858. for (;;) {
  9859. int t;
  9860. checkkwd = savecheckkwd;
  9861. t = readtoken();
  9862. switch (t) {
  9863. #if ENABLE_ASH_BASH_COMPAT
  9864. case TAND: /* "&&" */
  9865. case TOR: /* "||" */
  9866. if (!double_brackets_flag) {
  9867. tokpushback = 1;
  9868. goto out;
  9869. }
  9870. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9871. #endif
  9872. case TWORD:
  9873. n = stzalloc(sizeof(struct narg));
  9874. n->type = NARG;
  9875. /*n->narg.next = NULL; - stzalloc did it */
  9876. n->narg.text = wordtext;
  9877. #if ENABLE_ASH_BASH_COMPAT
  9878. if (strcmp("[[", wordtext) == 0)
  9879. double_brackets_flag = 1;
  9880. else if (strcmp("]]", wordtext) == 0)
  9881. double_brackets_flag = 0;
  9882. #endif
  9883. n->narg.backquote = backquotelist;
  9884. if (savecheckkwd && isassignment(wordtext)) {
  9885. *vpp = n;
  9886. vpp = &n->narg.next;
  9887. } else {
  9888. *app = n;
  9889. app = &n->narg.next;
  9890. savecheckkwd = 0;
  9891. }
  9892. break;
  9893. case TREDIR:
  9894. *rpp = n = redirnode;
  9895. rpp = &n->nfile.next;
  9896. parsefname(); /* read name of redirection file */
  9897. break;
  9898. case TLP:
  9899. if (args && app == &args->narg.next
  9900. && !vars && !redir
  9901. ) {
  9902. struct builtincmd *bcmd;
  9903. const char *name;
  9904. /* We have a function */
  9905. if (readtoken() != TRP)
  9906. raise_error_unexpected_syntax(TRP);
  9907. name = n->narg.text;
  9908. if (!goodname(name)
  9909. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9910. ) {
  9911. raise_error_syntax("bad function name");
  9912. }
  9913. n->type = NDEFUN;
  9914. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9915. n->narg.next = parse_command();
  9916. return n;
  9917. }
  9918. /* fall through */
  9919. default:
  9920. tokpushback = 1;
  9921. goto out;
  9922. }
  9923. }
  9924. out:
  9925. *app = NULL;
  9926. *vpp = NULL;
  9927. *rpp = NULL;
  9928. n = stzalloc(sizeof(struct ncmd));
  9929. n->type = NCMD;
  9930. n->ncmd.args = args;
  9931. n->ncmd.assign = vars;
  9932. n->ncmd.redirect = redir;
  9933. return n;
  9934. }
  9935. static union node *
  9936. parse_command(void)
  9937. {
  9938. union node *n1, *n2;
  9939. union node *ap, **app;
  9940. union node *cp, **cpp;
  9941. union node *redir, **rpp;
  9942. union node **rpp2;
  9943. int t;
  9944. redir = NULL;
  9945. rpp2 = &redir;
  9946. switch (readtoken()) {
  9947. default:
  9948. raise_error_unexpected_syntax(-1);
  9949. /* NOTREACHED */
  9950. case TIF:
  9951. n1 = stzalloc(sizeof(struct nif));
  9952. n1->type = NIF;
  9953. n1->nif.test = list(0);
  9954. if (readtoken() != TTHEN)
  9955. raise_error_unexpected_syntax(TTHEN);
  9956. n1->nif.ifpart = list(0);
  9957. n2 = n1;
  9958. while (readtoken() == TELIF) {
  9959. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9960. n2 = n2->nif.elsepart;
  9961. n2->type = NIF;
  9962. n2->nif.test = list(0);
  9963. if (readtoken() != TTHEN)
  9964. raise_error_unexpected_syntax(TTHEN);
  9965. n2->nif.ifpart = list(0);
  9966. }
  9967. if (lasttoken == TELSE)
  9968. n2->nif.elsepart = list(0);
  9969. else {
  9970. n2->nif.elsepart = NULL;
  9971. tokpushback = 1;
  9972. }
  9973. t = TFI;
  9974. break;
  9975. case TWHILE:
  9976. case TUNTIL: {
  9977. int got;
  9978. n1 = stzalloc(sizeof(struct nbinary));
  9979. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9980. n1->nbinary.ch1 = list(0);
  9981. got = readtoken();
  9982. if (got != TDO) {
  9983. TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
  9984. got == TWORD ? wordtext : ""));
  9985. raise_error_unexpected_syntax(TDO);
  9986. }
  9987. n1->nbinary.ch2 = list(0);
  9988. t = TDONE;
  9989. break;
  9990. }
  9991. case TFOR:
  9992. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9993. raise_error_syntax("bad for loop variable");
  9994. n1 = stzalloc(sizeof(struct nfor));
  9995. n1->type = NFOR;
  9996. n1->nfor.var = wordtext;
  9997. checkkwd = CHKKWD | CHKALIAS;
  9998. if (readtoken() == TIN) {
  9999. app = &ap;
  10000. while (readtoken() == TWORD) {
  10001. n2 = stzalloc(sizeof(struct narg));
  10002. n2->type = NARG;
  10003. /*n2->narg.next = NULL; - stzalloc did it */
  10004. n2->narg.text = wordtext;
  10005. n2->narg.backquote = backquotelist;
  10006. *app = n2;
  10007. app = &n2->narg.next;
  10008. }
  10009. *app = NULL;
  10010. n1->nfor.args = ap;
  10011. if (lasttoken != TNL && lasttoken != TSEMI)
  10012. raise_error_unexpected_syntax(-1);
  10013. } else {
  10014. n2 = stzalloc(sizeof(struct narg));
  10015. n2->type = NARG;
  10016. /*n2->narg.next = NULL; - stzalloc did it */
  10017. n2->narg.text = (char *)dolatstr;
  10018. /*n2->narg.backquote = NULL;*/
  10019. n1->nfor.args = n2;
  10020. /*
  10021. * Newline or semicolon here is optional (but note
  10022. * that the original Bourne shell only allowed NL).
  10023. */
  10024. if (lasttoken != TNL && lasttoken != TSEMI)
  10025. tokpushback = 1;
  10026. }
  10027. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10028. if (readtoken() != TDO)
  10029. raise_error_unexpected_syntax(TDO);
  10030. n1->nfor.body = list(0);
  10031. t = TDONE;
  10032. break;
  10033. case TCASE:
  10034. n1 = stzalloc(sizeof(struct ncase));
  10035. n1->type = NCASE;
  10036. if (readtoken() != TWORD)
  10037. raise_error_unexpected_syntax(TWORD);
  10038. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10039. n2->type = NARG;
  10040. /*n2->narg.next = NULL; - stzalloc did it */
  10041. n2->narg.text = wordtext;
  10042. n2->narg.backquote = backquotelist;
  10043. do {
  10044. checkkwd = CHKKWD | CHKALIAS;
  10045. } while (readtoken() == TNL);
  10046. if (lasttoken != TIN)
  10047. raise_error_unexpected_syntax(TIN);
  10048. cpp = &n1->ncase.cases;
  10049. next_case:
  10050. checkkwd = CHKNL | CHKKWD;
  10051. t = readtoken();
  10052. while (t != TESAC) {
  10053. if (lasttoken == TLP)
  10054. readtoken();
  10055. *cpp = cp = stzalloc(sizeof(struct nclist));
  10056. cp->type = NCLIST;
  10057. app = &cp->nclist.pattern;
  10058. for (;;) {
  10059. *app = ap = stzalloc(sizeof(struct narg));
  10060. ap->type = NARG;
  10061. /*ap->narg.next = NULL; - stzalloc did it */
  10062. ap->narg.text = wordtext;
  10063. ap->narg.backquote = backquotelist;
  10064. if (readtoken() != TPIPE)
  10065. break;
  10066. app = &ap->narg.next;
  10067. readtoken();
  10068. }
  10069. //ap->narg.next = NULL;
  10070. if (lasttoken != TRP)
  10071. raise_error_unexpected_syntax(TRP);
  10072. cp->nclist.body = list(2);
  10073. cpp = &cp->nclist.next;
  10074. checkkwd = CHKNL | CHKKWD;
  10075. t = readtoken();
  10076. if (t != TESAC) {
  10077. if (t != TENDCASE)
  10078. raise_error_unexpected_syntax(TENDCASE);
  10079. goto next_case;
  10080. }
  10081. }
  10082. *cpp = NULL;
  10083. goto redir;
  10084. case TLP:
  10085. n1 = stzalloc(sizeof(struct nredir));
  10086. n1->type = NSUBSHELL;
  10087. n1->nredir.n = list(0);
  10088. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10089. t = TRP;
  10090. break;
  10091. case TBEGIN:
  10092. n1 = list(0);
  10093. t = TEND;
  10094. break;
  10095. case TWORD:
  10096. case TREDIR:
  10097. tokpushback = 1;
  10098. return simplecmd();
  10099. }
  10100. if (readtoken() != t)
  10101. raise_error_unexpected_syntax(t);
  10102. redir:
  10103. /* Now check for redirection which may follow command */
  10104. checkkwd = CHKKWD | CHKALIAS;
  10105. rpp = rpp2;
  10106. while (readtoken() == TREDIR) {
  10107. *rpp = n2 = redirnode;
  10108. rpp = &n2->nfile.next;
  10109. parsefname();
  10110. }
  10111. tokpushback = 1;
  10112. *rpp = NULL;
  10113. if (redir) {
  10114. if (n1->type != NSUBSHELL) {
  10115. n2 = stzalloc(sizeof(struct nredir));
  10116. n2->type = NREDIR;
  10117. n2->nredir.n = n1;
  10118. n1 = n2;
  10119. }
  10120. n1->nredir.redirect = redir;
  10121. }
  10122. return n1;
  10123. }
  10124. #if ENABLE_ASH_BASH_COMPAT
  10125. static int decode_dollar_squote(void)
  10126. {
  10127. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10128. int c, cnt;
  10129. char *p;
  10130. char buf[4];
  10131. c = pgetc();
  10132. p = strchr(C_escapes, c);
  10133. if (p) {
  10134. buf[0] = c;
  10135. p = buf;
  10136. cnt = 3;
  10137. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10138. do {
  10139. c = pgetc();
  10140. *++p = c;
  10141. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10142. pungetc();
  10143. } else if (c == 'x') { /* \xHH */
  10144. do {
  10145. c = pgetc();
  10146. *++p = c;
  10147. } while (isxdigit(c) && --cnt);
  10148. pungetc();
  10149. if (cnt == 3) { /* \x but next char is "bad" */
  10150. c = 'x';
  10151. goto unrecognized;
  10152. }
  10153. } else { /* simple seq like \\ or \t */
  10154. p++;
  10155. }
  10156. *p = '\0';
  10157. p = buf;
  10158. c = bb_process_escape_sequence((void*)&p);
  10159. } else { /* unrecognized "\z": print both chars unless ' or " */
  10160. if (c != '\'' && c != '"') {
  10161. unrecognized:
  10162. c |= 0x100; /* "please encode \, then me" */
  10163. }
  10164. }
  10165. return c;
  10166. }
  10167. #endif
  10168. /*
  10169. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10170. * is not NULL, read a here document. In the latter case, eofmark is the
  10171. * word which marks the end of the document and striptabs is true if
  10172. * leading tabs should be stripped from the document. The argument c
  10173. * is the first character of the input token or document.
  10174. *
  10175. * Because C does not have internal subroutines, I have simulated them
  10176. * using goto's to implement the subroutine linkage. The following macros
  10177. * will run code that appears at the end of readtoken1.
  10178. */
  10179. #define CHECKEND() {goto checkend; checkend_return:;}
  10180. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10181. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10182. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10183. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10184. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10185. static int
  10186. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10187. {
  10188. /* NB: syntax parameter fits into smallint */
  10189. /* c parameter is an unsigned char or PEOF or PEOA */
  10190. char *out;
  10191. int len;
  10192. char line[EOFMARKLEN + 1];
  10193. struct nodelist *bqlist;
  10194. smallint quotef;
  10195. smallint dblquote;
  10196. smallint oldstyle;
  10197. smallint prevsyntax; /* syntax before arithmetic */
  10198. #if ENABLE_ASH_EXPAND_PRMT
  10199. smallint pssyntax; /* we are expanding a prompt string */
  10200. #endif
  10201. int varnest; /* levels of variables expansion */
  10202. int arinest; /* levels of arithmetic expansion */
  10203. int parenlevel; /* levels of parens in arithmetic */
  10204. int dqvarnest; /* levels of variables expansion within double quotes */
  10205. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  10206. #if __GNUC__
  10207. /* Avoid longjmp clobbering */
  10208. (void) &out;
  10209. (void) &quotef;
  10210. (void) &dblquote;
  10211. (void) &varnest;
  10212. (void) &arinest;
  10213. (void) &parenlevel;
  10214. (void) &dqvarnest;
  10215. (void) &oldstyle;
  10216. (void) &prevsyntax;
  10217. (void) &syntax;
  10218. #endif
  10219. startlinno = g_parsefile->linno;
  10220. bqlist = NULL;
  10221. quotef = 0;
  10222. prevsyntax = 0;
  10223. #if ENABLE_ASH_EXPAND_PRMT
  10224. pssyntax = (syntax == PSSYNTAX);
  10225. if (pssyntax)
  10226. syntax = DQSYNTAX;
  10227. #endif
  10228. dblquote = (syntax == DQSYNTAX);
  10229. varnest = 0;
  10230. arinest = 0;
  10231. parenlevel = 0;
  10232. dqvarnest = 0;
  10233. STARTSTACKSTR(out);
  10234. loop:
  10235. /* For each line, until end of word */
  10236. CHECKEND(); /* set c to PEOF if at end of here document */
  10237. for (;;) { /* until end of line or end of word */
  10238. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10239. switch (SIT(c, syntax)) {
  10240. case CNL: /* '\n' */
  10241. if (syntax == BASESYNTAX)
  10242. goto endword; /* exit outer loop */
  10243. USTPUTC(c, out);
  10244. g_parsefile->linno++;
  10245. setprompt_if(doprompt, 2);
  10246. c = pgetc();
  10247. goto loop; /* continue outer loop */
  10248. case CWORD:
  10249. USTPUTC(c, out);
  10250. break;
  10251. case CCTL:
  10252. if (eofmark == NULL || dblquote)
  10253. USTPUTC(CTLESC, out);
  10254. #if ENABLE_ASH_BASH_COMPAT
  10255. if (c == '\\' && bash_dollar_squote) {
  10256. c = decode_dollar_squote();
  10257. if (c & 0x100) {
  10258. USTPUTC('\\', out);
  10259. c = (unsigned char)c;
  10260. }
  10261. }
  10262. #endif
  10263. USTPUTC(c, out);
  10264. break;
  10265. case CBACK: /* backslash */
  10266. c = pgetc_without_PEOA();
  10267. if (c == PEOF) {
  10268. USTPUTC(CTLESC, out);
  10269. USTPUTC('\\', out);
  10270. pungetc();
  10271. } else if (c == '\n') {
  10272. setprompt_if(doprompt, 2);
  10273. } else {
  10274. #if ENABLE_ASH_EXPAND_PRMT
  10275. if (c == '$' && pssyntax) {
  10276. USTPUTC(CTLESC, out);
  10277. USTPUTC('\\', out);
  10278. }
  10279. #endif
  10280. /* Backslash is retained if we are in "str" and next char isn't special */
  10281. if (dblquote
  10282. && c != '\\'
  10283. && c != '`'
  10284. && c != '$'
  10285. && (c != '"' || eofmark != NULL)
  10286. ) {
  10287. USTPUTC(CTLESC, out);
  10288. USTPUTC('\\', out);
  10289. }
  10290. if (SIT(c, SQSYNTAX) == CCTL)
  10291. USTPUTC(CTLESC, out);
  10292. USTPUTC(c, out);
  10293. quotef = 1;
  10294. }
  10295. break;
  10296. case CSQUOTE:
  10297. syntax = SQSYNTAX;
  10298. quotemark:
  10299. if (eofmark == NULL) {
  10300. USTPUTC(CTLQUOTEMARK, out);
  10301. }
  10302. break;
  10303. case CDQUOTE:
  10304. syntax = DQSYNTAX;
  10305. dblquote = 1;
  10306. goto quotemark;
  10307. case CENDQUOTE:
  10308. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10309. if (eofmark != NULL && arinest == 0
  10310. && varnest == 0
  10311. ) {
  10312. USTPUTC(c, out);
  10313. } else {
  10314. if (dqvarnest == 0) {
  10315. syntax = BASESYNTAX;
  10316. dblquote = 0;
  10317. }
  10318. quotef = 1;
  10319. goto quotemark;
  10320. }
  10321. break;
  10322. case CVAR: /* '$' */
  10323. PARSESUB(); /* parse substitution */
  10324. break;
  10325. case CENDVAR: /* '}' */
  10326. if (varnest > 0) {
  10327. varnest--;
  10328. if (dqvarnest > 0) {
  10329. dqvarnest--;
  10330. }
  10331. c = CTLENDVAR;
  10332. }
  10333. USTPUTC(c, out);
  10334. break;
  10335. #if ENABLE_SH_MATH_SUPPORT
  10336. case CLP: /* '(' in arithmetic */
  10337. parenlevel++;
  10338. USTPUTC(c, out);
  10339. break;
  10340. case CRP: /* ')' in arithmetic */
  10341. if (parenlevel > 0) {
  10342. parenlevel--;
  10343. } else {
  10344. if (pgetc() == ')') {
  10345. if (--arinest == 0) {
  10346. syntax = prevsyntax;
  10347. dblquote = (syntax == DQSYNTAX);
  10348. c = CTLENDARI;
  10349. }
  10350. } else {
  10351. /*
  10352. * unbalanced parens
  10353. * (don't 2nd guess - no error)
  10354. */
  10355. pungetc();
  10356. }
  10357. }
  10358. USTPUTC(c, out);
  10359. break;
  10360. #endif
  10361. case CBQUOTE: /* '`' */
  10362. PARSEBACKQOLD();
  10363. break;
  10364. case CENDFILE:
  10365. goto endword; /* exit outer loop */
  10366. case CIGN:
  10367. break;
  10368. default:
  10369. if (varnest == 0) {
  10370. #if ENABLE_ASH_BASH_COMPAT
  10371. if (c == '&') {
  10372. if (pgetc() == '>')
  10373. c = 0x100 + '>'; /* flag &> */
  10374. pungetc();
  10375. }
  10376. #endif
  10377. goto endword; /* exit outer loop */
  10378. }
  10379. IF_ASH_ALIAS(if (c != PEOA))
  10380. USTPUTC(c, out);
  10381. }
  10382. c = pgetc_fast();
  10383. } /* for (;;) */
  10384. endword:
  10385. #if ENABLE_SH_MATH_SUPPORT
  10386. if (syntax == ARISYNTAX)
  10387. raise_error_syntax("missing '))'");
  10388. #endif
  10389. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  10390. raise_error_syntax("unterminated quoted string");
  10391. if (varnest != 0) {
  10392. startlinno = g_parsefile->linno;
  10393. /* { */
  10394. raise_error_syntax("missing '}'");
  10395. }
  10396. USTPUTC('\0', out);
  10397. len = out - (char *)stackblock();
  10398. out = stackblock();
  10399. if (eofmark == NULL) {
  10400. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10401. && quotef == 0
  10402. ) {
  10403. if (isdigit_str9(out)) {
  10404. PARSEREDIR(); /* passed as params: out, c */
  10405. lasttoken = TREDIR;
  10406. return lasttoken;
  10407. }
  10408. /* else: non-number X seen, interpret it
  10409. * as "NNNX>file" = "NNNX >file" */
  10410. }
  10411. pungetc();
  10412. }
  10413. quoteflag = quotef;
  10414. backquotelist = bqlist;
  10415. grabstackblock(len);
  10416. wordtext = out;
  10417. lasttoken = TWORD;
  10418. return lasttoken;
  10419. /* end of readtoken routine */
  10420. /*
  10421. * Check to see whether we are at the end of the here document. When this
  10422. * is called, c is set to the first character of the next input line. If
  10423. * we are at the end of the here document, this routine sets the c to PEOF.
  10424. */
  10425. checkend: {
  10426. if (eofmark) {
  10427. #if ENABLE_ASH_ALIAS
  10428. if (c == PEOA)
  10429. c = pgetc_without_PEOA();
  10430. #endif
  10431. if (striptabs) {
  10432. while (c == '\t') {
  10433. c = pgetc_without_PEOA();
  10434. }
  10435. }
  10436. if (c == *eofmark) {
  10437. if (pfgets(line, sizeof(line)) != NULL) {
  10438. char *p, *q;
  10439. p = line;
  10440. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10441. continue;
  10442. if (*p == '\n' && *q == '\0') {
  10443. c = PEOF;
  10444. g_parsefile->linno++;
  10445. needprompt = doprompt;
  10446. } else {
  10447. pushstring(line, NULL);
  10448. }
  10449. }
  10450. }
  10451. }
  10452. goto checkend_return;
  10453. }
  10454. /*
  10455. * Parse a redirection operator. The variable "out" points to a string
  10456. * specifying the fd to be redirected. The variable "c" contains the
  10457. * first character of the redirection operator.
  10458. */
  10459. parseredir: {
  10460. /* out is already checked to be a valid number or "" */
  10461. int fd = (*out == '\0' ? -1 : atoi(out));
  10462. union node *np;
  10463. np = stzalloc(sizeof(struct nfile));
  10464. if (c == '>') {
  10465. np->nfile.fd = 1;
  10466. c = pgetc();
  10467. if (c == '>')
  10468. np->type = NAPPEND;
  10469. else if (c == '|')
  10470. np->type = NCLOBBER;
  10471. else if (c == '&')
  10472. np->type = NTOFD;
  10473. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10474. else {
  10475. np->type = NTO;
  10476. pungetc();
  10477. }
  10478. }
  10479. #if ENABLE_ASH_BASH_COMPAT
  10480. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10481. np->nfile.fd = 1;
  10482. pgetc(); /* this is '>', no need to check */
  10483. np->type = NTO2;
  10484. }
  10485. #endif
  10486. else { /* c == '<' */
  10487. /*np->nfile.fd = 0; - stzalloc did it */
  10488. c = pgetc();
  10489. switch (c) {
  10490. case '<':
  10491. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10492. np = stzalloc(sizeof(struct nhere));
  10493. /*np->nfile.fd = 0; - stzalloc did it */
  10494. }
  10495. np->type = NHERE;
  10496. heredoc = stzalloc(sizeof(struct heredoc));
  10497. heredoc->here = np;
  10498. c = pgetc();
  10499. if (c == '-') {
  10500. heredoc->striptabs = 1;
  10501. } else {
  10502. /*heredoc->striptabs = 0; - stzalloc did it */
  10503. pungetc();
  10504. }
  10505. break;
  10506. case '&':
  10507. np->type = NFROMFD;
  10508. break;
  10509. case '>':
  10510. np->type = NFROMTO;
  10511. break;
  10512. default:
  10513. np->type = NFROM;
  10514. pungetc();
  10515. break;
  10516. }
  10517. }
  10518. if (fd >= 0)
  10519. np->nfile.fd = fd;
  10520. redirnode = np;
  10521. goto parseredir_return;
  10522. }
  10523. /*
  10524. * Parse a substitution. At this point, we have read the dollar sign
  10525. * and nothing else.
  10526. */
  10527. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10528. * (assuming ascii char codes, as the original implementation did) */
  10529. #define is_special(c) \
  10530. (((unsigned)(c) - 33 < 32) \
  10531. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10532. parsesub: {
  10533. unsigned char subtype;
  10534. int typeloc;
  10535. int flags;
  10536. c = pgetc();
  10537. if (c > 255 /* PEOA or PEOF */
  10538. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10539. ) {
  10540. #if ENABLE_ASH_BASH_COMPAT
  10541. if (c == '\'')
  10542. bash_dollar_squote = 1;
  10543. else
  10544. #endif
  10545. USTPUTC('$', out);
  10546. pungetc();
  10547. } else if (c == '(') {
  10548. /* $(command) or $((arith)) */
  10549. if (pgetc() == '(') {
  10550. #if ENABLE_SH_MATH_SUPPORT
  10551. PARSEARITH();
  10552. #else
  10553. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10554. #endif
  10555. } else {
  10556. pungetc();
  10557. PARSEBACKQNEW();
  10558. }
  10559. } else {
  10560. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  10561. USTPUTC(CTLVAR, out);
  10562. typeloc = out - (char *)stackblock();
  10563. USTPUTC(VSNORMAL, out);
  10564. subtype = VSNORMAL;
  10565. if (c == '{') {
  10566. c = pgetc();
  10567. if (c == '#') {
  10568. c = pgetc();
  10569. if (c == '}')
  10570. c = '#'; /* ${#} - same as $# */
  10571. else
  10572. subtype = VSLENGTH; /* ${#VAR} */
  10573. } else {
  10574. subtype = 0;
  10575. }
  10576. }
  10577. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10578. /* $[{[#]]NAME[}] */
  10579. do {
  10580. STPUTC(c, out);
  10581. c = pgetc();
  10582. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10583. } else if (isdigit(c)) {
  10584. /* $[{[#]]NUM[}] */
  10585. do {
  10586. STPUTC(c, out);
  10587. c = pgetc();
  10588. } while (isdigit(c));
  10589. } else if (is_special(c)) {
  10590. /* $[{[#]]<specialchar>[}] */
  10591. USTPUTC(c, out);
  10592. c = pgetc();
  10593. } else {
  10594. badsub:
  10595. raise_error_syntax("bad substitution");
  10596. }
  10597. if (c != '}' && subtype == VSLENGTH) {
  10598. /* ${#VAR didn't end with } */
  10599. goto badsub;
  10600. }
  10601. STPUTC('=', out);
  10602. flags = 0;
  10603. if (subtype == 0) {
  10604. /* ${VAR...} but not $VAR or ${#VAR} */
  10605. /* c == first char after VAR */
  10606. switch (c) {
  10607. case ':':
  10608. c = pgetc();
  10609. #if ENABLE_ASH_BASH_COMPAT
  10610. if (c == ':' || c == '$' || isdigit(c)) {
  10611. //TODO: support more general format ${v:EXPR:EXPR},
  10612. // where EXPR follows $(()) rules
  10613. subtype = VSSUBSTR;
  10614. pungetc();
  10615. break; /* "goto do_pungetc" is bigger (!) */
  10616. }
  10617. #endif
  10618. flags = VSNUL;
  10619. /*FALLTHROUGH*/
  10620. default: {
  10621. static const char types[] ALIGN1 = "}-+?=";
  10622. const char *p = strchr(types, c);
  10623. if (p == NULL)
  10624. goto badsub;
  10625. subtype = p - types + VSNORMAL;
  10626. break;
  10627. }
  10628. case '%':
  10629. case '#': {
  10630. int cc = c;
  10631. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  10632. c = pgetc();
  10633. if (c != cc)
  10634. goto do_pungetc;
  10635. subtype++;
  10636. break;
  10637. }
  10638. #if ENABLE_ASH_BASH_COMPAT
  10639. case '/':
  10640. /* ${v/[/]pattern/repl} */
  10641. //TODO: encode pattern and repl separately.
  10642. // Currently ${v/$var_with_slash/repl} is horribly broken
  10643. subtype = VSREPLACE;
  10644. c = pgetc();
  10645. if (c != '/')
  10646. goto do_pungetc;
  10647. subtype++; /* VSREPLACEALL */
  10648. break;
  10649. #endif
  10650. }
  10651. } else {
  10652. do_pungetc:
  10653. pungetc();
  10654. }
  10655. if (dblquote || arinest)
  10656. flags |= VSQUOTE;
  10657. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10658. if (subtype != VSNORMAL) {
  10659. varnest++;
  10660. if (dblquote || arinest) {
  10661. dqvarnest++;
  10662. }
  10663. }
  10664. }
  10665. goto parsesub_return;
  10666. }
  10667. /*
  10668. * Called to parse command substitutions. Newstyle is set if the command
  10669. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10670. * list of commands (passed by reference), and savelen is the number of
  10671. * characters on the top of the stack which must be preserved.
  10672. */
  10673. parsebackq: {
  10674. struct nodelist **nlpp;
  10675. smallint savepbq;
  10676. union node *n;
  10677. char *volatile str;
  10678. struct jmploc jmploc;
  10679. struct jmploc *volatile savehandler;
  10680. size_t savelen;
  10681. smallint saveprompt = 0;
  10682. #ifdef __GNUC__
  10683. (void) &saveprompt;
  10684. #endif
  10685. savepbq = parsebackquote;
  10686. if (setjmp(jmploc.loc)) {
  10687. free(str);
  10688. parsebackquote = 0;
  10689. exception_handler = savehandler;
  10690. longjmp(exception_handler->loc, 1);
  10691. }
  10692. INT_OFF;
  10693. str = NULL;
  10694. savelen = out - (char *)stackblock();
  10695. if (savelen > 0) {
  10696. str = ckmalloc(savelen);
  10697. memcpy(str, stackblock(), savelen);
  10698. }
  10699. savehandler = exception_handler;
  10700. exception_handler = &jmploc;
  10701. INT_ON;
  10702. if (oldstyle) {
  10703. /* We must read until the closing backquote, giving special
  10704. * treatment to some slashes, and then push the string and
  10705. * reread it as input, interpreting it normally.
  10706. */
  10707. char *pout;
  10708. size_t psavelen;
  10709. char *pstr;
  10710. STARTSTACKSTR(pout);
  10711. for (;;) {
  10712. int pc;
  10713. setprompt_if(needprompt, 2);
  10714. pc = pgetc();
  10715. switch (pc) {
  10716. case '`':
  10717. goto done;
  10718. case '\\':
  10719. pc = pgetc();
  10720. if (pc == '\n') {
  10721. g_parsefile->linno++;
  10722. setprompt_if(doprompt, 2);
  10723. /*
  10724. * If eating a newline, avoid putting
  10725. * the newline into the new character
  10726. * stream (via the STPUTC after the
  10727. * switch).
  10728. */
  10729. continue;
  10730. }
  10731. if (pc != '\\' && pc != '`' && pc != '$'
  10732. && (!dblquote || pc != '"')
  10733. ) {
  10734. STPUTC('\\', pout);
  10735. }
  10736. if (pc <= 255 /* not PEOA or PEOF */) {
  10737. break;
  10738. }
  10739. /* fall through */
  10740. case PEOF:
  10741. IF_ASH_ALIAS(case PEOA:)
  10742. startlinno = g_parsefile->linno;
  10743. raise_error_syntax("EOF in backquote substitution");
  10744. case '\n':
  10745. g_parsefile->linno++;
  10746. needprompt = doprompt;
  10747. break;
  10748. default:
  10749. break;
  10750. }
  10751. STPUTC(pc, pout);
  10752. }
  10753. done:
  10754. STPUTC('\0', pout);
  10755. psavelen = pout - (char *)stackblock();
  10756. if (psavelen > 0) {
  10757. pstr = grabstackstr(pout);
  10758. setinputstring(pstr);
  10759. }
  10760. }
  10761. nlpp = &bqlist;
  10762. while (*nlpp)
  10763. nlpp = &(*nlpp)->next;
  10764. *nlpp = stzalloc(sizeof(**nlpp));
  10765. /* (*nlpp)->next = NULL; - stzalloc did it */
  10766. parsebackquote = oldstyle;
  10767. if (oldstyle) {
  10768. saveprompt = doprompt;
  10769. doprompt = 0;
  10770. }
  10771. n = list(2);
  10772. if (oldstyle)
  10773. doprompt = saveprompt;
  10774. else if (readtoken() != TRP)
  10775. raise_error_unexpected_syntax(TRP);
  10776. (*nlpp)->n = n;
  10777. if (oldstyle) {
  10778. /*
  10779. * Start reading from old file again, ignoring any pushed back
  10780. * tokens left from the backquote parsing
  10781. */
  10782. popfile();
  10783. tokpushback = 0;
  10784. }
  10785. while (stackblocksize() <= savelen)
  10786. growstackblock();
  10787. STARTSTACKSTR(out);
  10788. if (str) {
  10789. memcpy(out, str, savelen);
  10790. STADJUST(savelen, out);
  10791. INT_OFF;
  10792. free(str);
  10793. str = NULL;
  10794. INT_ON;
  10795. }
  10796. parsebackquote = savepbq;
  10797. exception_handler = savehandler;
  10798. if (arinest || dblquote)
  10799. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10800. else
  10801. USTPUTC(CTLBACKQ, out);
  10802. if (oldstyle)
  10803. goto parsebackq_oldreturn;
  10804. goto parsebackq_newreturn;
  10805. }
  10806. #if ENABLE_SH_MATH_SUPPORT
  10807. /*
  10808. * Parse an arithmetic expansion (indicate start of one and set state)
  10809. */
  10810. parsearith: {
  10811. if (++arinest == 1) {
  10812. prevsyntax = syntax;
  10813. syntax = ARISYNTAX;
  10814. USTPUTC(CTLARI, out);
  10815. if (dblquote)
  10816. USTPUTC('"', out);
  10817. else
  10818. USTPUTC(' ', out);
  10819. } else {
  10820. /*
  10821. * we collapse embedded arithmetic expansion to
  10822. * parenthesis, which should be equivalent
  10823. */
  10824. USTPUTC('(', out);
  10825. }
  10826. goto parsearith_return;
  10827. }
  10828. #endif
  10829. } /* end of readtoken */
  10830. /*
  10831. * Read the next input token.
  10832. * If the token is a word, we set backquotelist to the list of cmds in
  10833. * backquotes. We set quoteflag to true if any part of the word was
  10834. * quoted.
  10835. * If the token is TREDIR, then we set redirnode to a structure containing
  10836. * the redirection.
  10837. * In all cases, the variable startlinno is set to the number of the line
  10838. * on which the token starts.
  10839. *
  10840. * [Change comment: here documents and internal procedures]
  10841. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10842. * word parsing code into a separate routine. In this case, readtoken
  10843. * doesn't need to have any internal procedures, but parseword does.
  10844. * We could also make parseoperator in essence the main routine, and
  10845. * have parseword (readtoken1?) handle both words and redirection.]
  10846. */
  10847. #define NEW_xxreadtoken
  10848. #ifdef NEW_xxreadtoken
  10849. /* singles must be first! */
  10850. static const char xxreadtoken_chars[7] ALIGN1 = {
  10851. '\n', '(', ')', /* singles */
  10852. '&', '|', ';', /* doubles */
  10853. 0
  10854. };
  10855. #define xxreadtoken_singles 3
  10856. #define xxreadtoken_doubles 3
  10857. static const char xxreadtoken_tokens[] ALIGN1 = {
  10858. TNL, TLP, TRP, /* only single occurrence allowed */
  10859. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10860. TEOF, /* corresponds to trailing nul */
  10861. TAND, TOR, TENDCASE /* if double occurrence */
  10862. };
  10863. static int
  10864. xxreadtoken(void)
  10865. {
  10866. int c;
  10867. if (tokpushback) {
  10868. tokpushback = 0;
  10869. return lasttoken;
  10870. }
  10871. setprompt_if(needprompt, 2);
  10872. startlinno = g_parsefile->linno;
  10873. for (;;) { /* until token or start of word found */
  10874. c = pgetc_fast();
  10875. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10876. continue;
  10877. if (c == '#') {
  10878. while ((c = pgetc()) != '\n' && c != PEOF)
  10879. continue;
  10880. pungetc();
  10881. } else if (c == '\\') {
  10882. if (pgetc() != '\n') {
  10883. pungetc();
  10884. break; /* return readtoken1(...) */
  10885. }
  10886. startlinno = ++g_parsefile->linno;
  10887. setprompt_if(doprompt, 2);
  10888. } else {
  10889. const char *p;
  10890. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10891. if (c != PEOF) {
  10892. if (c == '\n') {
  10893. g_parsefile->linno++;
  10894. needprompt = doprompt;
  10895. }
  10896. p = strchr(xxreadtoken_chars, c);
  10897. if (p == NULL)
  10898. break; /* return readtoken1(...) */
  10899. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10900. int cc = pgetc();
  10901. if (cc == c) { /* double occurrence? */
  10902. p += xxreadtoken_doubles + 1;
  10903. } else {
  10904. pungetc();
  10905. #if ENABLE_ASH_BASH_COMPAT
  10906. if (c == '&' && cc == '>') /* &> */
  10907. break; /* return readtoken1(...) */
  10908. #endif
  10909. }
  10910. }
  10911. }
  10912. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10913. return lasttoken;
  10914. }
  10915. } /* for (;;) */
  10916. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10917. }
  10918. #else /* old xxreadtoken */
  10919. #define RETURN(token) return lasttoken = token
  10920. static int
  10921. xxreadtoken(void)
  10922. {
  10923. int c;
  10924. if (tokpushback) {
  10925. tokpushback = 0;
  10926. return lasttoken;
  10927. }
  10928. setprompt_if(needprompt, 2);
  10929. startlinno = g_parsefile->linno;
  10930. for (;;) { /* until token or start of word found */
  10931. c = pgetc_fast();
  10932. switch (c) {
  10933. case ' ': case '\t':
  10934. IF_ASH_ALIAS(case PEOA:)
  10935. continue;
  10936. case '#':
  10937. while ((c = pgetc()) != '\n' && c != PEOF)
  10938. continue;
  10939. pungetc();
  10940. continue;
  10941. case '\\':
  10942. if (pgetc() == '\n') {
  10943. startlinno = ++g_parsefile->linno;
  10944. setprompt_if(doprompt, 2);
  10945. continue;
  10946. }
  10947. pungetc();
  10948. goto breakloop;
  10949. case '\n':
  10950. g_parsefile->linno++;
  10951. needprompt = doprompt;
  10952. RETURN(TNL);
  10953. case PEOF:
  10954. RETURN(TEOF);
  10955. case '&':
  10956. if (pgetc() == '&')
  10957. RETURN(TAND);
  10958. pungetc();
  10959. RETURN(TBACKGND);
  10960. case '|':
  10961. if (pgetc() == '|')
  10962. RETURN(TOR);
  10963. pungetc();
  10964. RETURN(TPIPE);
  10965. case ';':
  10966. if (pgetc() == ';')
  10967. RETURN(TENDCASE);
  10968. pungetc();
  10969. RETURN(TSEMI);
  10970. case '(':
  10971. RETURN(TLP);
  10972. case ')':
  10973. RETURN(TRP);
  10974. default:
  10975. goto breakloop;
  10976. }
  10977. }
  10978. breakloop:
  10979. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10980. #undef RETURN
  10981. }
  10982. #endif /* old xxreadtoken */
  10983. static int
  10984. readtoken(void)
  10985. {
  10986. int t;
  10987. #if DEBUG
  10988. smallint alreadyseen = tokpushback;
  10989. #endif
  10990. #if ENABLE_ASH_ALIAS
  10991. top:
  10992. #endif
  10993. t = xxreadtoken();
  10994. /*
  10995. * eat newlines
  10996. */
  10997. if (checkkwd & CHKNL) {
  10998. while (t == TNL) {
  10999. parseheredoc();
  11000. t = xxreadtoken();
  11001. }
  11002. }
  11003. if (t != TWORD || quoteflag) {
  11004. goto out;
  11005. }
  11006. /*
  11007. * check for keywords
  11008. */
  11009. if (checkkwd & CHKKWD) {
  11010. const char *const *pp;
  11011. pp = findkwd(wordtext);
  11012. if (pp) {
  11013. lasttoken = t = pp - tokname_array;
  11014. TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
  11015. goto out;
  11016. }
  11017. }
  11018. if (checkkwd & CHKALIAS) {
  11019. #if ENABLE_ASH_ALIAS
  11020. struct alias *ap;
  11021. ap = lookupalias(wordtext, 1);
  11022. if (ap != NULL) {
  11023. if (*ap->val) {
  11024. pushstring(ap->val, ap);
  11025. }
  11026. goto top;
  11027. }
  11028. #endif
  11029. }
  11030. out:
  11031. checkkwd = 0;
  11032. #if DEBUG
  11033. if (!alreadyseen)
  11034. TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11035. else
  11036. TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11037. #endif
  11038. return t;
  11039. }
  11040. static char
  11041. peektoken(void)
  11042. {
  11043. int t;
  11044. t = readtoken();
  11045. tokpushback = 1;
  11046. return tokname_array[t][0];
  11047. }
  11048. /*
  11049. * Read and parse a command. Returns NODE_EOF on end of file.
  11050. * (NULL is a valid parse tree indicating a blank line.)
  11051. */
  11052. static union node *
  11053. parsecmd(int interact)
  11054. {
  11055. int t;
  11056. tokpushback = 0;
  11057. doprompt = interact;
  11058. setprompt_if(doprompt, doprompt);
  11059. needprompt = 0;
  11060. t = readtoken();
  11061. if (t == TEOF)
  11062. return NODE_EOF;
  11063. if (t == TNL)
  11064. return NULL;
  11065. tokpushback = 1;
  11066. return list(1);
  11067. }
  11068. /*
  11069. * Input any here documents.
  11070. */
  11071. static void
  11072. parseheredoc(void)
  11073. {
  11074. struct heredoc *here;
  11075. union node *n;
  11076. here = heredoclist;
  11077. heredoclist = NULL;
  11078. while (here) {
  11079. setprompt_if(needprompt, 2);
  11080. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11081. here->eofmark, here->striptabs);
  11082. n = stzalloc(sizeof(struct narg));
  11083. n->narg.type = NARG;
  11084. /*n->narg.next = NULL; - stzalloc did it */
  11085. n->narg.text = wordtext;
  11086. n->narg.backquote = backquotelist;
  11087. here->here->nhere.doc = n;
  11088. here = here->next;
  11089. }
  11090. }
  11091. /*
  11092. * called by editline -- any expansions to the prompt should be added here.
  11093. */
  11094. #if ENABLE_ASH_EXPAND_PRMT
  11095. static const char *
  11096. expandstr(const char *ps)
  11097. {
  11098. union node n;
  11099. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  11100. * and token processing _can_ alter it (delete NULs etc). */
  11101. setinputstring((char *)ps);
  11102. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  11103. popfile();
  11104. n.narg.type = NARG;
  11105. n.narg.next = NULL;
  11106. n.narg.text = wordtext;
  11107. n.narg.backquote = backquotelist;
  11108. expandarg(&n, NULL, 0);
  11109. return stackblock();
  11110. }
  11111. #endif
  11112. /*
  11113. * Execute a command or commands contained in a string.
  11114. */
  11115. static int
  11116. evalstring(char *s, int mask)
  11117. {
  11118. union node *n;
  11119. struct stackmark smark;
  11120. int skip;
  11121. setinputstring(s);
  11122. setstackmark(&smark);
  11123. skip = 0;
  11124. while ((n = parsecmd(0)) != NODE_EOF) {
  11125. evaltree(n, 0);
  11126. popstackmark(&smark);
  11127. skip = evalskip;
  11128. if (skip)
  11129. break;
  11130. }
  11131. popfile();
  11132. skip &= mask;
  11133. evalskip = skip;
  11134. return skip;
  11135. }
  11136. /*
  11137. * The eval command.
  11138. */
  11139. static int FAST_FUNC
  11140. evalcmd(int argc UNUSED_PARAM, char **argv)
  11141. {
  11142. char *p;
  11143. char *concat;
  11144. if (argv[1]) {
  11145. p = argv[1];
  11146. argv += 2;
  11147. if (argv[0]) {
  11148. STARTSTACKSTR(concat);
  11149. for (;;) {
  11150. concat = stack_putstr(p, concat);
  11151. p = *argv++;
  11152. if (p == NULL)
  11153. break;
  11154. STPUTC(' ', concat);
  11155. }
  11156. STPUTC('\0', concat);
  11157. p = grabstackstr(concat);
  11158. }
  11159. evalstring(p, ~SKIPEVAL);
  11160. }
  11161. return exitstatus;
  11162. }
  11163. /*
  11164. * Read and execute commands.
  11165. * "Top" is nonzero for the top level command loop;
  11166. * it turns on prompting if the shell is interactive.
  11167. */
  11168. static int
  11169. cmdloop(int top)
  11170. {
  11171. union node *n;
  11172. struct stackmark smark;
  11173. int inter;
  11174. int numeof = 0;
  11175. TRACE(("cmdloop(%d) called\n", top));
  11176. for (;;) {
  11177. int skip;
  11178. setstackmark(&smark);
  11179. #if JOBS
  11180. if (doing_jobctl)
  11181. showjobs(stderr, SHOW_CHANGED);
  11182. #endif
  11183. inter = 0;
  11184. if (iflag && top) {
  11185. inter++;
  11186. chkmail();
  11187. }
  11188. n = parsecmd(inter);
  11189. #if DEBUG
  11190. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11191. showtree(n);
  11192. #endif
  11193. if (n == NODE_EOF) {
  11194. if (!top || numeof >= 50)
  11195. break;
  11196. if (!stoppedjobs()) {
  11197. if (!Iflag)
  11198. break;
  11199. out2str("\nUse \"exit\" to leave shell.\n");
  11200. }
  11201. numeof++;
  11202. } else if (nflag == 0) {
  11203. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11204. job_warning >>= 1;
  11205. numeof = 0;
  11206. evaltree(n, 0);
  11207. }
  11208. popstackmark(&smark);
  11209. skip = evalskip;
  11210. if (skip) {
  11211. evalskip = 0;
  11212. return skip & SKIPEVAL;
  11213. }
  11214. }
  11215. return 0;
  11216. }
  11217. /*
  11218. * Take commands from a file. To be compatible we should do a path
  11219. * search for the file, which is necessary to find sub-commands.
  11220. */
  11221. static char *
  11222. find_dot_file(char *name)
  11223. {
  11224. char *fullname;
  11225. const char *path = pathval();
  11226. struct stat statb;
  11227. /* don't try this for absolute or relative paths */
  11228. if (strchr(name, '/'))
  11229. return name;
  11230. /* IIRC standards do not say whether . is to be searched.
  11231. * And it is even smaller this way, making it unconditional for now:
  11232. */
  11233. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  11234. fullname = name;
  11235. goto try_cur_dir;
  11236. }
  11237. while ((fullname = path_advance(&path, name)) != NULL) {
  11238. try_cur_dir:
  11239. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11240. /*
  11241. * Don't bother freeing here, since it will
  11242. * be freed by the caller.
  11243. */
  11244. return fullname;
  11245. }
  11246. if (fullname != name)
  11247. stunalloc(fullname);
  11248. }
  11249. /* not found in the PATH */
  11250. ash_msg_and_raise_error("%s: not found", name);
  11251. /* NOTREACHED */
  11252. }
  11253. static int FAST_FUNC
  11254. dotcmd(int argc, char **argv)
  11255. {
  11256. char *fullname;
  11257. struct strlist *sp;
  11258. volatile struct shparam saveparam;
  11259. for (sp = cmdenviron; sp; sp = sp->next)
  11260. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11261. if (!argv[1]) {
  11262. /* bash says: "bash: .: filename argument required" */
  11263. return 2; /* bash compat */
  11264. }
  11265. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11266. exitstatus = 0;
  11267. fullname = find_dot_file(argv[1]);
  11268. argv += 2;
  11269. argc -= 2;
  11270. if (argc) { /* argc > 0, argv[0] != NULL */
  11271. saveparam = shellparam;
  11272. shellparam.malloced = 0;
  11273. shellparam.nparam = argc;
  11274. shellparam.p = argv;
  11275. };
  11276. setinputfile(fullname, INPUT_PUSH_FILE);
  11277. commandname = fullname;
  11278. cmdloop(0);
  11279. popfile();
  11280. if (argc) {
  11281. freeparam(&shellparam);
  11282. shellparam = saveparam;
  11283. };
  11284. return exitstatus;
  11285. }
  11286. static int FAST_FUNC
  11287. exitcmd(int argc UNUSED_PARAM, char **argv)
  11288. {
  11289. if (stoppedjobs())
  11290. return 0;
  11291. if (argv[1])
  11292. exitstatus = number(argv[1]);
  11293. raise_exception(EXEXIT);
  11294. /* NOTREACHED */
  11295. }
  11296. /*
  11297. * Read a file containing shell functions.
  11298. */
  11299. static void
  11300. readcmdfile(char *name)
  11301. {
  11302. setinputfile(name, INPUT_PUSH_FILE);
  11303. cmdloop(0);
  11304. popfile();
  11305. }
  11306. /* ============ find_command inplementation */
  11307. /*
  11308. * Resolve a command name. If you change this routine, you may have to
  11309. * change the shellexec routine as well.
  11310. */
  11311. static void
  11312. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11313. {
  11314. struct tblentry *cmdp;
  11315. int idx;
  11316. int prev;
  11317. char *fullname;
  11318. struct stat statb;
  11319. int e;
  11320. int updatetbl;
  11321. struct builtincmd *bcmd;
  11322. /* If name contains a slash, don't use PATH or hash table */
  11323. if (strchr(name, '/') != NULL) {
  11324. entry->u.index = -1;
  11325. if (act & DO_ABS) {
  11326. while (stat(name, &statb) < 0) {
  11327. #ifdef SYSV
  11328. if (errno == EINTR)
  11329. continue;
  11330. #endif
  11331. entry->cmdtype = CMDUNKNOWN;
  11332. return;
  11333. }
  11334. }
  11335. entry->cmdtype = CMDNORMAL;
  11336. return;
  11337. }
  11338. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11339. updatetbl = (path == pathval());
  11340. if (!updatetbl) {
  11341. act |= DO_ALTPATH;
  11342. if (strstr(path, "%builtin") != NULL)
  11343. act |= DO_ALTBLTIN;
  11344. }
  11345. /* If name is in the table, check answer will be ok */
  11346. cmdp = cmdlookup(name, 0);
  11347. if (cmdp != NULL) {
  11348. int bit;
  11349. switch (cmdp->cmdtype) {
  11350. default:
  11351. #if DEBUG
  11352. abort();
  11353. #endif
  11354. case CMDNORMAL:
  11355. bit = DO_ALTPATH;
  11356. break;
  11357. case CMDFUNCTION:
  11358. bit = DO_NOFUNC;
  11359. break;
  11360. case CMDBUILTIN:
  11361. bit = DO_ALTBLTIN;
  11362. break;
  11363. }
  11364. if (act & bit) {
  11365. updatetbl = 0;
  11366. cmdp = NULL;
  11367. } else if (cmdp->rehash == 0)
  11368. /* if not invalidated by cd, we're done */
  11369. goto success;
  11370. }
  11371. /* If %builtin not in path, check for builtin next */
  11372. bcmd = find_builtin(name);
  11373. if (bcmd) {
  11374. if (IS_BUILTIN_REGULAR(bcmd))
  11375. goto builtin_success;
  11376. if (act & DO_ALTPATH) {
  11377. if (!(act & DO_ALTBLTIN))
  11378. goto builtin_success;
  11379. } else if (builtinloc <= 0) {
  11380. goto builtin_success;
  11381. }
  11382. }
  11383. #if ENABLE_FEATURE_SH_STANDALONE
  11384. {
  11385. int applet_no = find_applet_by_name(name);
  11386. if (applet_no >= 0) {
  11387. entry->cmdtype = CMDNORMAL;
  11388. entry->u.index = -2 - applet_no;
  11389. return;
  11390. }
  11391. }
  11392. #endif
  11393. /* We have to search path. */
  11394. prev = -1; /* where to start */
  11395. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11396. if (cmdp->cmdtype == CMDBUILTIN)
  11397. prev = builtinloc;
  11398. else
  11399. prev = cmdp->param.index;
  11400. }
  11401. e = ENOENT;
  11402. idx = -1;
  11403. loop:
  11404. while ((fullname = path_advance(&path, name)) != NULL) {
  11405. stunalloc(fullname);
  11406. /* NB: code below will still use fullname
  11407. * despite it being "unallocated" */
  11408. idx++;
  11409. if (pathopt) {
  11410. if (prefix(pathopt, "builtin")) {
  11411. if (bcmd)
  11412. goto builtin_success;
  11413. continue;
  11414. }
  11415. if ((act & DO_NOFUNC)
  11416. || !prefix(pathopt, "func")
  11417. ) { /* ignore unimplemented options */
  11418. continue;
  11419. }
  11420. }
  11421. /* if rehash, don't redo absolute path names */
  11422. if (fullname[0] == '/' && idx <= prev) {
  11423. if (idx < prev)
  11424. continue;
  11425. TRACE(("searchexec \"%s\": no change\n", name));
  11426. goto success;
  11427. }
  11428. while (stat(fullname, &statb) < 0) {
  11429. #ifdef SYSV
  11430. if (errno == EINTR)
  11431. continue;
  11432. #endif
  11433. if (errno != ENOENT && errno != ENOTDIR)
  11434. e = errno;
  11435. goto loop;
  11436. }
  11437. e = EACCES; /* if we fail, this will be the error */
  11438. if (!S_ISREG(statb.st_mode))
  11439. continue;
  11440. if (pathopt) { /* this is a %func directory */
  11441. stalloc(strlen(fullname) + 1);
  11442. /* NB: stalloc will return space pointed by fullname
  11443. * (because we don't have any intervening allocations
  11444. * between stunalloc above and this stalloc) */
  11445. readcmdfile(fullname);
  11446. cmdp = cmdlookup(name, 0);
  11447. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11448. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11449. stunalloc(fullname);
  11450. goto success;
  11451. }
  11452. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11453. if (!updatetbl) {
  11454. entry->cmdtype = CMDNORMAL;
  11455. entry->u.index = idx;
  11456. return;
  11457. }
  11458. INT_OFF;
  11459. cmdp = cmdlookup(name, 1);
  11460. cmdp->cmdtype = CMDNORMAL;
  11461. cmdp->param.index = idx;
  11462. INT_ON;
  11463. goto success;
  11464. }
  11465. /* We failed. If there was an entry for this command, delete it */
  11466. if (cmdp && updatetbl)
  11467. delete_cmd_entry();
  11468. if (act & DO_ERR)
  11469. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11470. entry->cmdtype = CMDUNKNOWN;
  11471. return;
  11472. builtin_success:
  11473. if (!updatetbl) {
  11474. entry->cmdtype = CMDBUILTIN;
  11475. entry->u.cmd = bcmd;
  11476. return;
  11477. }
  11478. INT_OFF;
  11479. cmdp = cmdlookup(name, 1);
  11480. cmdp->cmdtype = CMDBUILTIN;
  11481. cmdp->param.cmd = bcmd;
  11482. INT_ON;
  11483. success:
  11484. cmdp->rehash = 0;
  11485. entry->cmdtype = cmdp->cmdtype;
  11486. entry->u = cmdp->param;
  11487. }
  11488. /* ============ trap.c */
  11489. /*
  11490. * The trap builtin.
  11491. */
  11492. static int FAST_FUNC
  11493. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11494. {
  11495. char *action;
  11496. char **ap;
  11497. int signo, exitcode;
  11498. nextopt(nullstr);
  11499. ap = argptr;
  11500. if (!*ap) {
  11501. for (signo = 0; signo < NSIG; signo++) {
  11502. char *tr = trap_ptr[signo];
  11503. if (tr) {
  11504. /* note: bash adds "SIG", but only if invoked
  11505. * as "bash". If called as "sh", or if set -o posix,
  11506. * then it prints short signal names.
  11507. * We are printing short names: */
  11508. out1fmt("trap -- %s %s\n",
  11509. single_quote(tr),
  11510. get_signame(signo));
  11511. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11512. * In this case, we will exit very soon, no need to free(). */
  11513. /* if (trap_ptr != trap && tp[0]) */
  11514. /* free(tr); */
  11515. }
  11516. }
  11517. /*
  11518. if (trap_ptr != trap) {
  11519. free(trap_ptr);
  11520. trap_ptr = trap;
  11521. }
  11522. */
  11523. return 0;
  11524. }
  11525. action = NULL;
  11526. if (ap[1])
  11527. action = *ap++;
  11528. exitcode = 0;
  11529. while (*ap) {
  11530. signo = get_signum(*ap);
  11531. if (signo < 0) {
  11532. /* Mimic bash message exactly */
  11533. ash_msg("%s: invalid signal specification", *ap);
  11534. exitcode = 1;
  11535. goto next;
  11536. }
  11537. INT_OFF;
  11538. if (action) {
  11539. if (LONE_DASH(action))
  11540. action = NULL;
  11541. else
  11542. action = ckstrdup(action);
  11543. }
  11544. free(trap[signo]);
  11545. if (action)
  11546. may_have_traps = 1;
  11547. trap[signo] = action;
  11548. if (signo != 0)
  11549. setsignal(signo);
  11550. INT_ON;
  11551. next:
  11552. ap++;
  11553. }
  11554. return exitcode;
  11555. }
  11556. /* ============ Builtins */
  11557. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11558. /*
  11559. * Lists available builtins
  11560. */
  11561. static int FAST_FUNC
  11562. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11563. {
  11564. unsigned col;
  11565. unsigned i;
  11566. out1fmt(
  11567. "Built-in commands:\n"
  11568. "------------------\n");
  11569. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11570. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11571. builtintab[i].name + 1);
  11572. if (col > 60) {
  11573. out1fmt("\n");
  11574. col = 0;
  11575. }
  11576. }
  11577. #if ENABLE_FEATURE_SH_STANDALONE
  11578. {
  11579. const char *a = applet_names;
  11580. while (*a) {
  11581. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11582. if (col > 60) {
  11583. out1fmt("\n");
  11584. col = 0;
  11585. }
  11586. a += strlen(a) + 1;
  11587. }
  11588. }
  11589. #endif
  11590. out1fmt("\n\n");
  11591. return EXIT_SUCCESS;
  11592. }
  11593. #endif /* FEATURE_SH_EXTRA_QUIET */
  11594. /*
  11595. * The export and readonly commands.
  11596. */
  11597. static int FAST_FUNC
  11598. exportcmd(int argc UNUSED_PARAM, char **argv)
  11599. {
  11600. struct var *vp;
  11601. char *name;
  11602. const char *p;
  11603. char **aptr;
  11604. char opt;
  11605. int flag;
  11606. int flag_off;
  11607. /* "readonly" in bash accepts, but ignores -n.
  11608. * We do the same: it saves a conditional in nextopt's param.
  11609. */
  11610. flag_off = 0;
  11611. while ((opt = nextopt("np")) != '\0') {
  11612. if (opt == 'n')
  11613. flag_off = VEXPORT;
  11614. }
  11615. flag = VEXPORT;
  11616. if (argv[0][0] == 'r') {
  11617. flag = VREADONLY;
  11618. flag_off = 0; /* readonly ignores -n */
  11619. }
  11620. flag_off = ~flag_off;
  11621. /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
  11622. {
  11623. aptr = argptr;
  11624. name = *aptr;
  11625. if (name) {
  11626. do {
  11627. p = strchr(name, '=');
  11628. if (p != NULL) {
  11629. p++;
  11630. } else {
  11631. vp = *findvar(hashvar(name), name);
  11632. if (vp) {
  11633. vp->flags = ((vp->flags | flag) & flag_off);
  11634. continue;
  11635. }
  11636. }
  11637. setvar(name, p, (flag & flag_off));
  11638. } while ((name = *++aptr) != NULL);
  11639. return 0;
  11640. }
  11641. }
  11642. /* No arguments. Show the list of exported or readonly vars.
  11643. * -n is ignored.
  11644. */
  11645. showvars(argv[0], flag, 0);
  11646. return 0;
  11647. }
  11648. /*
  11649. * Delete a function if it exists.
  11650. */
  11651. static void
  11652. unsetfunc(const char *name)
  11653. {
  11654. struct tblentry *cmdp;
  11655. cmdp = cmdlookup(name, 0);
  11656. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  11657. delete_cmd_entry();
  11658. }
  11659. /*
  11660. * The unset builtin command. We unset the function before we unset the
  11661. * variable to allow a function to be unset when there is a readonly variable
  11662. * with the same name.
  11663. */
  11664. static int FAST_FUNC
  11665. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11666. {
  11667. char **ap;
  11668. int i;
  11669. int flag = 0;
  11670. int ret = 0;
  11671. while ((i = nextopt("vf")) != 0) {
  11672. flag = i;
  11673. }
  11674. for (ap = argptr; *ap; ap++) {
  11675. if (flag != 'f') {
  11676. i = unsetvar(*ap);
  11677. ret |= i;
  11678. if (!(i & 2))
  11679. continue;
  11680. }
  11681. if (flag != 'v')
  11682. unsetfunc(*ap);
  11683. }
  11684. return ret & 1;
  11685. }
  11686. static const unsigned char timescmd_str[] ALIGN1 = {
  11687. ' ', offsetof(struct tms, tms_utime),
  11688. '\n', offsetof(struct tms, tms_stime),
  11689. ' ', offsetof(struct tms, tms_cutime),
  11690. '\n', offsetof(struct tms, tms_cstime),
  11691. 0
  11692. };
  11693. static int FAST_FUNC
  11694. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11695. {
  11696. unsigned long clk_tck, s, t;
  11697. const unsigned char *p;
  11698. struct tms buf;
  11699. clk_tck = sysconf(_SC_CLK_TCK);
  11700. times(&buf);
  11701. p = timescmd_str;
  11702. do {
  11703. t = *(clock_t *)(((char *) &buf) + p[1]);
  11704. s = t / clk_tck;
  11705. t = t % clk_tck;
  11706. out1fmt("%lum%lu.%03lus%c",
  11707. s / 60, s % 60,
  11708. (t * 1000) / clk_tck,
  11709. p[0]);
  11710. p += 2;
  11711. } while (*p);
  11712. return 0;
  11713. }
  11714. #if ENABLE_SH_MATH_SUPPORT
  11715. /*
  11716. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  11717. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11718. *
  11719. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11720. */
  11721. static int FAST_FUNC
  11722. letcmd(int argc UNUSED_PARAM, char **argv)
  11723. {
  11724. arith_t i;
  11725. argv++;
  11726. if (!*argv)
  11727. ash_msg_and_raise_error("expression expected");
  11728. do {
  11729. i = ash_arith(*argv);
  11730. } while (*++argv);
  11731. return !i;
  11732. }
  11733. #endif
  11734. /*
  11735. * The read builtin. Options:
  11736. * -r Do not interpret '\' specially
  11737. * -s Turn off echo (tty only)
  11738. * -n NCHARS Read NCHARS max
  11739. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11740. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11741. * -u FD Read from given FD instead of fd 0
  11742. * This uses unbuffered input, which may be avoidable in some cases.
  11743. * TODO: bash also has:
  11744. * -a ARRAY Read into array[0],[1],etc
  11745. * -d DELIM End on DELIM char, not newline
  11746. * -e Use line editing (tty only)
  11747. */
  11748. static int FAST_FUNC
  11749. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11750. {
  11751. char *opt_n = NULL;
  11752. char *opt_p = NULL;
  11753. char *opt_t = NULL;
  11754. char *opt_u = NULL;
  11755. int read_flags = 0;
  11756. const char *r;
  11757. int i;
  11758. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11759. switch (i) {
  11760. case 'p':
  11761. opt_p = optionarg;
  11762. break;
  11763. case 'n':
  11764. opt_n = optionarg;
  11765. break;
  11766. case 's':
  11767. read_flags |= BUILTIN_READ_SILENT;
  11768. break;
  11769. case 't':
  11770. opt_t = optionarg;
  11771. break;
  11772. case 'r':
  11773. read_flags |= BUILTIN_READ_RAW;
  11774. break;
  11775. case 'u':
  11776. opt_u = optionarg;
  11777. break;
  11778. default:
  11779. break;
  11780. }
  11781. }
  11782. /* "read -s" needs to save/restore termios, can't allow ^C
  11783. * to jump out of it.
  11784. */
  11785. INT_OFF;
  11786. r = shell_builtin_read(setvar2,
  11787. argptr,
  11788. bltinlookup("IFS"), /* can be NULL */
  11789. read_flags,
  11790. opt_n,
  11791. opt_p,
  11792. opt_t,
  11793. opt_u
  11794. );
  11795. INT_ON;
  11796. if ((uintptr_t)r > 1)
  11797. ash_msg_and_raise_error(r);
  11798. return (uintptr_t)r;
  11799. }
  11800. static int FAST_FUNC
  11801. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11802. {
  11803. static const char permuser[3] ALIGN1 = "ugo";
  11804. static const char permmode[3] ALIGN1 = "rwx";
  11805. static const short permmask[] ALIGN2 = {
  11806. S_IRUSR, S_IWUSR, S_IXUSR,
  11807. S_IRGRP, S_IWGRP, S_IXGRP,
  11808. S_IROTH, S_IWOTH, S_IXOTH
  11809. };
  11810. /* TODO: use bb_parse_mode() instead */
  11811. char *ap;
  11812. mode_t mask;
  11813. int i;
  11814. int symbolic_mode = 0;
  11815. while (nextopt("S") != '\0') {
  11816. symbolic_mode = 1;
  11817. }
  11818. INT_OFF;
  11819. mask = umask(0);
  11820. umask(mask);
  11821. INT_ON;
  11822. ap = *argptr;
  11823. if (ap == NULL) {
  11824. if (symbolic_mode) {
  11825. char buf[18];
  11826. char *p = buf;
  11827. for (i = 0; i < 3; i++) {
  11828. int j;
  11829. *p++ = permuser[i];
  11830. *p++ = '=';
  11831. for (j = 0; j < 3; j++) {
  11832. if ((mask & permmask[3 * i + j]) == 0) {
  11833. *p++ = permmode[j];
  11834. }
  11835. }
  11836. *p++ = ',';
  11837. }
  11838. *--p = 0;
  11839. puts(buf);
  11840. } else {
  11841. out1fmt("%.4o\n", mask);
  11842. }
  11843. } else {
  11844. if (isdigit((unsigned char) *ap)) {
  11845. mask = 0;
  11846. do {
  11847. if (*ap >= '8' || *ap < '0')
  11848. ash_msg_and_raise_error(msg_illnum, argv[1]);
  11849. mask = (mask << 3) + (*ap - '0');
  11850. } while (*++ap != '\0');
  11851. umask(mask);
  11852. } else {
  11853. mask = ~mask & 0777;
  11854. if (!bb_parse_mode(ap, &mask)) {
  11855. ash_msg_and_raise_error("illegal mode: %s", ap);
  11856. }
  11857. umask(~mask & 0777);
  11858. }
  11859. }
  11860. return 0;
  11861. }
  11862. static int FAST_FUNC
  11863. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  11864. {
  11865. return shell_builtin_ulimit(argv);
  11866. }
  11867. /* ============ main() and helpers */
  11868. /*
  11869. * Called to exit the shell.
  11870. */
  11871. static void
  11872. exitshell(void)
  11873. {
  11874. struct jmploc loc;
  11875. char *p;
  11876. int status;
  11877. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  11878. save_history(line_input_state);
  11879. #endif
  11880. status = exitstatus;
  11881. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11882. if (setjmp(loc.loc)) {
  11883. if (exception_type == EXEXIT)
  11884. /* dash bug: it just does _exit(exitstatus) here
  11885. * but we have to do setjobctl(0) first!
  11886. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11887. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11888. status = exitstatus;
  11889. goto out;
  11890. }
  11891. exception_handler = &loc;
  11892. p = trap[0];
  11893. if (p) {
  11894. trap[0] = NULL;
  11895. evalstring(p, 0);
  11896. free(p);
  11897. }
  11898. flush_stdout_stderr();
  11899. out:
  11900. setjobctl(0);
  11901. _exit(status);
  11902. /* NOTREACHED */
  11903. }
  11904. static void
  11905. init(void)
  11906. {
  11907. /* from input.c: */
  11908. /* we will never free this */
  11909. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  11910. /* from trap.c: */
  11911. signal(SIGCHLD, SIG_DFL);
  11912. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11913. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11914. */
  11915. signal(SIGHUP, SIG_DFL);
  11916. /* from var.c: */
  11917. {
  11918. char **envp;
  11919. const char *p;
  11920. struct stat st1, st2;
  11921. initvar();
  11922. for (envp = environ; envp && *envp; envp++) {
  11923. if (strchr(*envp, '=')) {
  11924. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11925. }
  11926. }
  11927. setvar("PPID", utoa(getppid()), 0);
  11928. p = lookupvar("PWD");
  11929. if (p) {
  11930. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11931. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  11932. ) {
  11933. p = '\0';
  11934. }
  11935. }
  11936. setpwd(p, 0);
  11937. }
  11938. }
  11939. //usage:#define ash_trivial_usage
  11940. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  11941. //usage:#define ash_full_usage "\n\n"
  11942. //usage: "Unix shell interpreter"
  11943. //usage:#if ENABLE_FEATURE_SH_IS_ASH
  11944. //usage:# define sh_trivial_usage ash_trivial_usage
  11945. //usage:# define sh_full_usage ash_full_usage
  11946. //usage:#endif
  11947. //usage:#if ENABLE_FEATURE_BASH_IS_ASH
  11948. //usage:# define bash_trivial_usage ash_trivial_usage
  11949. //usage:# define bash_full_usage ash_full_usage
  11950. //usage:#endif
  11951. /*
  11952. * Process the shell command line arguments.
  11953. */
  11954. static void
  11955. procargs(char **argv)
  11956. {
  11957. int i;
  11958. const char *xminusc;
  11959. char **xargv;
  11960. xargv = argv;
  11961. arg0 = xargv[0];
  11962. /* if (xargv[0]) - mmm, this is always true! */
  11963. xargv++;
  11964. for (i = 0; i < NOPTS; i++)
  11965. optlist[i] = 2;
  11966. argptr = xargv;
  11967. if (options(/*cmdline:*/ 1)) {
  11968. /* it already printed err message */
  11969. raise_exception(EXERROR);
  11970. }
  11971. xargv = argptr;
  11972. xminusc = minusc;
  11973. if (*xargv == NULL) {
  11974. if (xminusc)
  11975. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11976. sflag = 1;
  11977. }
  11978. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11979. iflag = 1;
  11980. if (mflag == 2)
  11981. mflag = iflag;
  11982. for (i = 0; i < NOPTS; i++)
  11983. if (optlist[i] == 2)
  11984. optlist[i] = 0;
  11985. #if DEBUG == 2
  11986. debug = 1;
  11987. #endif
  11988. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11989. if (xminusc) {
  11990. minusc = *xargv++;
  11991. if (*xargv)
  11992. goto setarg0;
  11993. } else if (!sflag) {
  11994. setinputfile(*xargv, 0);
  11995. setarg0:
  11996. arg0 = *xargv++;
  11997. commandname = arg0;
  11998. }
  11999. shellparam.p = xargv;
  12000. #if ENABLE_ASH_GETOPTS
  12001. shellparam.optind = 1;
  12002. shellparam.optoff = -1;
  12003. #endif
  12004. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12005. while (*xargv) {
  12006. shellparam.nparam++;
  12007. xargv++;
  12008. }
  12009. optschanged();
  12010. }
  12011. /*
  12012. * Read /etc/profile or .profile.
  12013. */
  12014. static void
  12015. read_profile(const char *name)
  12016. {
  12017. int skip;
  12018. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12019. return;
  12020. skip = cmdloop(0);
  12021. popfile();
  12022. if (skip)
  12023. exitshell();
  12024. }
  12025. /*
  12026. * This routine is called when an error or an interrupt occurs in an
  12027. * interactive shell and control is returned to the main command loop.
  12028. */
  12029. static void
  12030. reset(void)
  12031. {
  12032. /* from eval.c: */
  12033. evalskip = 0;
  12034. loopnest = 0;
  12035. /* from input.c: */
  12036. g_parsefile->left_in_buffer = 0;
  12037. g_parsefile->left_in_line = 0; /* clear input buffer */
  12038. popallfiles();
  12039. /* from parser.c: */
  12040. tokpushback = 0;
  12041. checkkwd = 0;
  12042. /* from redir.c: */
  12043. clearredir(/*drop:*/ 0);
  12044. }
  12045. #if PROFILE
  12046. static short profile_buf[16384];
  12047. extern int etext();
  12048. #endif
  12049. /*
  12050. * Main routine. We initialize things, parse the arguments, execute
  12051. * profiles if we're a login shell, and then call cmdloop to execute
  12052. * commands. The setjmp call sets up the location to jump to when an
  12053. * exception occurs. When an exception occurs the variable "state"
  12054. * is used to figure out how far we had gotten.
  12055. */
  12056. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12057. int ash_main(int argc UNUSED_PARAM, char **argv)
  12058. {
  12059. const char *shinit;
  12060. volatile smallint state;
  12061. struct jmploc jmploc;
  12062. struct stackmark smark;
  12063. /* Initialize global data */
  12064. INIT_G_misc();
  12065. INIT_G_memstack();
  12066. INIT_G_var();
  12067. #if ENABLE_ASH_ALIAS
  12068. INIT_G_alias();
  12069. #endif
  12070. INIT_G_cmdtable();
  12071. #if PROFILE
  12072. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12073. #endif
  12074. #if ENABLE_FEATURE_EDITING
  12075. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12076. #endif
  12077. state = 0;
  12078. if (setjmp(jmploc.loc)) {
  12079. smallint e;
  12080. smallint s;
  12081. reset();
  12082. e = exception_type;
  12083. if (e == EXERROR)
  12084. exitstatus = 2;
  12085. s = state;
  12086. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12087. exitshell();
  12088. }
  12089. if (e == EXINT) {
  12090. outcslow('\n', stderr);
  12091. }
  12092. popstackmark(&smark);
  12093. FORCE_INT_ON; /* enable interrupts */
  12094. if (s == 1)
  12095. goto state1;
  12096. if (s == 2)
  12097. goto state2;
  12098. if (s == 3)
  12099. goto state3;
  12100. goto state4;
  12101. }
  12102. exception_handler = &jmploc;
  12103. #if DEBUG
  12104. opentrace();
  12105. TRACE(("Shell args: "));
  12106. trace_puts_args(argv);
  12107. #endif
  12108. rootpid = getpid();
  12109. init();
  12110. setstackmark(&smark);
  12111. procargs(argv);
  12112. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12113. if (iflag) {
  12114. const char *hp = lookupvar("HISTFILE");
  12115. if (!hp) {
  12116. hp = lookupvar("HOME");
  12117. if (hp) {
  12118. char *defhp = concat_path_file(hp, ".ash_history");
  12119. setvar("HISTFILE", defhp, 0);
  12120. free(defhp);
  12121. }
  12122. }
  12123. }
  12124. #endif
  12125. if (argv[0] && argv[0][0] == '-')
  12126. isloginsh = 1;
  12127. if (isloginsh) {
  12128. state = 1;
  12129. read_profile("/etc/profile");
  12130. state1:
  12131. state = 2;
  12132. read_profile(".profile");
  12133. }
  12134. state2:
  12135. state = 3;
  12136. if (
  12137. #ifndef linux
  12138. getuid() == geteuid() && getgid() == getegid() &&
  12139. #endif
  12140. iflag
  12141. ) {
  12142. shinit = lookupvar("ENV");
  12143. if (shinit != NULL && *shinit != '\0') {
  12144. read_profile(shinit);
  12145. }
  12146. }
  12147. state3:
  12148. state = 4;
  12149. if (minusc) {
  12150. /* evalstring pushes parsefile stack.
  12151. * Ensure we don't falsely claim that 0 (stdin)
  12152. * is one of stacked source fds.
  12153. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12154. // if (!sflag) g_parsefile->pf_fd = -1;
  12155. // ^^ not necessary since now we special-case fd 0
  12156. // in is_hidden_fd() to not be considered "hidden fd"
  12157. evalstring(minusc, 0);
  12158. }
  12159. if (sflag || minusc == NULL) {
  12160. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12161. if (iflag) {
  12162. const char *hp = lookupvar("HISTFILE");
  12163. if (hp)
  12164. line_input_state->hist_file = hp;
  12165. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12166. hp = lookupvar("HISTFILESIZE");
  12167. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12168. # endif
  12169. }
  12170. #endif
  12171. state4: /* XXX ??? - why isn't this before the "if" statement */
  12172. cmdloop(1);
  12173. }
  12174. #if PROFILE
  12175. monitor(0);
  12176. #endif
  12177. #ifdef GPROF
  12178. {
  12179. extern void _mcleanup(void);
  12180. _mcleanup();
  12181. }
  12182. #endif
  12183. TRACE(("End of main reached\n"));
  12184. exitshell();
  12185. /* NOTREACHED */
  12186. }
  12187. /*-
  12188. * Copyright (c) 1989, 1991, 1993, 1994
  12189. * The Regents of the University of California. All rights reserved.
  12190. *
  12191. * This code is derived from software contributed to Berkeley by
  12192. * Kenneth Almquist.
  12193. *
  12194. * Redistribution and use in source and binary forms, with or without
  12195. * modification, are permitted provided that the following conditions
  12196. * are met:
  12197. * 1. Redistributions of source code must retain the above copyright
  12198. * notice, this list of conditions and the following disclaimer.
  12199. * 2. Redistributions in binary form must reproduce the above copyright
  12200. * notice, this list of conditions and the following disclaimer in the
  12201. * documentation and/or other materials provided with the distribution.
  12202. * 3. Neither the name of the University nor the names of its contributors
  12203. * may be used to endorse or promote products derived from this software
  12204. * without specific prior written permission.
  12205. *
  12206. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12207. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12208. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12209. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12210. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12211. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12212. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12213. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12214. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12215. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12216. * SUCH DAMAGE.
  12217. */