ash.c 293 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302
  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 <setjmp.h>
  37. #include <fnmatch.h>
  38. #include <sys/times.h>
  39. #include <sys/utsname.h> /* for setting $HOSTNAME */
  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_HELP
  136. //config: bool "help builtin"
  137. //config: default y
  138. //config: depends on ASH
  139. //config: help
  140. //config: Enable help builtin in ash.
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "'command' command to override shell builtins"
  144. //config: default y
  145. //config: depends on ASH
  146. //config: help
  147. //config: Enable support for the ash 'command' builtin, which allows
  148. //config: you to run the specified command with the specified arguments,
  149. //config: even when there is an ash builtin command with the same name.
  150. //config:
  151. //config:config ASH_MAIL
  152. //config: bool "Check for new mail on interactive shells"
  153. //config: default n
  154. //config: depends on ASH
  155. //config: help
  156. //config: Enable "check for new mail" function in the ash shell.
  157. //config:
  158. //config:config ASH_OPTIMIZE_FOR_SIZE
  159. //config: bool "Optimize for size instead of speed"
  160. //config: default y
  161. //config: depends on ASH
  162. //config: help
  163. //config: Compile ash for reduced size at the price of speed.
  164. //config:
  165. //config:config ASH_RANDOM_SUPPORT
  166. //config: bool "Pseudorandom generator and $RANDOM variable"
  167. //config: default y
  168. //config: depends on ASH
  169. //config: help
  170. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  171. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  172. //config: You can reset the generator by using a specified start value.
  173. //config: After "unset RANDOM" the generator will switch off and this
  174. //config: variable will no longer have special treatment.
  175. //config:
  176. //config:config ASH_EXPAND_PRMT
  177. //config: bool "Expand prompt string"
  178. //config: default y
  179. //config: depends on ASH
  180. //config: help
  181. //config: "PS#" may contain volatile content, such as backquote commands.
  182. //config: This option recreates the prompt string from the environment
  183. //config: variable each time it is displayed.
  184. //config:
  185. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  186. //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
  187. //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
  188. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  189. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  190. /* ============ Hash table sizes. Configurable. */
  191. #define VTABSIZE 39
  192. #define ATABSIZE 39
  193. #define CMDTABLESIZE 31 /* should be prime */
  194. /* ============ Shell options */
  195. static const char *const optletters_optnames[] = {
  196. "e" "errexit",
  197. "f" "noglob",
  198. "I" "ignoreeof",
  199. "i" "interactive",
  200. "m" "monitor",
  201. "n" "noexec",
  202. "s" "stdin",
  203. "x" "xtrace",
  204. "v" "verbose",
  205. "C" "noclobber",
  206. "a" "allexport",
  207. "b" "notify",
  208. "u" "nounset",
  209. "\0" "vi"
  210. #if ENABLE_ASH_BASH_COMPAT
  211. ,"\0" "pipefail"
  212. #endif
  213. #if DEBUG
  214. ,"\0" "nolog"
  215. ,"\0" "debug"
  216. #endif
  217. };
  218. #define optletters(n) optletters_optnames[n][0]
  219. #define optnames(n) (optletters_optnames[n] + 1)
  220. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  221. /* ============ Misc data */
  222. #define msg_illnum "Illegal number: %s"
  223. /*
  224. * We enclose jmp_buf in a structure so that we can declare pointers to
  225. * jump locations. The global variable handler contains the location to
  226. * jump to when an exception occurs, and the global variable exception_type
  227. * contains a code identifying the exception. To implement nested
  228. * exception handlers, the user should save the value of handler on entry
  229. * to an inner scope, set handler to point to a jmploc structure for the
  230. * inner scope, and restore handler on exit from the scope.
  231. */
  232. struct jmploc {
  233. jmp_buf loc;
  234. };
  235. struct globals_misc {
  236. /* pid of main shell */
  237. int rootpid;
  238. /* shell level: 0 for the main shell, 1 for its children, and so on */
  239. int shlvl;
  240. #define rootshell (!shlvl)
  241. char *minusc; /* argument to -c option */
  242. char *curdir; // = nullstr; /* current working directory */
  243. char *physdir; // = nullstr; /* physical working directory */
  244. char *arg0; /* value of $0 */
  245. struct jmploc *exception_handler;
  246. volatile int suppress_int; /* counter */
  247. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  248. /* last pending signal */
  249. volatile /*sig_atomic_t*/ smallint pending_sig;
  250. smallint exception_type; /* kind of exception (0..5) */
  251. /* exceptions */
  252. #define EXINT 0 /* SIGINT received */
  253. #define EXERROR 1 /* a generic error */
  254. #define EXSHELLPROC 2 /* execute a shell procedure */
  255. #define EXEXEC 3 /* command execution failed */
  256. #define EXEXIT 4 /* exit the shell */
  257. #define EXSIG 5 /* trapped signal in wait(1) */
  258. smallint isloginsh;
  259. char nullstr[1]; /* zero length string */
  260. char optlist[NOPTS];
  261. #define eflag optlist[0]
  262. #define fflag optlist[1]
  263. #define Iflag optlist[2]
  264. #define iflag optlist[3]
  265. #define mflag optlist[4]
  266. #define nflag optlist[5]
  267. #define sflag optlist[6]
  268. #define xflag optlist[7]
  269. #define vflag optlist[8]
  270. #define Cflag optlist[9]
  271. #define aflag optlist[10]
  272. #define bflag optlist[11]
  273. #define uflag optlist[12]
  274. #define viflag optlist[13]
  275. #if ENABLE_ASH_BASH_COMPAT
  276. # define pipefail optlist[14]
  277. #else
  278. # define pipefail 0
  279. #endif
  280. #if DEBUG
  281. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  282. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  283. #endif
  284. /* trap handler commands */
  285. /*
  286. * Sigmode records the current value of the signal handlers for the various
  287. * modes. A value of zero means that the current handler is not known.
  288. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  289. */
  290. char sigmode[NSIG - 1];
  291. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  292. #define S_CATCH 2 /* signal is caught */
  293. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  294. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  295. /* indicates specified signal received */
  296. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  297. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  298. char *trap[NSIG];
  299. char **trap_ptr; /* used only by "trap hack" */
  300. /* Rarely referenced stuff */
  301. #if ENABLE_ASH_RANDOM_SUPPORT
  302. random_t random_gen;
  303. #endif
  304. pid_t backgndpid; /* pid of last background process */
  305. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  306. };
  307. extern struct globals_misc *const ash_ptr_to_globals_misc;
  308. #define G_misc (*ash_ptr_to_globals_misc)
  309. #define rootpid (G_misc.rootpid )
  310. #define shlvl (G_misc.shlvl )
  311. #define minusc (G_misc.minusc )
  312. #define curdir (G_misc.curdir )
  313. #define physdir (G_misc.physdir )
  314. #define arg0 (G_misc.arg0 )
  315. #define exception_handler (G_misc.exception_handler)
  316. #define exception_type (G_misc.exception_type )
  317. #define suppress_int (G_misc.suppress_int )
  318. #define pending_int (G_misc.pending_int )
  319. #define pending_sig (G_misc.pending_sig )
  320. #define isloginsh (G_misc.isloginsh )
  321. #define nullstr (G_misc.nullstr )
  322. #define optlist (G_misc.optlist )
  323. #define sigmode (G_misc.sigmode )
  324. #define gotsig (G_misc.gotsig )
  325. #define may_have_traps (G_misc.may_have_traps )
  326. #define trap (G_misc.trap )
  327. #define trap_ptr (G_misc.trap_ptr )
  328. #define random_gen (G_misc.random_gen )
  329. #define backgndpid (G_misc.backgndpid )
  330. #define job_warning (G_misc.job_warning)
  331. #define INIT_G_misc() do { \
  332. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  333. barrier(); \
  334. curdir = nullstr; \
  335. physdir = nullstr; \
  336. trap_ptr = trap; \
  337. } while (0)
  338. /* ============ DEBUG */
  339. #if DEBUG
  340. static void trace_printf(const char *fmt, ...);
  341. static void trace_vprintf(const char *fmt, va_list va);
  342. # define TRACE(param) trace_printf param
  343. # define TRACEV(param) trace_vprintf param
  344. # define close(fd) do { \
  345. int dfd = (fd); \
  346. if (close(dfd) < 0) \
  347. bb_error_msg("bug on %d: closing %d(0x%x)", \
  348. __LINE__, dfd, dfd); \
  349. } while (0)
  350. #else
  351. # define TRACE(param)
  352. # define TRACEV(param)
  353. #endif
  354. /* ============ Utility functions */
  355. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  356. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  357. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  358. static int isdigit_str9(const char *str)
  359. {
  360. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  361. while (--maxlen && isdigit(*str))
  362. str++;
  363. return (*str == '\0');
  364. }
  365. static const char *var_end(const char *var)
  366. {
  367. while (*var)
  368. if (*var++ == '=')
  369. break;
  370. return var;
  371. }
  372. /* ============ Interrupts / exceptions */
  373. static void exitshell(void) NORETURN;
  374. /*
  375. * These macros allow the user to suspend the handling of interrupt signals
  376. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  377. * much more efficient and portable. (But hacking the kernel is so much
  378. * more fun than worrying about efficiency and portability. :-))
  379. */
  380. #define INT_OFF do { \
  381. suppress_int++; \
  382. xbarrier(); \
  383. } while (0)
  384. /*
  385. * Called to raise an exception. Since C doesn't include exceptions, we
  386. * just do a longjmp to the exception handler. The type of exception is
  387. * stored in the global variable "exception_type".
  388. */
  389. static void raise_exception(int) NORETURN;
  390. static void
  391. raise_exception(int e)
  392. {
  393. #if DEBUG
  394. if (exception_handler == NULL)
  395. abort();
  396. #endif
  397. INT_OFF;
  398. exception_type = e;
  399. longjmp(exception_handler->loc, 1);
  400. }
  401. #if DEBUG
  402. #define raise_exception(e) do { \
  403. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  404. raise_exception(e); \
  405. } while (0)
  406. #endif
  407. /*
  408. * Called from trap.c when a SIGINT is received. (If the user specifies
  409. * that SIGINT is to be trapped or ignored using the trap builtin, then
  410. * this routine is not called.) Suppressint is nonzero when interrupts
  411. * are held using the INT_OFF macro. (The test for iflag is just
  412. * defensive programming.)
  413. */
  414. static void raise_interrupt(void) NORETURN;
  415. static void
  416. raise_interrupt(void)
  417. {
  418. int ex_type;
  419. pending_int = 0;
  420. /* Signal is not automatically unmasked after it is raised,
  421. * do it ourself - unmask all signals */
  422. sigprocmask_allsigs(SIG_UNBLOCK);
  423. /* pending_sig = 0; - now done in signal_handler() */
  424. ex_type = EXSIG;
  425. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  426. if (!(rootshell && iflag)) {
  427. /* Kill ourself with SIGINT */
  428. signal(SIGINT, SIG_DFL);
  429. raise(SIGINT);
  430. }
  431. ex_type = EXINT;
  432. }
  433. raise_exception(ex_type);
  434. /* NOTREACHED */
  435. }
  436. #if DEBUG
  437. #define raise_interrupt() do { \
  438. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  439. raise_interrupt(); \
  440. } while (0)
  441. #endif
  442. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  443. int_on(void)
  444. {
  445. xbarrier();
  446. if (--suppress_int == 0 && pending_int) {
  447. raise_interrupt();
  448. }
  449. }
  450. #define INT_ON int_on()
  451. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  452. force_int_on(void)
  453. {
  454. xbarrier();
  455. suppress_int = 0;
  456. if (pending_int)
  457. raise_interrupt();
  458. }
  459. #define FORCE_INT_ON force_int_on()
  460. #define SAVE_INT(v) ((v) = suppress_int)
  461. #define RESTORE_INT(v) do { \
  462. xbarrier(); \
  463. suppress_int = (v); \
  464. if (suppress_int == 0 && pending_int) \
  465. raise_interrupt(); \
  466. } while (0)
  467. /* ============ Stdout/stderr output */
  468. static void
  469. outstr(const char *p, FILE *file)
  470. {
  471. INT_OFF;
  472. fputs(p, file);
  473. INT_ON;
  474. }
  475. static void
  476. flush_stdout_stderr(void)
  477. {
  478. INT_OFF;
  479. fflush_all();
  480. INT_ON;
  481. }
  482. /* Was called outcslow(c,FILE*), but c was always '\n' */
  483. static void
  484. newline_and_flush(FILE *dest)
  485. {
  486. INT_OFF;
  487. putc('\n', dest);
  488. fflush(dest);
  489. INT_ON;
  490. }
  491. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  492. static int
  493. out1fmt(const char *fmt, ...)
  494. {
  495. va_list ap;
  496. int r;
  497. INT_OFF;
  498. va_start(ap, fmt);
  499. r = vprintf(fmt, ap);
  500. va_end(ap);
  501. INT_ON;
  502. return r;
  503. }
  504. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  505. static int
  506. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  507. {
  508. va_list ap;
  509. int ret;
  510. va_start(ap, fmt);
  511. INT_OFF;
  512. ret = vsnprintf(outbuf, length, fmt, ap);
  513. va_end(ap);
  514. INT_ON;
  515. return ret;
  516. }
  517. static void
  518. out1str(const char *p)
  519. {
  520. outstr(p, stdout);
  521. }
  522. static void
  523. out2str(const char *p)
  524. {
  525. outstr(p, stderr);
  526. flush_stdout_stderr();
  527. }
  528. /* ============ Parser structures */
  529. /* control characters in argument strings */
  530. #define CTL_FIRST CTLESC
  531. #define CTLESC ((unsigned char)'\201') /* escape next character */
  532. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  533. #define CTLENDVAR ((unsigned char)'\203')
  534. #define CTLBACKQ ((unsigned char)'\204')
  535. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  536. #define CTLENDARI ((unsigned char)'\207')
  537. #define CTLQUOTEMARK ((unsigned char)'\210')
  538. #define CTL_LAST CTLQUOTEMARK
  539. /* variable substitution byte (follows CTLVAR) */
  540. #define VSTYPE 0x0f /* type of variable substitution */
  541. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  542. /* values of VSTYPE field */
  543. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  544. #define VSMINUS 0x2 /* ${var-text} */
  545. #define VSPLUS 0x3 /* ${var+text} */
  546. #define VSQUESTION 0x4 /* ${var?message} */
  547. #define VSASSIGN 0x5 /* ${var=text} */
  548. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  549. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  550. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  551. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  552. #define VSLENGTH 0xa /* ${#var} */
  553. #if ENABLE_ASH_BASH_COMPAT
  554. #define VSSUBSTR 0xc /* ${var:position:length} */
  555. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  556. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  557. #endif
  558. static const char dolatstr[] ALIGN1 = {
  559. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  560. };
  561. #define DOLATSTRLEN 6
  562. #define NCMD 0
  563. #define NPIPE 1
  564. #define NREDIR 2
  565. #define NBACKGND 3
  566. #define NSUBSHELL 4
  567. #define NAND 5
  568. #define NOR 6
  569. #define NSEMI 7
  570. #define NIF 8
  571. #define NWHILE 9
  572. #define NUNTIL 10
  573. #define NFOR 11
  574. #define NCASE 12
  575. #define NCLIST 13
  576. #define NDEFUN 14
  577. #define NARG 15
  578. #define NTO 16
  579. #if ENABLE_ASH_BASH_COMPAT
  580. #define NTO2 17
  581. #endif
  582. #define NCLOBBER 18
  583. #define NFROM 19
  584. #define NFROMTO 20
  585. #define NAPPEND 21
  586. #define NTOFD 22
  587. #define NFROMFD 23
  588. #define NHERE 24
  589. #define NXHERE 25
  590. #define NNOT 26
  591. #define N_NUMBER 27
  592. union node;
  593. struct ncmd {
  594. smallint type; /* Nxxxx */
  595. union node *assign;
  596. union node *args;
  597. union node *redirect;
  598. };
  599. struct npipe {
  600. smallint type;
  601. smallint pipe_backgnd;
  602. struct nodelist *cmdlist;
  603. };
  604. struct nredir {
  605. smallint type;
  606. union node *n;
  607. union node *redirect;
  608. };
  609. struct nbinary {
  610. smallint type;
  611. union node *ch1;
  612. union node *ch2;
  613. };
  614. struct nif {
  615. smallint type;
  616. union node *test;
  617. union node *ifpart;
  618. union node *elsepart;
  619. };
  620. struct nfor {
  621. smallint type;
  622. union node *args;
  623. union node *body;
  624. char *var;
  625. };
  626. struct ncase {
  627. smallint type;
  628. union node *expr;
  629. union node *cases;
  630. };
  631. struct nclist {
  632. smallint type;
  633. union node *next;
  634. union node *pattern;
  635. union node *body;
  636. };
  637. struct narg {
  638. smallint type;
  639. union node *next;
  640. char *text;
  641. struct nodelist *backquote;
  642. };
  643. /* nfile and ndup layout must match!
  644. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  645. * that it is actually NTO2 (>&file), and change its type.
  646. */
  647. struct nfile {
  648. smallint type;
  649. union node *next;
  650. int fd;
  651. int _unused_dupfd;
  652. union node *fname;
  653. char *expfname;
  654. };
  655. struct ndup {
  656. smallint type;
  657. union node *next;
  658. int fd;
  659. int dupfd;
  660. union node *vname;
  661. char *_unused_expfname;
  662. };
  663. struct nhere {
  664. smallint type;
  665. union node *next;
  666. int fd;
  667. union node *doc;
  668. };
  669. struct nnot {
  670. smallint type;
  671. union node *com;
  672. };
  673. union node {
  674. smallint type;
  675. struct ncmd ncmd;
  676. struct npipe npipe;
  677. struct nredir nredir;
  678. struct nbinary nbinary;
  679. struct nif nif;
  680. struct nfor nfor;
  681. struct ncase ncase;
  682. struct nclist nclist;
  683. struct narg narg;
  684. struct nfile nfile;
  685. struct ndup ndup;
  686. struct nhere nhere;
  687. struct nnot nnot;
  688. };
  689. /*
  690. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  691. * It must be distinct from NULL.
  692. */
  693. #define NODE_EOF ((union node *) -1L)
  694. struct nodelist {
  695. struct nodelist *next;
  696. union node *n;
  697. };
  698. struct funcnode {
  699. int count;
  700. union node n;
  701. };
  702. /*
  703. * Free a parse tree.
  704. */
  705. static void
  706. freefunc(struct funcnode *f)
  707. {
  708. if (f && --f->count < 0)
  709. free(f);
  710. }
  711. /* ============ Debugging output */
  712. #if DEBUG
  713. static FILE *tracefile;
  714. static void
  715. trace_printf(const char *fmt, ...)
  716. {
  717. va_list va;
  718. if (debug != 1)
  719. return;
  720. if (DEBUG_TIME)
  721. fprintf(tracefile, "%u ", (int) time(NULL));
  722. if (DEBUG_PID)
  723. fprintf(tracefile, "[%u] ", (int) getpid());
  724. if (DEBUG_SIG)
  725. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  726. va_start(va, fmt);
  727. vfprintf(tracefile, fmt, va);
  728. va_end(va);
  729. }
  730. static void
  731. trace_vprintf(const char *fmt, va_list va)
  732. {
  733. if (debug != 1)
  734. return;
  735. if (DEBUG_TIME)
  736. fprintf(tracefile, "%u ", (int) time(NULL));
  737. if (DEBUG_PID)
  738. fprintf(tracefile, "[%u] ", (int) getpid());
  739. if (DEBUG_SIG)
  740. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  741. vfprintf(tracefile, fmt, va);
  742. }
  743. static void
  744. trace_puts(const char *s)
  745. {
  746. if (debug != 1)
  747. return;
  748. fputs(s, tracefile);
  749. }
  750. static void
  751. trace_puts_quoted(char *s)
  752. {
  753. char *p;
  754. char c;
  755. if (debug != 1)
  756. return;
  757. putc('"', tracefile);
  758. for (p = s; *p; p++) {
  759. switch ((unsigned char)*p) {
  760. case '\n': c = 'n'; goto backslash;
  761. case '\t': c = 't'; goto backslash;
  762. case '\r': c = 'r'; goto backslash;
  763. case '\"': c = '\"'; goto backslash;
  764. case '\\': c = '\\'; goto backslash;
  765. case CTLESC: c = 'e'; goto backslash;
  766. case CTLVAR: c = 'v'; goto backslash;
  767. case CTLBACKQ: c = 'q'; goto backslash;
  768. backslash:
  769. putc('\\', tracefile);
  770. putc(c, tracefile);
  771. break;
  772. default:
  773. if (*p >= ' ' && *p <= '~')
  774. putc(*p, tracefile);
  775. else {
  776. putc('\\', tracefile);
  777. putc((*p >> 6) & 03, tracefile);
  778. putc((*p >> 3) & 07, tracefile);
  779. putc(*p & 07, tracefile);
  780. }
  781. break;
  782. }
  783. }
  784. putc('"', tracefile);
  785. }
  786. static void
  787. trace_puts_args(char **ap)
  788. {
  789. if (debug != 1)
  790. return;
  791. if (!*ap)
  792. return;
  793. while (1) {
  794. trace_puts_quoted(*ap);
  795. if (!*++ap) {
  796. putc('\n', tracefile);
  797. break;
  798. }
  799. putc(' ', tracefile);
  800. }
  801. }
  802. static void
  803. opentrace(void)
  804. {
  805. char s[100];
  806. #ifdef O_APPEND
  807. int flags;
  808. #endif
  809. if (debug != 1) {
  810. if (tracefile)
  811. fflush(tracefile);
  812. /* leave open because libedit might be using it */
  813. return;
  814. }
  815. strcpy(s, "./trace");
  816. if (tracefile) {
  817. if (!freopen(s, "a", tracefile)) {
  818. fprintf(stderr, "Can't re-open %s\n", s);
  819. debug = 0;
  820. return;
  821. }
  822. } else {
  823. tracefile = fopen(s, "a");
  824. if (tracefile == NULL) {
  825. fprintf(stderr, "Can't open %s\n", s);
  826. debug = 0;
  827. return;
  828. }
  829. }
  830. #ifdef O_APPEND
  831. flags = fcntl(fileno(tracefile), F_GETFL);
  832. if (flags >= 0)
  833. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  834. #endif
  835. setlinebuf(tracefile);
  836. fputs("\nTracing started.\n", tracefile);
  837. }
  838. static void
  839. indent(int amount, char *pfx, FILE *fp)
  840. {
  841. int i;
  842. for (i = 0; i < amount; i++) {
  843. if (pfx && i == amount - 1)
  844. fputs(pfx, fp);
  845. putc('\t', fp);
  846. }
  847. }
  848. /* little circular references here... */
  849. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  850. static void
  851. sharg(union node *arg, FILE *fp)
  852. {
  853. char *p;
  854. struct nodelist *bqlist;
  855. unsigned char subtype;
  856. if (arg->type != NARG) {
  857. out1fmt("<node type %d>\n", arg->type);
  858. abort();
  859. }
  860. bqlist = arg->narg.backquote;
  861. for (p = arg->narg.text; *p; p++) {
  862. switch ((unsigned char)*p) {
  863. case CTLESC:
  864. p++;
  865. putc(*p, fp);
  866. break;
  867. case CTLVAR:
  868. putc('$', fp);
  869. putc('{', fp);
  870. subtype = *++p;
  871. if (subtype == VSLENGTH)
  872. putc('#', fp);
  873. while (*p != '=') {
  874. putc(*p, fp);
  875. p++;
  876. }
  877. if (subtype & VSNUL)
  878. putc(':', fp);
  879. switch (subtype & VSTYPE) {
  880. case VSNORMAL:
  881. putc('}', fp);
  882. break;
  883. case VSMINUS:
  884. putc('-', fp);
  885. break;
  886. case VSPLUS:
  887. putc('+', fp);
  888. break;
  889. case VSQUESTION:
  890. putc('?', fp);
  891. break;
  892. case VSASSIGN:
  893. putc('=', fp);
  894. break;
  895. case VSTRIMLEFT:
  896. putc('#', fp);
  897. break;
  898. case VSTRIMLEFTMAX:
  899. putc('#', fp);
  900. putc('#', fp);
  901. break;
  902. case VSTRIMRIGHT:
  903. putc('%', fp);
  904. break;
  905. case VSTRIMRIGHTMAX:
  906. putc('%', fp);
  907. putc('%', fp);
  908. break;
  909. case VSLENGTH:
  910. break;
  911. default:
  912. out1fmt("<subtype %d>", subtype);
  913. }
  914. break;
  915. case CTLENDVAR:
  916. putc('}', fp);
  917. break;
  918. case CTLBACKQ:
  919. putc('$', fp);
  920. putc('(', fp);
  921. shtree(bqlist->n, -1, NULL, fp);
  922. putc(')', fp);
  923. break;
  924. default:
  925. putc(*p, fp);
  926. break;
  927. }
  928. }
  929. }
  930. static void
  931. shcmd(union node *cmd, FILE *fp)
  932. {
  933. union node *np;
  934. int first;
  935. const char *s;
  936. int dftfd;
  937. first = 1;
  938. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  939. if (!first)
  940. putc(' ', fp);
  941. sharg(np, fp);
  942. first = 0;
  943. }
  944. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  945. if (!first)
  946. putc(' ', fp);
  947. dftfd = 0;
  948. switch (np->nfile.type) {
  949. case NTO: s = ">>"+1; dftfd = 1; break;
  950. case NCLOBBER: s = ">|"; dftfd = 1; break;
  951. case NAPPEND: s = ">>"; dftfd = 1; break;
  952. #if ENABLE_ASH_BASH_COMPAT
  953. case NTO2:
  954. #endif
  955. case NTOFD: s = ">&"; dftfd = 1; break;
  956. case NFROM: s = "<"; break;
  957. case NFROMFD: s = "<&"; break;
  958. case NFROMTO: s = "<>"; break;
  959. default: s = "*error*"; break;
  960. }
  961. if (np->nfile.fd != dftfd)
  962. fprintf(fp, "%d", np->nfile.fd);
  963. fputs(s, fp);
  964. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  965. fprintf(fp, "%d", np->ndup.dupfd);
  966. } else {
  967. sharg(np->nfile.fname, fp);
  968. }
  969. first = 0;
  970. }
  971. }
  972. static void
  973. shtree(union node *n, int ind, char *pfx, FILE *fp)
  974. {
  975. struct nodelist *lp;
  976. const char *s;
  977. if (n == NULL)
  978. return;
  979. indent(ind, pfx, fp);
  980. if (n == NODE_EOF) {
  981. fputs("<EOF>", fp);
  982. return;
  983. }
  984. switch (n->type) {
  985. case NSEMI:
  986. s = "; ";
  987. goto binop;
  988. case NAND:
  989. s = " && ";
  990. goto binop;
  991. case NOR:
  992. s = " || ";
  993. binop:
  994. shtree(n->nbinary.ch1, ind, NULL, fp);
  995. /* if (ind < 0) */
  996. fputs(s, fp);
  997. shtree(n->nbinary.ch2, ind, NULL, fp);
  998. break;
  999. case NCMD:
  1000. shcmd(n, fp);
  1001. if (ind >= 0)
  1002. putc('\n', fp);
  1003. break;
  1004. case NPIPE:
  1005. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1006. shtree(lp->n, 0, NULL, fp);
  1007. if (lp->next)
  1008. fputs(" | ", fp);
  1009. }
  1010. if (n->npipe.pipe_backgnd)
  1011. fputs(" &", fp);
  1012. if (ind >= 0)
  1013. putc('\n', fp);
  1014. break;
  1015. default:
  1016. fprintf(fp, "<node type %d>", n->type);
  1017. if (ind >= 0)
  1018. putc('\n', fp);
  1019. break;
  1020. }
  1021. }
  1022. static void
  1023. showtree(union node *n)
  1024. {
  1025. trace_puts("showtree called\n");
  1026. shtree(n, 1, NULL, stderr);
  1027. }
  1028. #endif /* DEBUG */
  1029. /* ============ Parser data */
  1030. /*
  1031. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1032. */
  1033. struct strlist {
  1034. struct strlist *next;
  1035. char *text;
  1036. };
  1037. struct alias;
  1038. struct strpush {
  1039. struct strpush *prev; /* preceding string on stack */
  1040. char *prev_string;
  1041. int prev_left_in_line;
  1042. #if ENABLE_ASH_ALIAS
  1043. struct alias *ap; /* if push was associated with an alias */
  1044. #endif
  1045. char *string; /* remember the string since it may change */
  1046. };
  1047. struct parsefile {
  1048. struct parsefile *prev; /* preceding file on stack */
  1049. int linno; /* current line */
  1050. int pf_fd; /* file descriptor (or -1 if string) */
  1051. int left_in_line; /* number of chars left in this line */
  1052. int left_in_buffer; /* number of chars left in this buffer past the line */
  1053. char *next_to_pgetc; /* next char in buffer */
  1054. char *buf; /* input buffer */
  1055. struct strpush *strpush; /* for pushing strings at this level */
  1056. struct strpush basestrpush; /* so pushing one is fast */
  1057. };
  1058. static struct parsefile basepf; /* top level input file */
  1059. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1060. static int startlinno; /* line # where last token started */
  1061. static char *commandname; /* currently executing command */
  1062. static struct strlist *cmdenviron; /* environment for builtin command */
  1063. static uint8_t exitstatus; /* exit status of last command */
  1064. /* ============ Message printing */
  1065. static void
  1066. ash_vmsg(const char *msg, va_list ap)
  1067. {
  1068. fprintf(stderr, "%s: ", arg0);
  1069. if (commandname) {
  1070. if (strcmp(arg0, commandname))
  1071. fprintf(stderr, "%s: ", commandname);
  1072. if (!iflag || g_parsefile->pf_fd > 0)
  1073. fprintf(stderr, "line %d: ", startlinno);
  1074. }
  1075. vfprintf(stderr, msg, ap);
  1076. newline_and_flush(stderr);
  1077. }
  1078. /*
  1079. * Exverror is called to raise the error exception. If the second argument
  1080. * is not NULL then error prints an error message using printf style
  1081. * formatting. It then raises the error exception.
  1082. */
  1083. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1084. static void
  1085. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1086. {
  1087. #if DEBUG
  1088. if (msg) {
  1089. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  1090. TRACEV((msg, ap));
  1091. TRACE(("\") pid=%d\n", getpid()));
  1092. } else
  1093. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  1094. if (msg)
  1095. #endif
  1096. ash_vmsg(msg, ap);
  1097. flush_stdout_stderr();
  1098. raise_exception(cond);
  1099. /* NOTREACHED */
  1100. }
  1101. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1102. static void
  1103. ash_msg_and_raise_error(const char *msg, ...)
  1104. {
  1105. va_list ap;
  1106. va_start(ap, msg);
  1107. ash_vmsg_and_raise(EXERROR, msg, ap);
  1108. /* NOTREACHED */
  1109. va_end(ap);
  1110. }
  1111. static void raise_error_syntax(const char *) NORETURN;
  1112. static void
  1113. raise_error_syntax(const char *msg)
  1114. {
  1115. ash_msg_and_raise_error("syntax error: %s", msg);
  1116. /* NOTREACHED */
  1117. }
  1118. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1119. static void
  1120. ash_msg_and_raise(int cond, const char *msg, ...)
  1121. {
  1122. va_list ap;
  1123. va_start(ap, msg);
  1124. ash_vmsg_and_raise(cond, msg, ap);
  1125. /* NOTREACHED */
  1126. va_end(ap);
  1127. }
  1128. /*
  1129. * error/warning routines for external builtins
  1130. */
  1131. static void
  1132. ash_msg(const char *fmt, ...)
  1133. {
  1134. va_list ap;
  1135. va_start(ap, fmt);
  1136. ash_vmsg(fmt, ap);
  1137. va_end(ap);
  1138. }
  1139. /*
  1140. * Return a string describing an error. The returned string may be a
  1141. * pointer to a static buffer that will be overwritten on the next call.
  1142. * Action describes the operation that got the error.
  1143. */
  1144. static const char *
  1145. errmsg(int e, const char *em)
  1146. {
  1147. if (e == ENOENT || e == ENOTDIR) {
  1148. return em;
  1149. }
  1150. return strerror(e);
  1151. }
  1152. /* ============ Memory allocation */
  1153. #if 0
  1154. /* I consider these wrappers nearly useless:
  1155. * ok, they return you to nearest exception handler, but
  1156. * how much memory do you leak in the process, making
  1157. * memory starvation worse?
  1158. */
  1159. static void *
  1160. ckrealloc(void * p, size_t nbytes)
  1161. {
  1162. p = realloc(p, nbytes);
  1163. if (!p)
  1164. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1165. return p;
  1166. }
  1167. static void *
  1168. ckmalloc(size_t nbytes)
  1169. {
  1170. return ckrealloc(NULL, nbytes);
  1171. }
  1172. static void *
  1173. ckzalloc(size_t nbytes)
  1174. {
  1175. return memset(ckmalloc(nbytes), 0, nbytes);
  1176. }
  1177. static char *
  1178. ckstrdup(const char *s)
  1179. {
  1180. char *p = strdup(s);
  1181. if (!p)
  1182. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1183. return p;
  1184. }
  1185. #else
  1186. /* Using bbox equivalents. They exit if out of memory */
  1187. # define ckrealloc xrealloc
  1188. # define ckmalloc xmalloc
  1189. # define ckzalloc xzalloc
  1190. # define ckstrdup xstrdup
  1191. #endif
  1192. /*
  1193. * It appears that grabstackstr() will barf with such alignments
  1194. * because stalloc() will return a string allocated in a new stackblock.
  1195. */
  1196. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1197. enum {
  1198. /* Most machines require the value returned from malloc to be aligned
  1199. * in some way. The following macro will get this right
  1200. * on many machines. */
  1201. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1202. /* Minimum size of a block */
  1203. MINSIZE = SHELL_ALIGN(504),
  1204. };
  1205. struct stack_block {
  1206. struct stack_block *prev;
  1207. char space[MINSIZE];
  1208. };
  1209. struct stackmark {
  1210. struct stack_block *stackp;
  1211. char *stacknxt;
  1212. size_t stacknleft;
  1213. struct stackmark *marknext;
  1214. };
  1215. struct globals_memstack {
  1216. struct stack_block *g_stackp; // = &stackbase;
  1217. struct stackmark *markp;
  1218. char *g_stacknxt; // = stackbase.space;
  1219. char *sstrend; // = stackbase.space + MINSIZE;
  1220. size_t g_stacknleft; // = MINSIZE;
  1221. int herefd; // = -1;
  1222. struct stack_block stackbase;
  1223. };
  1224. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1225. #define G_memstack (*ash_ptr_to_globals_memstack)
  1226. #define g_stackp (G_memstack.g_stackp )
  1227. #define markp (G_memstack.markp )
  1228. #define g_stacknxt (G_memstack.g_stacknxt )
  1229. #define sstrend (G_memstack.sstrend )
  1230. #define g_stacknleft (G_memstack.g_stacknleft)
  1231. #define herefd (G_memstack.herefd )
  1232. #define stackbase (G_memstack.stackbase )
  1233. #define INIT_G_memstack() do { \
  1234. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1235. barrier(); \
  1236. g_stackp = &stackbase; \
  1237. g_stacknxt = stackbase.space; \
  1238. g_stacknleft = MINSIZE; \
  1239. sstrend = stackbase.space + MINSIZE; \
  1240. herefd = -1; \
  1241. } while (0)
  1242. #define stackblock() ((void *)g_stacknxt)
  1243. #define stackblocksize() g_stacknleft
  1244. /*
  1245. * Parse trees for commands are allocated in lifo order, so we use a stack
  1246. * to make this more efficient, and also to avoid all sorts of exception
  1247. * handling code to handle interrupts in the middle of a parse.
  1248. *
  1249. * The size 504 was chosen because the Ultrix malloc handles that size
  1250. * well.
  1251. */
  1252. static void *
  1253. stalloc(size_t nbytes)
  1254. {
  1255. char *p;
  1256. size_t aligned;
  1257. aligned = SHELL_ALIGN(nbytes);
  1258. if (aligned > g_stacknleft) {
  1259. size_t len;
  1260. size_t blocksize;
  1261. struct stack_block *sp;
  1262. blocksize = aligned;
  1263. if (blocksize < MINSIZE)
  1264. blocksize = MINSIZE;
  1265. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1266. if (len < blocksize)
  1267. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1268. INT_OFF;
  1269. sp = ckmalloc(len);
  1270. sp->prev = g_stackp;
  1271. g_stacknxt = sp->space;
  1272. g_stacknleft = blocksize;
  1273. sstrend = g_stacknxt + blocksize;
  1274. g_stackp = sp;
  1275. INT_ON;
  1276. }
  1277. p = g_stacknxt;
  1278. g_stacknxt += aligned;
  1279. g_stacknleft -= aligned;
  1280. return p;
  1281. }
  1282. static void *
  1283. stzalloc(size_t nbytes)
  1284. {
  1285. return memset(stalloc(nbytes), 0, nbytes);
  1286. }
  1287. static void
  1288. stunalloc(void *p)
  1289. {
  1290. #if DEBUG
  1291. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1292. write(STDERR_FILENO, "stunalloc\n", 10);
  1293. abort();
  1294. }
  1295. #endif
  1296. g_stacknleft += g_stacknxt - (char *)p;
  1297. g_stacknxt = p;
  1298. }
  1299. /*
  1300. * Like strdup but works with the ash stack.
  1301. */
  1302. static char *
  1303. ststrdup(const char *p)
  1304. {
  1305. size_t len = strlen(p) + 1;
  1306. return memcpy(stalloc(len), p, len);
  1307. }
  1308. static void
  1309. setstackmark(struct stackmark *mark)
  1310. {
  1311. mark->stackp = g_stackp;
  1312. mark->stacknxt = g_stacknxt;
  1313. mark->stacknleft = g_stacknleft;
  1314. mark->marknext = markp;
  1315. markp = mark;
  1316. }
  1317. static void
  1318. popstackmark(struct stackmark *mark)
  1319. {
  1320. struct stack_block *sp;
  1321. if (!mark->stackp)
  1322. return;
  1323. INT_OFF;
  1324. markp = mark->marknext;
  1325. while (g_stackp != mark->stackp) {
  1326. sp = g_stackp;
  1327. g_stackp = sp->prev;
  1328. free(sp);
  1329. }
  1330. g_stacknxt = mark->stacknxt;
  1331. g_stacknleft = mark->stacknleft;
  1332. sstrend = mark->stacknxt + mark->stacknleft;
  1333. INT_ON;
  1334. }
  1335. /*
  1336. * When the parser reads in a string, it wants to stick the string on the
  1337. * stack and only adjust the stack pointer when it knows how big the
  1338. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1339. * of space on top of the stack and stackblocklen returns the length of
  1340. * this block. Growstackblock will grow this space by at least one byte,
  1341. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1342. * part of the block that has been used.
  1343. */
  1344. static void
  1345. growstackblock(void)
  1346. {
  1347. size_t newlen;
  1348. newlen = g_stacknleft * 2;
  1349. if (newlen < g_stacknleft)
  1350. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1351. if (newlen < 128)
  1352. newlen += 128;
  1353. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1354. struct stack_block *oldstackp;
  1355. struct stackmark *xmark;
  1356. struct stack_block *sp;
  1357. struct stack_block *prevstackp;
  1358. size_t grosslen;
  1359. INT_OFF;
  1360. oldstackp = g_stackp;
  1361. sp = g_stackp;
  1362. prevstackp = sp->prev;
  1363. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1364. sp = ckrealloc(sp, grosslen);
  1365. sp->prev = prevstackp;
  1366. g_stackp = sp;
  1367. g_stacknxt = sp->space;
  1368. g_stacknleft = newlen;
  1369. sstrend = sp->space + newlen;
  1370. /*
  1371. * Stack marks pointing to the start of the old block
  1372. * must be relocated to point to the new block
  1373. */
  1374. xmark = markp;
  1375. while (xmark != NULL && xmark->stackp == oldstackp) {
  1376. xmark->stackp = g_stackp;
  1377. xmark->stacknxt = g_stacknxt;
  1378. xmark->stacknleft = g_stacknleft;
  1379. xmark = xmark->marknext;
  1380. }
  1381. INT_ON;
  1382. } else {
  1383. char *oldspace = g_stacknxt;
  1384. size_t oldlen = g_stacknleft;
  1385. char *p = stalloc(newlen);
  1386. /* free the space we just allocated */
  1387. g_stacknxt = memcpy(p, oldspace, oldlen);
  1388. g_stacknleft += newlen;
  1389. }
  1390. }
  1391. static void
  1392. grabstackblock(size_t len)
  1393. {
  1394. len = SHELL_ALIGN(len);
  1395. g_stacknxt += len;
  1396. g_stacknleft -= len;
  1397. }
  1398. /*
  1399. * The following routines are somewhat easier to use than the above.
  1400. * The user declares a variable of type STACKSTR, which may be declared
  1401. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1402. * the user uses the macro STPUTC to add characters to the string. In
  1403. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1404. * grown as necessary. When the user is done, she can just leave the
  1405. * string there and refer to it using stackblock(). Or she can allocate
  1406. * the space for it using grabstackstr(). If it is necessary to allow
  1407. * someone else to use the stack temporarily and then continue to grow
  1408. * the string, the user should use grabstack to allocate the space, and
  1409. * then call ungrabstr(p) to return to the previous mode of operation.
  1410. *
  1411. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1412. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1413. * is space for at least one character.
  1414. */
  1415. static void *
  1416. growstackstr(void)
  1417. {
  1418. size_t len = stackblocksize();
  1419. if (herefd >= 0 && len >= 1024) {
  1420. full_write(herefd, stackblock(), len);
  1421. return stackblock();
  1422. }
  1423. growstackblock();
  1424. return (char *)stackblock() + len;
  1425. }
  1426. /*
  1427. * Called from CHECKSTRSPACE.
  1428. */
  1429. static char *
  1430. makestrspace(size_t newlen, char *p)
  1431. {
  1432. size_t len = p - g_stacknxt;
  1433. size_t size = stackblocksize();
  1434. for (;;) {
  1435. size_t nleft;
  1436. size = stackblocksize();
  1437. nleft = size - len;
  1438. if (nleft >= newlen)
  1439. break;
  1440. growstackblock();
  1441. }
  1442. return (char *)stackblock() + len;
  1443. }
  1444. static char *
  1445. stack_nputstr(const char *s, size_t n, char *p)
  1446. {
  1447. p = makestrspace(n, p);
  1448. p = (char *)memcpy(p, s, n) + n;
  1449. return p;
  1450. }
  1451. static char *
  1452. stack_putstr(const char *s, char *p)
  1453. {
  1454. return stack_nputstr(s, strlen(s), p);
  1455. }
  1456. static char *
  1457. _STPUTC(int c, char *p)
  1458. {
  1459. if (p == sstrend)
  1460. p = growstackstr();
  1461. *p++ = c;
  1462. return p;
  1463. }
  1464. #define STARTSTACKSTR(p) ((p) = stackblock())
  1465. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1466. #define CHECKSTRSPACE(n, p) do { \
  1467. char *q = (p); \
  1468. size_t l = (n); \
  1469. size_t m = sstrend - q; \
  1470. if (l > m) \
  1471. (p) = makestrspace(l, q); \
  1472. } while (0)
  1473. #define USTPUTC(c, p) (*(p)++ = (c))
  1474. #define STACKSTRNUL(p) do { \
  1475. if ((p) == sstrend) \
  1476. (p) = growstackstr(); \
  1477. *(p) = '\0'; \
  1478. } while (0)
  1479. #define STUNPUTC(p) (--(p))
  1480. #define STTOPC(p) ((p)[-1])
  1481. #define STADJUST(amount, p) ((p) += (amount))
  1482. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1483. #define ungrabstackstr(s, p) stunalloc(s)
  1484. #define stackstrend() ((void *)sstrend)
  1485. /* ============ String helpers */
  1486. /*
  1487. * prefix -- see if pfx is a prefix of string.
  1488. */
  1489. static char *
  1490. prefix(const char *string, const char *pfx)
  1491. {
  1492. while (*pfx) {
  1493. if (*pfx++ != *string++)
  1494. return NULL;
  1495. }
  1496. return (char *) string;
  1497. }
  1498. /*
  1499. * Check for a valid number. This should be elsewhere.
  1500. */
  1501. static int
  1502. is_number(const char *p)
  1503. {
  1504. do {
  1505. if (!isdigit(*p))
  1506. return 0;
  1507. } while (*++p != '\0');
  1508. return 1;
  1509. }
  1510. /*
  1511. * Convert a string of digits to an integer, printing an error message on
  1512. * failure.
  1513. */
  1514. static int
  1515. number(const char *s)
  1516. {
  1517. if (!is_number(s))
  1518. ash_msg_and_raise_error(msg_illnum, s);
  1519. return atoi(s);
  1520. }
  1521. /*
  1522. * Produce a possibly single quoted string suitable as input to the shell.
  1523. * The return string is allocated on the stack.
  1524. */
  1525. static char *
  1526. single_quote(const char *s)
  1527. {
  1528. char *p;
  1529. STARTSTACKSTR(p);
  1530. do {
  1531. char *q;
  1532. size_t len;
  1533. len = strchrnul(s, '\'') - s;
  1534. q = p = makestrspace(len + 3, p);
  1535. *q++ = '\'';
  1536. q = (char *)memcpy(q, s, len) + len;
  1537. *q++ = '\'';
  1538. s += len;
  1539. STADJUST(q - p, p);
  1540. if (*s != '\'')
  1541. break;
  1542. len = 0;
  1543. do len++; while (*++s == '\'');
  1544. q = p = makestrspace(len + 3, p);
  1545. *q++ = '"';
  1546. q = (char *)memcpy(q, s - len, len) + len;
  1547. *q++ = '"';
  1548. STADJUST(q - p, p);
  1549. } while (*s);
  1550. USTPUTC('\0', p);
  1551. return stackblock();
  1552. }
  1553. /* ============ nextopt */
  1554. static char **argptr; /* argument list for builtin commands */
  1555. static char *optionarg; /* set by nextopt (like getopt) */
  1556. static char *optptr; /* used by nextopt */
  1557. /*
  1558. * XXX - should get rid of. Have all builtins use getopt(3).
  1559. * The library getopt must have the BSD extension static variable
  1560. * "optreset", otherwise it can't be used within the shell safely.
  1561. *
  1562. * Standard option processing (a la getopt) for builtin routines.
  1563. * The only argument that is passed to nextopt is the option string;
  1564. * the other arguments are unnecessary. It returns the character,
  1565. * or '\0' on end of input.
  1566. */
  1567. static int
  1568. nextopt(const char *optstring)
  1569. {
  1570. char *p;
  1571. const char *q;
  1572. char c;
  1573. p = optptr;
  1574. if (p == NULL || *p == '\0') {
  1575. /* We ate entire "-param", take next one */
  1576. p = *argptr;
  1577. if (p == NULL)
  1578. return '\0';
  1579. if (*p != '-')
  1580. return '\0';
  1581. if (*++p == '\0') /* just "-" ? */
  1582. return '\0';
  1583. argptr++;
  1584. if (LONE_DASH(p)) /* "--" ? */
  1585. return '\0';
  1586. /* p => next "-param" */
  1587. }
  1588. /* p => some option char in the middle of a "-param" */
  1589. c = *p++;
  1590. for (q = optstring; *q != c;) {
  1591. if (*q == '\0')
  1592. ash_msg_and_raise_error("illegal option -%c", c);
  1593. if (*++q == ':')
  1594. q++;
  1595. }
  1596. if (*++q == ':') {
  1597. if (*p == '\0') {
  1598. p = *argptr++;
  1599. if (p == NULL)
  1600. ash_msg_and_raise_error("no arg for -%c option", c);
  1601. }
  1602. optionarg = p;
  1603. p = NULL;
  1604. }
  1605. optptr = p;
  1606. return c;
  1607. }
  1608. /* ============ Shell variables */
  1609. /*
  1610. * The parsefile structure pointed to by the global variable parsefile
  1611. * contains information about the current file being read.
  1612. */
  1613. struct shparam {
  1614. int nparam; /* # of positional parameters (without $0) */
  1615. #if ENABLE_ASH_GETOPTS
  1616. int optind; /* next parameter to be processed by getopts */
  1617. int optoff; /* used by getopts */
  1618. #endif
  1619. unsigned char malloced; /* if parameter list dynamically allocated */
  1620. char **p; /* parameter list */
  1621. };
  1622. /*
  1623. * Free the list of positional parameters.
  1624. */
  1625. static void
  1626. freeparam(volatile struct shparam *param)
  1627. {
  1628. if (param->malloced) {
  1629. char **ap, **ap1;
  1630. ap = ap1 = param->p;
  1631. while (*ap)
  1632. free(*ap++);
  1633. free(ap1);
  1634. }
  1635. }
  1636. #if ENABLE_ASH_GETOPTS
  1637. static void FAST_FUNC getoptsreset(const char *value);
  1638. #endif
  1639. struct var {
  1640. struct var *next; /* next entry in hash list */
  1641. int flags; /* flags are defined above */
  1642. const char *var_text; /* name=value */
  1643. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1644. /* the variable gets set/unset */
  1645. };
  1646. struct localvar {
  1647. struct localvar *next; /* next local variable in list */
  1648. struct var *vp; /* the variable that was made local */
  1649. int flags; /* saved flags */
  1650. const char *text; /* saved text */
  1651. };
  1652. /* flags */
  1653. #define VEXPORT 0x01 /* variable is exported */
  1654. #define VREADONLY 0x02 /* variable cannot be modified */
  1655. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1656. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1657. #define VSTACK 0x10 /* text is allocated on the stack */
  1658. #define VUNSET 0x20 /* the variable is not set */
  1659. #define VNOFUNC 0x40 /* don't call the callback function */
  1660. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1661. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1662. #if ENABLE_ASH_RANDOM_SUPPORT
  1663. # define VDYNAMIC 0x200 /* dynamic variable */
  1664. #else
  1665. # define VDYNAMIC 0
  1666. #endif
  1667. /* Need to be before varinit_data[] */
  1668. #if ENABLE_LOCALE_SUPPORT
  1669. static void FAST_FUNC
  1670. change_lc_all(const char *value)
  1671. {
  1672. if (value && *value != '\0')
  1673. setlocale(LC_ALL, value);
  1674. }
  1675. static void FAST_FUNC
  1676. change_lc_ctype(const char *value)
  1677. {
  1678. if (value && *value != '\0')
  1679. setlocale(LC_CTYPE, value);
  1680. }
  1681. #endif
  1682. #if ENABLE_ASH_MAIL
  1683. static void chkmail(void);
  1684. static void changemail(const char *var_value) FAST_FUNC;
  1685. #else
  1686. # define chkmail() ((void)0)
  1687. #endif
  1688. static void changepath(const char *) FAST_FUNC;
  1689. #if ENABLE_ASH_RANDOM_SUPPORT
  1690. static void change_random(const char *) FAST_FUNC;
  1691. #endif
  1692. static const struct {
  1693. int flags;
  1694. const char *var_text;
  1695. void (*var_func)(const char *) FAST_FUNC;
  1696. } varinit_data[] = {
  1697. /*
  1698. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1699. * some environment strings may be constant.
  1700. */
  1701. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1702. #if ENABLE_ASH_MAIL
  1703. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1704. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1705. #endif
  1706. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1707. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1708. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1709. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1710. #if ENABLE_ASH_GETOPTS
  1711. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1712. #endif
  1713. #if ENABLE_ASH_RANDOM_SUPPORT
  1714. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1715. #endif
  1716. #if ENABLE_LOCALE_SUPPORT
  1717. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1718. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1719. #endif
  1720. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1721. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1722. #endif
  1723. };
  1724. struct redirtab;
  1725. struct globals_var {
  1726. struct shparam shellparam; /* $@ current positional parameters */
  1727. struct redirtab *redirlist;
  1728. int g_nullredirs;
  1729. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1730. struct var *vartab[VTABSIZE];
  1731. struct var varinit[ARRAY_SIZE(varinit_data)];
  1732. };
  1733. extern struct globals_var *const ash_ptr_to_globals_var;
  1734. #define G_var (*ash_ptr_to_globals_var)
  1735. #define shellparam (G_var.shellparam )
  1736. //#define redirlist (G_var.redirlist )
  1737. #define g_nullredirs (G_var.g_nullredirs )
  1738. #define preverrout_fd (G_var.preverrout_fd)
  1739. #define vartab (G_var.vartab )
  1740. #define varinit (G_var.varinit )
  1741. #define INIT_G_var() do { \
  1742. unsigned i; \
  1743. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1744. barrier(); \
  1745. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1746. varinit[i].flags = varinit_data[i].flags; \
  1747. varinit[i].var_text = varinit_data[i].var_text; \
  1748. varinit[i].var_func = varinit_data[i].var_func; \
  1749. } \
  1750. } while (0)
  1751. #define vifs varinit[0]
  1752. #if ENABLE_ASH_MAIL
  1753. # define vmail (&vifs)[1]
  1754. # define vmpath (&vmail)[1]
  1755. # define vpath (&vmpath)[1]
  1756. #else
  1757. # define vpath (&vifs)[1]
  1758. #endif
  1759. #define vps1 (&vpath)[1]
  1760. #define vps2 (&vps1)[1]
  1761. #define vps4 (&vps2)[1]
  1762. #if ENABLE_ASH_GETOPTS
  1763. # define voptind (&vps4)[1]
  1764. # if ENABLE_ASH_RANDOM_SUPPORT
  1765. # define vrandom (&voptind)[1]
  1766. # endif
  1767. #else
  1768. # if ENABLE_ASH_RANDOM_SUPPORT
  1769. # define vrandom (&vps4)[1]
  1770. # endif
  1771. #endif
  1772. /*
  1773. * The following macros access the values of the above variables.
  1774. * They have to skip over the name. They return the null string
  1775. * for unset variables.
  1776. */
  1777. #define ifsval() (vifs.var_text + 4)
  1778. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1779. #if ENABLE_ASH_MAIL
  1780. # define mailval() (vmail.var_text + 5)
  1781. # define mpathval() (vmpath.var_text + 9)
  1782. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1783. #endif
  1784. #define pathval() (vpath.var_text + 5)
  1785. #define ps1val() (vps1.var_text + 4)
  1786. #define ps2val() (vps2.var_text + 4)
  1787. #define ps4val() (vps4.var_text + 4)
  1788. #if ENABLE_ASH_GETOPTS
  1789. # define optindval() (voptind.var_text + 7)
  1790. #endif
  1791. #if ENABLE_ASH_GETOPTS
  1792. static void FAST_FUNC
  1793. getoptsreset(const char *value)
  1794. {
  1795. shellparam.optind = number(value);
  1796. shellparam.optoff = -1;
  1797. }
  1798. #endif
  1799. /*
  1800. * Compares two strings up to the first = or '\0'. The first
  1801. * string must be terminated by '='; the second may be terminated by
  1802. * either '=' or '\0'.
  1803. */
  1804. static int
  1805. varcmp(const char *p, const char *q)
  1806. {
  1807. int c, d;
  1808. while ((c = *p) == (d = *q)) {
  1809. if (c == '\0' || c == '=')
  1810. goto out;
  1811. p++;
  1812. q++;
  1813. }
  1814. if (c == '=')
  1815. c = '\0';
  1816. if (d == '=')
  1817. d = '\0';
  1818. out:
  1819. return c - d;
  1820. }
  1821. /*
  1822. * Find the appropriate entry in the hash table from the name.
  1823. */
  1824. static struct var **
  1825. hashvar(const char *p)
  1826. {
  1827. unsigned hashval;
  1828. hashval = ((unsigned char) *p) << 4;
  1829. while (*p && *p != '=')
  1830. hashval += (unsigned char) *p++;
  1831. return &vartab[hashval % VTABSIZE];
  1832. }
  1833. static int
  1834. vpcmp(const void *a, const void *b)
  1835. {
  1836. return varcmp(*(const char **)a, *(const char **)b);
  1837. }
  1838. /*
  1839. * This routine initializes the builtin variables.
  1840. */
  1841. static void
  1842. initvar(void)
  1843. {
  1844. struct var *vp;
  1845. struct var *end;
  1846. struct var **vpp;
  1847. /*
  1848. * PS1 depends on uid
  1849. */
  1850. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1851. vps1.var_text = "PS1=\\w \\$ ";
  1852. #else
  1853. if (!geteuid())
  1854. vps1.var_text = "PS1=# ";
  1855. #endif
  1856. vp = varinit;
  1857. end = vp + ARRAY_SIZE(varinit);
  1858. do {
  1859. vpp = hashvar(vp->var_text);
  1860. vp->next = *vpp;
  1861. *vpp = vp;
  1862. } while (++vp < end);
  1863. }
  1864. static struct var **
  1865. findvar(struct var **vpp, const char *name)
  1866. {
  1867. for (; *vpp; vpp = &(*vpp)->next) {
  1868. if (varcmp((*vpp)->var_text, name) == 0) {
  1869. break;
  1870. }
  1871. }
  1872. return vpp;
  1873. }
  1874. /*
  1875. * Find the value of a variable. Returns NULL if not set.
  1876. */
  1877. static const char* FAST_FUNC
  1878. lookupvar(const char *name)
  1879. {
  1880. struct var *v;
  1881. v = *findvar(hashvar(name), name);
  1882. if (v) {
  1883. #if ENABLE_ASH_RANDOM_SUPPORT
  1884. /*
  1885. * Dynamic variables are implemented roughly the same way they are
  1886. * in bash. Namely, they're "special" so long as they aren't unset.
  1887. * As soon as they're unset, they're no longer dynamic, and dynamic
  1888. * lookup will no longer happen at that point. -- PFM.
  1889. */
  1890. if (v->flags & VDYNAMIC)
  1891. v->var_func(NULL);
  1892. #endif
  1893. if (!(v->flags & VUNSET))
  1894. return var_end(v->var_text);
  1895. }
  1896. return NULL;
  1897. }
  1898. static void reinit_unicode_for_ash(void)
  1899. {
  1900. /* Unicode support should be activated even if LANG is set
  1901. * _during_ shell execution, not only if it was set when
  1902. * shell was started. Therefore, re-check LANG every time:
  1903. */
  1904. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1905. || ENABLE_UNICODE_USING_LOCALE
  1906. ) {
  1907. const char *s = lookupvar("LC_ALL");
  1908. if (!s) s = lookupvar("LC_CTYPE");
  1909. if (!s) s = lookupvar("LANG");
  1910. reinit_unicode(s);
  1911. }
  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. setvar0(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. setvar0(s, NULL);
  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(NULL, "/");
  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[] ALIGN2 = {
  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[] ALIGN1 = {
  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. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3002. /*
  3003. * A job structure contains information about a job. A job is either a
  3004. * single process or a set of processes contained in a pipeline. In the
  3005. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3006. * array of pids.
  3007. */
  3008. struct procstat {
  3009. pid_t ps_pid; /* process id */
  3010. int ps_status; /* last process status from wait() */
  3011. char *ps_cmd; /* text of command being run */
  3012. };
  3013. struct job {
  3014. struct procstat ps0; /* status of process */
  3015. struct procstat *ps; /* status or processes when more than one */
  3016. #if JOBS
  3017. int stopstatus; /* status of a stopped job */
  3018. #endif
  3019. uint32_t
  3020. nprocs: 16, /* number of processes */
  3021. state: 8,
  3022. #define JOBRUNNING 0 /* at least one proc running */
  3023. #define JOBSTOPPED 1 /* all procs are stopped */
  3024. #define JOBDONE 2 /* all procs are completed */
  3025. #if JOBS
  3026. sigint: 1, /* job was killed by SIGINT */
  3027. jobctl: 1, /* job running under job control */
  3028. #endif
  3029. waited: 1, /* true if this entry has been waited for */
  3030. used: 1, /* true if this entry is in used */
  3031. changed: 1; /* true if status has changed */
  3032. struct job *prev_job; /* previous job */
  3033. };
  3034. static struct job *makejob(/*union node *,*/ int);
  3035. static int forkshell(struct job *, union node *, int);
  3036. static int waitforjob(struct job *);
  3037. #if !JOBS
  3038. enum { doing_jobctl = 0 };
  3039. #define setjobctl(on) do {} while (0)
  3040. #else
  3041. static smallint doing_jobctl; //references:8
  3042. static void setjobctl(int);
  3043. #endif
  3044. /*
  3045. * Ignore a signal.
  3046. */
  3047. static void
  3048. ignoresig(int signo)
  3049. {
  3050. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3051. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3052. /* No, need to do it */
  3053. signal(signo, SIG_IGN);
  3054. }
  3055. sigmode[signo - 1] = S_HARD_IGN;
  3056. }
  3057. /*
  3058. * Only one usage site - in setsignal()
  3059. */
  3060. static void
  3061. signal_handler(int signo)
  3062. {
  3063. gotsig[signo - 1] = 1;
  3064. if (signo == SIGINT && !trap[SIGINT]) {
  3065. if (!suppress_int) {
  3066. pending_sig = 0;
  3067. raise_interrupt(); /* does not return */
  3068. }
  3069. pending_int = 1;
  3070. } else {
  3071. pending_sig = signo;
  3072. }
  3073. }
  3074. /*
  3075. * Set the signal handler for the specified signal. The routine figures
  3076. * out what it should be set to.
  3077. */
  3078. static void
  3079. setsignal(int signo)
  3080. {
  3081. char *t;
  3082. char cur_act, new_act;
  3083. struct sigaction act;
  3084. t = trap[signo];
  3085. new_act = S_DFL;
  3086. if (t != NULL) { /* trap for this sig is set */
  3087. new_act = S_CATCH;
  3088. if (t[0] == '\0') /* trap is "": ignore this sig */
  3089. new_act = S_IGN;
  3090. }
  3091. if (rootshell && new_act == S_DFL) {
  3092. switch (signo) {
  3093. case SIGINT:
  3094. if (iflag || minusc || sflag == 0)
  3095. new_act = S_CATCH;
  3096. break;
  3097. case SIGQUIT:
  3098. #if DEBUG
  3099. if (debug)
  3100. break;
  3101. #endif
  3102. /* man bash:
  3103. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3104. * commands run by bash have signal handlers
  3105. * set to the values inherited by the shell
  3106. * from its parent". */
  3107. new_act = S_IGN;
  3108. break;
  3109. case SIGTERM:
  3110. if (iflag)
  3111. new_act = S_IGN;
  3112. break;
  3113. #if JOBS
  3114. case SIGTSTP:
  3115. case SIGTTOU:
  3116. if (mflag)
  3117. new_act = S_IGN;
  3118. break;
  3119. #endif
  3120. }
  3121. }
  3122. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3123. //whereas we have to restore it to what shell got on entry
  3124. //from the parent. See comment above
  3125. t = &sigmode[signo - 1];
  3126. cur_act = *t;
  3127. if (cur_act == 0) {
  3128. /* current setting is not yet known */
  3129. if (sigaction(signo, NULL, &act)) {
  3130. /* pretend it worked; maybe we should give a warning,
  3131. * but other shells don't. We don't alter sigmode,
  3132. * so we retry every time.
  3133. * btw, in Linux it never fails. --vda */
  3134. return;
  3135. }
  3136. if (act.sa_handler == SIG_IGN) {
  3137. cur_act = S_HARD_IGN;
  3138. if (mflag
  3139. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3140. ) {
  3141. cur_act = S_IGN; /* don't hard ignore these */
  3142. }
  3143. }
  3144. }
  3145. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3146. return;
  3147. act.sa_handler = SIG_DFL;
  3148. switch (new_act) {
  3149. case S_CATCH:
  3150. act.sa_handler = signal_handler;
  3151. break;
  3152. case S_IGN:
  3153. act.sa_handler = SIG_IGN;
  3154. break;
  3155. }
  3156. /* flags and mask matter only if !DFL and !IGN, but we do it
  3157. * for all cases for more deterministic behavior:
  3158. */
  3159. act.sa_flags = 0;
  3160. sigfillset(&act.sa_mask);
  3161. sigaction_set(signo, &act);
  3162. *t = new_act;
  3163. }
  3164. /* mode flags for set_curjob */
  3165. #define CUR_DELETE 2
  3166. #define CUR_RUNNING 1
  3167. #define CUR_STOPPED 0
  3168. /* mode flags for dowait */
  3169. #define DOWAIT_NONBLOCK WNOHANG
  3170. #define DOWAIT_BLOCK 0
  3171. #if JOBS
  3172. /* pgrp of shell on invocation */
  3173. static int initialpgrp; //references:2
  3174. static int ttyfd = -1; //5
  3175. #endif
  3176. /* array of jobs */
  3177. static struct job *jobtab; //5
  3178. /* size of array */
  3179. static unsigned njobs; //4
  3180. /* current job */
  3181. static struct job *curjob; //lots
  3182. /* number of presumed living untracked jobs */
  3183. static int jobless; //4
  3184. static void
  3185. set_curjob(struct job *jp, unsigned mode)
  3186. {
  3187. struct job *jp1;
  3188. struct job **jpp, **curp;
  3189. /* first remove from list */
  3190. jpp = curp = &curjob;
  3191. while (1) {
  3192. jp1 = *jpp;
  3193. if (jp1 == jp)
  3194. break;
  3195. jpp = &jp1->prev_job;
  3196. }
  3197. *jpp = jp1->prev_job;
  3198. /* Then re-insert in correct position */
  3199. jpp = curp;
  3200. switch (mode) {
  3201. default:
  3202. #if DEBUG
  3203. abort();
  3204. #endif
  3205. case CUR_DELETE:
  3206. /* job being deleted */
  3207. break;
  3208. case CUR_RUNNING:
  3209. /* newly created job or backgrounded job,
  3210. * put after all stopped jobs.
  3211. */
  3212. while (1) {
  3213. jp1 = *jpp;
  3214. #if JOBS
  3215. if (!jp1 || jp1->state != JOBSTOPPED)
  3216. #endif
  3217. break;
  3218. jpp = &jp1->prev_job;
  3219. }
  3220. /* FALLTHROUGH */
  3221. #if JOBS
  3222. case CUR_STOPPED:
  3223. #endif
  3224. /* newly stopped job - becomes curjob */
  3225. jp->prev_job = *jpp;
  3226. *jpp = jp;
  3227. break;
  3228. }
  3229. }
  3230. #if JOBS || DEBUG
  3231. static int
  3232. jobno(const struct job *jp)
  3233. {
  3234. return jp - jobtab + 1;
  3235. }
  3236. #endif
  3237. /*
  3238. * Convert a job name to a job structure.
  3239. */
  3240. #if !JOBS
  3241. #define getjob(name, getctl) getjob(name)
  3242. #endif
  3243. static struct job *
  3244. getjob(const char *name, int getctl)
  3245. {
  3246. struct job *jp;
  3247. struct job *found;
  3248. const char *err_msg = "%s: no such job";
  3249. unsigned num;
  3250. int c;
  3251. const char *p;
  3252. char *(*match)(const char *, const char *);
  3253. jp = curjob;
  3254. p = name;
  3255. if (!p)
  3256. goto currentjob;
  3257. if (*p != '%')
  3258. goto err;
  3259. c = *++p;
  3260. if (!c)
  3261. goto currentjob;
  3262. if (!p[1]) {
  3263. if (c == '+' || c == '%') {
  3264. currentjob:
  3265. err_msg = "No current job";
  3266. goto check;
  3267. }
  3268. if (c == '-') {
  3269. if (jp)
  3270. jp = jp->prev_job;
  3271. err_msg = "No previous job";
  3272. check:
  3273. if (!jp)
  3274. goto err;
  3275. goto gotit;
  3276. }
  3277. }
  3278. if (is_number(p)) {
  3279. num = atoi(p);
  3280. if (num <= njobs) {
  3281. jp = jobtab + num - 1;
  3282. if (jp->used)
  3283. goto gotit;
  3284. goto err;
  3285. }
  3286. }
  3287. match = prefix;
  3288. if (*p == '?') {
  3289. match = strstr;
  3290. p++;
  3291. }
  3292. found = NULL;
  3293. while (jp) {
  3294. if (match(jp->ps[0].ps_cmd, p)) {
  3295. if (found)
  3296. goto err;
  3297. found = jp;
  3298. err_msg = "%s: ambiguous";
  3299. }
  3300. jp = jp->prev_job;
  3301. }
  3302. if (!found)
  3303. goto err;
  3304. jp = found;
  3305. gotit:
  3306. #if JOBS
  3307. err_msg = "job %s not created under job control";
  3308. if (getctl && jp->jobctl == 0)
  3309. goto err;
  3310. #endif
  3311. return jp;
  3312. err:
  3313. ash_msg_and_raise_error(err_msg, name);
  3314. }
  3315. /*
  3316. * Mark a job structure as unused.
  3317. */
  3318. static void
  3319. freejob(struct job *jp)
  3320. {
  3321. struct procstat *ps;
  3322. int i;
  3323. INT_OFF;
  3324. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3325. if (ps->ps_cmd != nullstr)
  3326. free(ps->ps_cmd);
  3327. }
  3328. if (jp->ps != &jp->ps0)
  3329. free(jp->ps);
  3330. jp->used = 0;
  3331. set_curjob(jp, CUR_DELETE);
  3332. INT_ON;
  3333. }
  3334. #if JOBS
  3335. static void
  3336. xtcsetpgrp(int fd, pid_t pgrp)
  3337. {
  3338. if (tcsetpgrp(fd, pgrp))
  3339. ash_msg_and_raise_error("can't set tty process group (%m)");
  3340. }
  3341. /*
  3342. * Turn job control on and off.
  3343. *
  3344. * Note: This code assumes that the third arg to ioctl is a character
  3345. * pointer, which is true on Berkeley systems but not System V. Since
  3346. * System V doesn't have job control yet, this isn't a problem now.
  3347. *
  3348. * Called with interrupts off.
  3349. */
  3350. static void
  3351. setjobctl(int on)
  3352. {
  3353. int fd;
  3354. int pgrp;
  3355. if (on == doing_jobctl || rootshell == 0)
  3356. return;
  3357. if (on) {
  3358. int ofd;
  3359. ofd = fd = open(_PATH_TTY, O_RDWR);
  3360. if (fd < 0) {
  3361. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3362. * That sometimes helps to acquire controlling tty.
  3363. * Obviously, a workaround for bugs when someone
  3364. * failed to provide a controlling tty to bash! :) */
  3365. fd = 2;
  3366. while (!isatty(fd))
  3367. if (--fd < 0)
  3368. goto out;
  3369. }
  3370. fd = fcntl(fd, F_DUPFD, 10);
  3371. if (ofd >= 0)
  3372. close(ofd);
  3373. if (fd < 0)
  3374. goto out;
  3375. /* fd is a tty at this point */
  3376. close_on_exec_on(fd);
  3377. while (1) { /* while we are in the background */
  3378. pgrp = tcgetpgrp(fd);
  3379. if (pgrp < 0) {
  3380. out:
  3381. ash_msg("can't access tty; job control turned off");
  3382. mflag = on = 0;
  3383. goto close;
  3384. }
  3385. if (pgrp == getpgrp())
  3386. break;
  3387. killpg(0, SIGTTIN);
  3388. }
  3389. initialpgrp = pgrp;
  3390. setsignal(SIGTSTP);
  3391. setsignal(SIGTTOU);
  3392. setsignal(SIGTTIN);
  3393. pgrp = rootpid;
  3394. setpgid(0, pgrp);
  3395. xtcsetpgrp(fd, pgrp);
  3396. } else {
  3397. /* turning job control off */
  3398. fd = ttyfd;
  3399. pgrp = initialpgrp;
  3400. /* was xtcsetpgrp, but this can make exiting ash
  3401. * loop forever if pty is already deleted */
  3402. tcsetpgrp(fd, pgrp);
  3403. setpgid(0, pgrp);
  3404. setsignal(SIGTSTP);
  3405. setsignal(SIGTTOU);
  3406. setsignal(SIGTTIN);
  3407. close:
  3408. if (fd >= 0)
  3409. close(fd);
  3410. fd = -1;
  3411. }
  3412. ttyfd = fd;
  3413. doing_jobctl = on;
  3414. }
  3415. static int FAST_FUNC
  3416. killcmd(int argc, char **argv)
  3417. {
  3418. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3419. int i = 1;
  3420. do {
  3421. if (argv[i][0] == '%') {
  3422. /*
  3423. * "kill %N" - job kill
  3424. * Converting to pgrp / pid kill
  3425. */
  3426. struct job *jp;
  3427. char *dst;
  3428. int j, n;
  3429. jp = getjob(argv[i], 0);
  3430. /*
  3431. * In jobs started under job control, we signal
  3432. * entire process group by kill -PGRP_ID.
  3433. * This happens, f.e., in interactive shell.
  3434. *
  3435. * Otherwise, we signal each child via
  3436. * kill PID1 PID2 PID3.
  3437. * Testcases:
  3438. * sh -c 'sleep 1|sleep 1 & kill %1'
  3439. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3440. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3441. */
  3442. n = jp->nprocs; /* can't be 0 (I hope) */
  3443. if (jp->jobctl)
  3444. n = 1;
  3445. dst = alloca(n * sizeof(int)*4);
  3446. argv[i] = dst;
  3447. for (j = 0; j < n; j++) {
  3448. struct procstat *ps = &jp->ps[j];
  3449. /* Skip non-running and not-stopped members
  3450. * (i.e. dead members) of the job
  3451. */
  3452. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3453. continue;
  3454. /*
  3455. * kill_main has matching code to expect
  3456. * leading space. Needed to not confuse
  3457. * negative pids with "kill -SIGNAL_NO" syntax
  3458. */
  3459. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3460. }
  3461. *dst = '\0';
  3462. }
  3463. } while (argv[++i]);
  3464. }
  3465. return kill_main(argc, argv);
  3466. }
  3467. static void
  3468. showpipe(struct job *jp /*, FILE *out*/)
  3469. {
  3470. struct procstat *ps;
  3471. struct procstat *psend;
  3472. psend = jp->ps + jp->nprocs;
  3473. for (ps = jp->ps + 1; ps < psend; ps++)
  3474. printf(" | %s", ps->ps_cmd);
  3475. newline_and_flush(stdout);
  3476. flush_stdout_stderr();
  3477. }
  3478. static int
  3479. restartjob(struct job *jp, int mode)
  3480. {
  3481. struct procstat *ps;
  3482. int i;
  3483. int status;
  3484. pid_t pgid;
  3485. INT_OFF;
  3486. if (jp->state == JOBDONE)
  3487. goto out;
  3488. jp->state = JOBRUNNING;
  3489. pgid = jp->ps[0].ps_pid;
  3490. if (mode == FORK_FG)
  3491. xtcsetpgrp(ttyfd, pgid);
  3492. killpg(pgid, SIGCONT);
  3493. ps = jp->ps;
  3494. i = jp->nprocs;
  3495. do {
  3496. if (WIFSTOPPED(ps->ps_status)) {
  3497. ps->ps_status = -1;
  3498. }
  3499. ps++;
  3500. } while (--i);
  3501. out:
  3502. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3503. INT_ON;
  3504. return status;
  3505. }
  3506. static int FAST_FUNC
  3507. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3508. {
  3509. struct job *jp;
  3510. int mode;
  3511. int retval;
  3512. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3513. nextopt(nullstr);
  3514. argv = argptr;
  3515. do {
  3516. jp = getjob(*argv, 1);
  3517. if (mode == FORK_BG) {
  3518. set_curjob(jp, CUR_RUNNING);
  3519. printf("[%d] ", jobno(jp));
  3520. }
  3521. out1str(jp->ps[0].ps_cmd);
  3522. showpipe(jp /*, stdout*/);
  3523. retval = restartjob(jp, mode);
  3524. } while (*argv && *++argv);
  3525. return retval;
  3526. }
  3527. #endif
  3528. static int
  3529. sprint_status48(char *s, int status, int sigonly)
  3530. {
  3531. int col;
  3532. int st;
  3533. col = 0;
  3534. if (!WIFEXITED(status)) {
  3535. if (JOBS && WIFSTOPPED(status))
  3536. st = WSTOPSIG(status);
  3537. else
  3538. st = WTERMSIG(status);
  3539. if (sigonly) {
  3540. if (st == SIGINT || st == SIGPIPE)
  3541. goto out;
  3542. if (JOBS && WIFSTOPPED(status))
  3543. goto out;
  3544. }
  3545. st &= 0x7f;
  3546. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3547. col = fmtstr(s, 32, strsignal(st));
  3548. if (WCOREDUMP(status)) {
  3549. strcpy(s + col, " (core dumped)");
  3550. col += sizeof(" (core dumped)")-1;
  3551. }
  3552. } else if (!sigonly) {
  3553. st = WEXITSTATUS(status);
  3554. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3555. }
  3556. out:
  3557. return col;
  3558. }
  3559. static int
  3560. dowait(int wait_flags, struct job *job)
  3561. {
  3562. int pid;
  3563. int status;
  3564. struct job *jp;
  3565. struct job *thisjob;
  3566. TRACE(("dowait(0x%x) called\n", wait_flags));
  3567. /* Do a wait system call. If job control is compiled in, we accept
  3568. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3569. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3570. if (doing_jobctl)
  3571. wait_flags |= WUNTRACED;
  3572. pid = waitpid(-1, &status, wait_flags);
  3573. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3574. pid, status, errno, strerror(errno)));
  3575. if (pid <= 0)
  3576. return pid;
  3577. INT_OFF;
  3578. thisjob = NULL;
  3579. for (jp = curjob; jp; jp = jp->prev_job) {
  3580. int jobstate;
  3581. struct procstat *ps;
  3582. struct procstat *psend;
  3583. if (jp->state == JOBDONE)
  3584. continue;
  3585. jobstate = JOBDONE;
  3586. ps = jp->ps;
  3587. psend = ps + jp->nprocs;
  3588. do {
  3589. if (ps->ps_pid == pid) {
  3590. TRACE(("Job %d: changing status of proc %d "
  3591. "from 0x%x to 0x%x\n",
  3592. jobno(jp), pid, ps->ps_status, status));
  3593. ps->ps_status = status;
  3594. thisjob = jp;
  3595. }
  3596. if (ps->ps_status == -1)
  3597. jobstate = JOBRUNNING;
  3598. #if JOBS
  3599. if (jobstate == JOBRUNNING)
  3600. continue;
  3601. if (WIFSTOPPED(ps->ps_status)) {
  3602. jp->stopstatus = ps->ps_status;
  3603. jobstate = JOBSTOPPED;
  3604. }
  3605. #endif
  3606. } while (++ps < psend);
  3607. if (!thisjob)
  3608. continue;
  3609. /* Found the job where one of its processes changed its state.
  3610. * Is there at least one live and running process in this job? */
  3611. if (jobstate != JOBRUNNING) {
  3612. /* No. All live processes in the job are stopped
  3613. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3614. */
  3615. thisjob->changed = 1;
  3616. if (thisjob->state != jobstate) {
  3617. TRACE(("Job %d: changing state from %d to %d\n",
  3618. jobno(thisjob), thisjob->state, jobstate));
  3619. thisjob->state = jobstate;
  3620. #if JOBS
  3621. if (jobstate == JOBSTOPPED)
  3622. set_curjob(thisjob, CUR_STOPPED);
  3623. #endif
  3624. }
  3625. }
  3626. goto out;
  3627. }
  3628. /* The process wasn't found in job list */
  3629. if (JOBS && !WIFSTOPPED(status))
  3630. jobless--;
  3631. out:
  3632. INT_ON;
  3633. if (thisjob && thisjob == job) {
  3634. char s[48 + 1];
  3635. int len;
  3636. len = sprint_status48(s, status, 1);
  3637. if (len) {
  3638. s[len] = '\n';
  3639. s[len + 1] = '\0';
  3640. out2str(s);
  3641. }
  3642. }
  3643. return pid;
  3644. }
  3645. static int
  3646. blocking_wait_with_raise_on_sig(void)
  3647. {
  3648. pid_t pid = dowait(DOWAIT_BLOCK, NULL);
  3649. if (pid <= 0 && pending_sig)
  3650. raise_exception(EXSIG);
  3651. return pid;
  3652. }
  3653. #if JOBS
  3654. static void
  3655. showjob(struct job *jp, int mode)
  3656. {
  3657. struct procstat *ps;
  3658. struct procstat *psend;
  3659. int col;
  3660. int indent_col;
  3661. char s[16 + 16 + 48];
  3662. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3663. ps = jp->ps;
  3664. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3665. /* just output process (group) id of pipeline */
  3666. fprintf(out, "%d\n", ps->ps_pid);
  3667. return;
  3668. }
  3669. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3670. indent_col = col;
  3671. if (jp == curjob)
  3672. s[col - 3] = '+';
  3673. else if (curjob && jp == curjob->prev_job)
  3674. s[col - 3] = '-';
  3675. if (mode & SHOW_PIDS)
  3676. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3677. psend = ps + jp->nprocs;
  3678. if (jp->state == JOBRUNNING) {
  3679. strcpy(s + col, "Running");
  3680. col += sizeof("Running") - 1;
  3681. } else {
  3682. int status = psend[-1].ps_status;
  3683. if (jp->state == JOBSTOPPED)
  3684. status = jp->stopstatus;
  3685. col += sprint_status48(s + col, status, 0);
  3686. }
  3687. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3688. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3689. * or prints several "PID | <cmdN>" lines,
  3690. * depending on SHOW_PIDS bit.
  3691. * We do not print status of individual processes
  3692. * between PID and <cmdN>. bash does it, but not very well:
  3693. * first line shows overall job status, not process status,
  3694. * making it impossible to know 1st process status.
  3695. */
  3696. goto start;
  3697. do {
  3698. /* for each process */
  3699. s[0] = '\0';
  3700. col = 33;
  3701. if (mode & SHOW_PIDS)
  3702. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3703. start:
  3704. fprintf(out, "%s%*c%s%s",
  3705. s,
  3706. 33 - col >= 0 ? 33 - col : 0, ' ',
  3707. ps == jp->ps ? "" : "| ",
  3708. ps->ps_cmd
  3709. );
  3710. } while (++ps != psend);
  3711. newline_and_flush(out);
  3712. jp->changed = 0;
  3713. if (jp->state == JOBDONE) {
  3714. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3715. freejob(jp);
  3716. }
  3717. }
  3718. /*
  3719. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3720. * statuses have changed since the last call to showjobs.
  3721. */
  3722. static void
  3723. showjobs(int mode)
  3724. {
  3725. struct job *jp;
  3726. TRACE(("showjobs(0x%x) called\n", mode));
  3727. /* Handle all finished jobs */
  3728. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3729. continue;
  3730. for (jp = curjob; jp; jp = jp->prev_job) {
  3731. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3732. showjob(jp, mode);
  3733. }
  3734. }
  3735. }
  3736. static int FAST_FUNC
  3737. jobscmd(int argc UNUSED_PARAM, char **argv)
  3738. {
  3739. int mode, m;
  3740. mode = 0;
  3741. while ((m = nextopt("lp")) != '\0') {
  3742. if (m == 'l')
  3743. mode |= SHOW_PIDS;
  3744. else
  3745. mode |= SHOW_ONLY_PGID;
  3746. }
  3747. argv = argptr;
  3748. if (*argv) {
  3749. do
  3750. showjob(getjob(*argv, 0), mode);
  3751. while (*++argv);
  3752. } else {
  3753. showjobs(mode);
  3754. }
  3755. return 0;
  3756. }
  3757. #endif /* JOBS */
  3758. /* Called only on finished or stopped jobs (no members are running) */
  3759. static int
  3760. getstatus(struct job *job)
  3761. {
  3762. int status;
  3763. int retval;
  3764. struct procstat *ps;
  3765. /* Fetch last member's status */
  3766. ps = job->ps + job->nprocs - 1;
  3767. status = ps->ps_status;
  3768. if (pipefail) {
  3769. /* "set -o pipefail" mode: use last _nonzero_ status */
  3770. while (status == 0 && --ps >= job->ps)
  3771. status = ps->ps_status;
  3772. }
  3773. retval = WEXITSTATUS(status);
  3774. if (!WIFEXITED(status)) {
  3775. #if JOBS
  3776. retval = WSTOPSIG(status);
  3777. if (!WIFSTOPPED(status))
  3778. #endif
  3779. {
  3780. /* XXX: limits number of signals */
  3781. retval = WTERMSIG(status);
  3782. #if JOBS
  3783. if (retval == SIGINT)
  3784. job->sigint = 1;
  3785. #endif
  3786. }
  3787. retval += 128;
  3788. }
  3789. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3790. jobno(job), job->nprocs, status, retval));
  3791. return retval;
  3792. }
  3793. static int FAST_FUNC
  3794. waitcmd(int argc UNUSED_PARAM, char **argv)
  3795. {
  3796. struct job *job;
  3797. int retval;
  3798. struct job *jp;
  3799. if (pending_sig)
  3800. raise_exception(EXSIG);
  3801. nextopt(nullstr);
  3802. retval = 0;
  3803. argv = argptr;
  3804. if (!*argv) {
  3805. /* wait for all jobs */
  3806. for (;;) {
  3807. jp = curjob;
  3808. while (1) {
  3809. if (!jp) /* no running procs */
  3810. goto ret;
  3811. if (jp->state == JOBRUNNING)
  3812. break;
  3813. jp->waited = 1;
  3814. jp = jp->prev_job;
  3815. }
  3816. blocking_wait_with_raise_on_sig();
  3817. /* man bash:
  3818. * "When bash is waiting for an asynchronous command via
  3819. * the wait builtin, the reception of a signal for which a trap
  3820. * has been set will cause the wait builtin to return immediately
  3821. * with an exit status greater than 128, immediately after which
  3822. * the trap is executed."
  3823. *
  3824. * blocking_wait_with_raise_on_sig raises signal handlers
  3825. * if it gets no pid (pid < 0). However,
  3826. * if child sends us a signal *and immediately exits*,
  3827. * blocking_wait_with_raise_on_sig gets pid > 0
  3828. * and does not handle pending_sig. Check this case: */
  3829. if (pending_sig)
  3830. raise_exception(EXSIG);
  3831. }
  3832. }
  3833. retval = 127;
  3834. do {
  3835. if (**argv != '%') {
  3836. pid_t pid = number(*argv);
  3837. job = curjob;
  3838. while (1) {
  3839. if (!job)
  3840. goto repeat;
  3841. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3842. break;
  3843. job = job->prev_job;
  3844. }
  3845. } else {
  3846. job = getjob(*argv, 0);
  3847. }
  3848. /* loop until process terminated or stopped */
  3849. while (job->state == JOBRUNNING)
  3850. blocking_wait_with_raise_on_sig();
  3851. job->waited = 1;
  3852. retval = getstatus(job);
  3853. repeat: ;
  3854. } while (*++argv);
  3855. ret:
  3856. return retval;
  3857. }
  3858. static struct job *
  3859. growjobtab(void)
  3860. {
  3861. size_t len;
  3862. ptrdiff_t offset;
  3863. struct job *jp, *jq;
  3864. len = njobs * sizeof(*jp);
  3865. jq = jobtab;
  3866. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3867. offset = (char *)jp - (char *)jq;
  3868. if (offset) {
  3869. /* Relocate pointers */
  3870. size_t l = len;
  3871. jq = (struct job *)((char *)jq + l);
  3872. while (l) {
  3873. l -= sizeof(*jp);
  3874. jq--;
  3875. #define joff(p) ((struct job *)((char *)(p) + l))
  3876. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3877. if (joff(jp)->ps == &jq->ps0)
  3878. jmove(joff(jp)->ps);
  3879. if (joff(jp)->prev_job)
  3880. jmove(joff(jp)->prev_job);
  3881. }
  3882. if (curjob)
  3883. jmove(curjob);
  3884. #undef joff
  3885. #undef jmove
  3886. }
  3887. njobs += 4;
  3888. jobtab = jp;
  3889. jp = (struct job *)((char *)jp + len);
  3890. jq = jp + 3;
  3891. do {
  3892. jq->used = 0;
  3893. } while (--jq >= jp);
  3894. return jp;
  3895. }
  3896. /*
  3897. * Return a new job structure.
  3898. * Called with interrupts off.
  3899. */
  3900. static struct job *
  3901. makejob(/*union node *node,*/ int nprocs)
  3902. {
  3903. int i;
  3904. struct job *jp;
  3905. for (i = njobs, jp = jobtab; ; jp++) {
  3906. if (--i < 0) {
  3907. jp = growjobtab();
  3908. break;
  3909. }
  3910. if (jp->used == 0)
  3911. break;
  3912. if (jp->state != JOBDONE || !jp->waited)
  3913. continue;
  3914. #if JOBS
  3915. if (doing_jobctl)
  3916. continue;
  3917. #endif
  3918. freejob(jp);
  3919. break;
  3920. }
  3921. memset(jp, 0, sizeof(*jp));
  3922. #if JOBS
  3923. /* jp->jobctl is a bitfield.
  3924. * "jp->jobctl |= jobctl" likely to give awful code */
  3925. if (doing_jobctl)
  3926. jp->jobctl = 1;
  3927. #endif
  3928. jp->prev_job = curjob;
  3929. curjob = jp;
  3930. jp->used = 1;
  3931. jp->ps = &jp->ps0;
  3932. if (nprocs > 1) {
  3933. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3934. }
  3935. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3936. jobno(jp)));
  3937. return jp;
  3938. }
  3939. #if JOBS
  3940. /*
  3941. * Return a string identifying a command (to be printed by the
  3942. * jobs command).
  3943. */
  3944. static char *cmdnextc;
  3945. static void
  3946. cmdputs(const char *s)
  3947. {
  3948. static const char vstype[VSTYPE + 1][3] = {
  3949. "", "}", "-", "+", "?", "=",
  3950. "%", "%%", "#", "##"
  3951. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3952. };
  3953. const char *p, *str;
  3954. char cc[2];
  3955. char *nextc;
  3956. unsigned char c;
  3957. unsigned char subtype = 0;
  3958. int quoted = 0;
  3959. cc[1] = '\0';
  3960. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3961. p = s;
  3962. while ((c = *p++) != '\0') {
  3963. str = NULL;
  3964. switch (c) {
  3965. case CTLESC:
  3966. c = *p++;
  3967. break;
  3968. case CTLVAR:
  3969. subtype = *p++;
  3970. if ((subtype & VSTYPE) == VSLENGTH)
  3971. str = "${#";
  3972. else
  3973. str = "${";
  3974. goto dostr;
  3975. case CTLENDVAR:
  3976. str = "\"}" + !(quoted & 1);
  3977. quoted >>= 1;
  3978. subtype = 0;
  3979. goto dostr;
  3980. case CTLBACKQ:
  3981. str = "$(...)";
  3982. goto dostr;
  3983. #if ENABLE_SH_MATH_SUPPORT
  3984. case CTLARI:
  3985. str = "$((";
  3986. goto dostr;
  3987. case CTLENDARI:
  3988. str = "))";
  3989. goto dostr;
  3990. #endif
  3991. case CTLQUOTEMARK:
  3992. quoted ^= 1;
  3993. c = '"';
  3994. break;
  3995. case '=':
  3996. if (subtype == 0)
  3997. break;
  3998. if ((subtype & VSTYPE) != VSNORMAL)
  3999. quoted <<= 1;
  4000. str = vstype[subtype & VSTYPE];
  4001. if (subtype & VSNUL)
  4002. c = ':';
  4003. else
  4004. goto checkstr;
  4005. break;
  4006. case '\'':
  4007. case '\\':
  4008. case '"':
  4009. case '$':
  4010. /* These can only happen inside quotes */
  4011. cc[0] = c;
  4012. str = cc;
  4013. c = '\\';
  4014. break;
  4015. default:
  4016. break;
  4017. }
  4018. USTPUTC(c, nextc);
  4019. checkstr:
  4020. if (!str)
  4021. continue;
  4022. dostr:
  4023. while ((c = *str++) != '\0') {
  4024. USTPUTC(c, nextc);
  4025. }
  4026. } /* while *p++ not NUL */
  4027. if (quoted & 1) {
  4028. USTPUTC('"', nextc);
  4029. }
  4030. *nextc = 0;
  4031. cmdnextc = nextc;
  4032. }
  4033. /* cmdtxt() and cmdlist() call each other */
  4034. static void cmdtxt(union node *n);
  4035. static void
  4036. cmdlist(union node *np, int sep)
  4037. {
  4038. for (; np; np = np->narg.next) {
  4039. if (!sep)
  4040. cmdputs(" ");
  4041. cmdtxt(np);
  4042. if (sep && np->narg.next)
  4043. cmdputs(" ");
  4044. }
  4045. }
  4046. static void
  4047. cmdtxt(union node *n)
  4048. {
  4049. union node *np;
  4050. struct nodelist *lp;
  4051. const char *p;
  4052. if (!n)
  4053. return;
  4054. switch (n->type) {
  4055. default:
  4056. #if DEBUG
  4057. abort();
  4058. #endif
  4059. case NPIPE:
  4060. lp = n->npipe.cmdlist;
  4061. for (;;) {
  4062. cmdtxt(lp->n);
  4063. lp = lp->next;
  4064. if (!lp)
  4065. break;
  4066. cmdputs(" | ");
  4067. }
  4068. break;
  4069. case NSEMI:
  4070. p = "; ";
  4071. goto binop;
  4072. case NAND:
  4073. p = " && ";
  4074. goto binop;
  4075. case NOR:
  4076. p = " || ";
  4077. binop:
  4078. cmdtxt(n->nbinary.ch1);
  4079. cmdputs(p);
  4080. n = n->nbinary.ch2;
  4081. goto donode;
  4082. case NREDIR:
  4083. case NBACKGND:
  4084. n = n->nredir.n;
  4085. goto donode;
  4086. case NNOT:
  4087. cmdputs("!");
  4088. n = n->nnot.com;
  4089. donode:
  4090. cmdtxt(n);
  4091. break;
  4092. case NIF:
  4093. cmdputs("if ");
  4094. cmdtxt(n->nif.test);
  4095. cmdputs("; then ");
  4096. if (n->nif.elsepart) {
  4097. cmdtxt(n->nif.ifpart);
  4098. cmdputs("; else ");
  4099. n = n->nif.elsepart;
  4100. } else {
  4101. n = n->nif.ifpart;
  4102. }
  4103. p = "; fi";
  4104. goto dotail;
  4105. case NSUBSHELL:
  4106. cmdputs("(");
  4107. n = n->nredir.n;
  4108. p = ")";
  4109. goto dotail;
  4110. case NWHILE:
  4111. p = "while ";
  4112. goto until;
  4113. case NUNTIL:
  4114. p = "until ";
  4115. until:
  4116. cmdputs(p);
  4117. cmdtxt(n->nbinary.ch1);
  4118. n = n->nbinary.ch2;
  4119. p = "; done";
  4120. dodo:
  4121. cmdputs("; do ");
  4122. dotail:
  4123. cmdtxt(n);
  4124. goto dotail2;
  4125. case NFOR:
  4126. cmdputs("for ");
  4127. cmdputs(n->nfor.var);
  4128. cmdputs(" in ");
  4129. cmdlist(n->nfor.args, 1);
  4130. n = n->nfor.body;
  4131. p = "; done";
  4132. goto dodo;
  4133. case NDEFUN:
  4134. cmdputs(n->narg.text);
  4135. p = "() { ... }";
  4136. goto dotail2;
  4137. case NCMD:
  4138. cmdlist(n->ncmd.args, 1);
  4139. cmdlist(n->ncmd.redirect, 0);
  4140. break;
  4141. case NARG:
  4142. p = n->narg.text;
  4143. dotail2:
  4144. cmdputs(p);
  4145. break;
  4146. case NHERE:
  4147. case NXHERE:
  4148. p = "<<...";
  4149. goto dotail2;
  4150. case NCASE:
  4151. cmdputs("case ");
  4152. cmdputs(n->ncase.expr->narg.text);
  4153. cmdputs(" in ");
  4154. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4155. cmdtxt(np->nclist.pattern);
  4156. cmdputs(") ");
  4157. cmdtxt(np->nclist.body);
  4158. cmdputs(";; ");
  4159. }
  4160. p = "esac";
  4161. goto dotail2;
  4162. case NTO:
  4163. p = ">";
  4164. goto redir;
  4165. case NCLOBBER:
  4166. p = ">|";
  4167. goto redir;
  4168. case NAPPEND:
  4169. p = ">>";
  4170. goto redir;
  4171. #if ENABLE_ASH_BASH_COMPAT
  4172. case NTO2:
  4173. #endif
  4174. case NTOFD:
  4175. p = ">&";
  4176. goto redir;
  4177. case NFROM:
  4178. p = "<";
  4179. goto redir;
  4180. case NFROMFD:
  4181. p = "<&";
  4182. goto redir;
  4183. case NFROMTO:
  4184. p = "<>";
  4185. redir:
  4186. cmdputs(utoa(n->nfile.fd));
  4187. cmdputs(p);
  4188. if (n->type == NTOFD || n->type == NFROMFD) {
  4189. cmdputs(utoa(n->ndup.dupfd));
  4190. break;
  4191. }
  4192. n = n->nfile.fname;
  4193. goto donode;
  4194. }
  4195. }
  4196. static char *
  4197. commandtext(union node *n)
  4198. {
  4199. char *name;
  4200. STARTSTACKSTR(cmdnextc);
  4201. cmdtxt(n);
  4202. name = stackblock();
  4203. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4204. name, cmdnextc, cmdnextc));
  4205. return ckstrdup(name);
  4206. }
  4207. #endif /* JOBS */
  4208. /*
  4209. * Fork off a subshell. If we are doing job control, give the subshell its
  4210. * own process group. Jp is a job structure that the job is to be added to.
  4211. * N is the command that will be evaluated by the child. Both jp and n may
  4212. * be NULL. The mode parameter can be one of the following:
  4213. * FORK_FG - Fork off a foreground process.
  4214. * FORK_BG - Fork off a background process.
  4215. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4216. * process group even if job control is on.
  4217. *
  4218. * When job control is turned off, background processes have their standard
  4219. * input redirected to /dev/null (except for the second and later processes
  4220. * in a pipeline).
  4221. *
  4222. * Called with interrupts off.
  4223. */
  4224. /*
  4225. * Clear traps on a fork.
  4226. */
  4227. static void
  4228. clear_traps(void)
  4229. {
  4230. char **tp;
  4231. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4232. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4233. INT_OFF;
  4234. if (trap_ptr == trap)
  4235. free(*tp);
  4236. /* else: it "belongs" to trap_ptr vector, don't free */
  4237. *tp = NULL;
  4238. if ((tp - trap) != 0)
  4239. setsignal(tp - trap);
  4240. INT_ON;
  4241. }
  4242. }
  4243. may_have_traps = 0;
  4244. }
  4245. /* Lives far away from here, needed for forkchild */
  4246. static void closescript(void);
  4247. /* Called after fork(), in child */
  4248. static NOINLINE void
  4249. forkchild(struct job *jp, union node *n, int mode)
  4250. {
  4251. int oldlvl;
  4252. TRACE(("Child shell %d\n", getpid()));
  4253. oldlvl = shlvl;
  4254. shlvl++;
  4255. /* man bash: "Non-builtin commands run by bash have signal handlers
  4256. * set to the values inherited by the shell from its parent".
  4257. * Do we do it correctly? */
  4258. closescript();
  4259. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4260. && n && n->type == NCMD /* is it single cmd? */
  4261. /* && n->ncmd.args->type == NARG - always true? */
  4262. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4263. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4264. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4265. ) {
  4266. TRACE(("Trap hack\n"));
  4267. /* Awful hack for `trap` or $(trap).
  4268. *
  4269. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4270. * contains an example where "trap" is executed in a subshell:
  4271. *
  4272. * save_traps=$(trap)
  4273. * ...
  4274. * eval "$save_traps"
  4275. *
  4276. * Standard does not say that "trap" in subshell shall print
  4277. * parent shell's traps. It only says that its output
  4278. * must have suitable form, but then, in the above example
  4279. * (which is not supposed to be normative), it implies that.
  4280. *
  4281. * bash (and probably other shell) does implement it
  4282. * (traps are reset to defaults, but "trap" still shows them),
  4283. * but as a result, "trap" logic is hopelessly messed up:
  4284. *
  4285. * # trap
  4286. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4287. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4288. * # true | trap <--- trap is in subshell - no output (ditto)
  4289. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4290. * trap -- 'echo Ho' SIGWINCH
  4291. * # echo `(trap)` <--- in subshell in subshell - output
  4292. * trap -- 'echo Ho' SIGWINCH
  4293. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4294. * trap -- 'echo Ho' SIGWINCH
  4295. *
  4296. * The rules when to forget and when to not forget traps
  4297. * get really complex and nonsensical.
  4298. *
  4299. * Our solution: ONLY bare $(trap) or `trap` is special.
  4300. */
  4301. /* Save trap handler strings for trap builtin to print */
  4302. trap_ptr = xmemdup(trap, sizeof(trap));
  4303. /* Fall through into clearing traps */
  4304. }
  4305. clear_traps();
  4306. #if JOBS
  4307. /* do job control only in root shell */
  4308. doing_jobctl = 0;
  4309. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4310. pid_t pgrp;
  4311. if (jp->nprocs == 0)
  4312. pgrp = getpid();
  4313. else
  4314. pgrp = jp->ps[0].ps_pid;
  4315. /* this can fail because we are doing it in the parent also */
  4316. setpgid(0, pgrp);
  4317. if (mode == FORK_FG)
  4318. xtcsetpgrp(ttyfd, pgrp);
  4319. setsignal(SIGTSTP);
  4320. setsignal(SIGTTOU);
  4321. } else
  4322. #endif
  4323. if (mode == FORK_BG) {
  4324. /* man bash: "When job control is not in effect,
  4325. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4326. ignoresig(SIGINT);
  4327. ignoresig(SIGQUIT);
  4328. if (jp->nprocs == 0) {
  4329. close(0);
  4330. if (open(bb_dev_null, O_RDONLY) != 0)
  4331. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4332. }
  4333. }
  4334. if (oldlvl == 0) {
  4335. if (iflag) { /* why if iflag only? */
  4336. setsignal(SIGINT);
  4337. setsignal(SIGTERM);
  4338. }
  4339. /* man bash:
  4340. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4341. * commands run by bash have signal handlers
  4342. * set to the values inherited by the shell
  4343. * from its parent".
  4344. * Take care of the second rule: */
  4345. setsignal(SIGQUIT);
  4346. }
  4347. #if JOBS
  4348. if (n && n->type == NCMD
  4349. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4350. ) {
  4351. TRACE(("Job hack\n"));
  4352. /* "jobs": we do not want to clear job list for it,
  4353. * instead we remove only _its_ own_ job from job list.
  4354. * This makes "jobs .... | cat" more useful.
  4355. */
  4356. freejob(curjob);
  4357. return;
  4358. }
  4359. #endif
  4360. for (jp = curjob; jp; jp = jp->prev_job)
  4361. freejob(jp);
  4362. jobless = 0;
  4363. }
  4364. /* Called after fork(), in parent */
  4365. #if !JOBS
  4366. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4367. #endif
  4368. static void
  4369. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4370. {
  4371. TRACE(("In parent shell: child = %d\n", pid));
  4372. if (!jp) {
  4373. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4374. continue;
  4375. jobless++;
  4376. return;
  4377. }
  4378. #if JOBS
  4379. if (mode != FORK_NOJOB && jp->jobctl) {
  4380. int pgrp;
  4381. if (jp->nprocs == 0)
  4382. pgrp = pid;
  4383. else
  4384. pgrp = jp->ps[0].ps_pid;
  4385. /* This can fail because we are doing it in the child also */
  4386. setpgid(pid, pgrp);
  4387. }
  4388. #endif
  4389. if (mode == FORK_BG) {
  4390. backgndpid = pid; /* set $! */
  4391. set_curjob(jp, CUR_RUNNING);
  4392. }
  4393. if (jp) {
  4394. struct procstat *ps = &jp->ps[jp->nprocs++];
  4395. ps->ps_pid = pid;
  4396. ps->ps_status = -1;
  4397. ps->ps_cmd = nullstr;
  4398. #if JOBS
  4399. if (doing_jobctl && n)
  4400. ps->ps_cmd = commandtext(n);
  4401. #endif
  4402. }
  4403. }
  4404. static int
  4405. forkshell(struct job *jp, union node *n, int mode)
  4406. {
  4407. int pid;
  4408. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4409. pid = fork();
  4410. if (pid < 0) {
  4411. TRACE(("Fork failed, errno=%d", errno));
  4412. if (jp)
  4413. freejob(jp);
  4414. ash_msg_and_raise_error("can't fork");
  4415. }
  4416. if (pid == 0) {
  4417. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4418. forkchild(jp, n, mode);
  4419. } else {
  4420. forkparent(jp, n, mode, pid);
  4421. }
  4422. return pid;
  4423. }
  4424. /*
  4425. * Wait for job to finish.
  4426. *
  4427. * Under job control we have the problem that while a child process
  4428. * is running interrupts generated by the user are sent to the child
  4429. * but not to the shell. This means that an infinite loop started by
  4430. * an interactive user may be hard to kill. With job control turned off,
  4431. * an interactive user may place an interactive program inside a loop.
  4432. * If the interactive program catches interrupts, the user doesn't want
  4433. * these interrupts to also abort the loop. The approach we take here
  4434. * is to have the shell ignore interrupt signals while waiting for a
  4435. * foreground process to terminate, and then send itself an interrupt
  4436. * signal if the child process was terminated by an interrupt signal.
  4437. * Unfortunately, some programs want to do a bit of cleanup and then
  4438. * exit on interrupt; unless these processes terminate themselves by
  4439. * sending a signal to themselves (instead of calling exit) they will
  4440. * confuse this approach.
  4441. *
  4442. * Called with interrupts off.
  4443. */
  4444. static int
  4445. waitforjob(struct job *jp)
  4446. {
  4447. int st;
  4448. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4449. INT_OFF;
  4450. while (jp->state == JOBRUNNING) {
  4451. /* In non-interactive shells, we _can_ get
  4452. * a keyboard signal here and be EINTRed,
  4453. * but we just loop back, waiting for command to complete.
  4454. *
  4455. * man bash:
  4456. * "If bash is waiting for a command to complete and receives
  4457. * a signal for which a trap has been set, the trap
  4458. * will not be executed until the command completes."
  4459. *
  4460. * Reality is that even if trap is not set, bash
  4461. * will not act on the signal until command completes.
  4462. * Try this. sleep5intoff.c:
  4463. * #include <signal.h>
  4464. * #include <unistd.h>
  4465. * int main() {
  4466. * sigset_t set;
  4467. * sigemptyset(&set);
  4468. * sigaddset(&set, SIGINT);
  4469. * sigaddset(&set, SIGQUIT);
  4470. * sigprocmask(SIG_BLOCK, &set, NULL);
  4471. * sleep(5);
  4472. * return 0;
  4473. * }
  4474. * $ bash -c './sleep5intoff; echo hi'
  4475. * ^C^C^C^C <--- pressing ^C once a second
  4476. * $ _
  4477. * $ bash -c './sleep5intoff; echo hi'
  4478. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4479. * $ _
  4480. */
  4481. dowait(DOWAIT_BLOCK, jp);
  4482. }
  4483. INT_ON;
  4484. st = getstatus(jp);
  4485. #if JOBS
  4486. if (jp->jobctl) {
  4487. xtcsetpgrp(ttyfd, rootpid);
  4488. /*
  4489. * This is truly gross.
  4490. * If we're doing job control, then we did a TIOCSPGRP which
  4491. * caused us (the shell) to no longer be in the controlling
  4492. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4493. * intuit from the subprocess exit status whether a SIGINT
  4494. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4495. */
  4496. if (jp->sigint) /* TODO: do the same with all signals */
  4497. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4498. }
  4499. if (jp->state == JOBDONE)
  4500. #endif
  4501. freejob(jp);
  4502. return st;
  4503. }
  4504. /*
  4505. * return 1 if there are stopped jobs, otherwise 0
  4506. */
  4507. static int
  4508. stoppedjobs(void)
  4509. {
  4510. struct job *jp;
  4511. int retval;
  4512. retval = 0;
  4513. if (job_warning)
  4514. goto out;
  4515. jp = curjob;
  4516. if (jp && jp->state == JOBSTOPPED) {
  4517. out2str("You have stopped jobs.\n");
  4518. job_warning = 2;
  4519. retval++;
  4520. }
  4521. out:
  4522. return retval;
  4523. }
  4524. /* ============ redir.c
  4525. *
  4526. * Code for dealing with input/output redirection.
  4527. */
  4528. #undef EMPTY
  4529. #undef CLOSED
  4530. #define EMPTY -2 /* marks an unused slot in redirtab */
  4531. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4532. /*
  4533. * Open a file in noclobber mode.
  4534. * The code was copied from bash.
  4535. */
  4536. static int
  4537. noclobberopen(const char *fname)
  4538. {
  4539. int r, fd;
  4540. struct stat finfo, finfo2;
  4541. /*
  4542. * If the file exists and is a regular file, return an error
  4543. * immediately.
  4544. */
  4545. r = stat(fname, &finfo);
  4546. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4547. errno = EEXIST;
  4548. return -1;
  4549. }
  4550. /*
  4551. * If the file was not present (r != 0), make sure we open it
  4552. * exclusively so that if it is created before we open it, our open
  4553. * will fail. Make sure that we do not truncate an existing file.
  4554. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4555. * file was not a regular file, we leave O_EXCL off.
  4556. */
  4557. if (r != 0)
  4558. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4559. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4560. /* If the open failed, return the file descriptor right away. */
  4561. if (fd < 0)
  4562. return fd;
  4563. /*
  4564. * OK, the open succeeded, but the file may have been changed from a
  4565. * non-regular file to a regular file between the stat and the open.
  4566. * We are assuming that the O_EXCL open handles the case where FILENAME
  4567. * did not exist and is symlinked to an existing file between the stat
  4568. * and open.
  4569. */
  4570. /*
  4571. * If we can open it and fstat the file descriptor, and neither check
  4572. * revealed that it was a regular file, and the file has not been
  4573. * replaced, return the file descriptor.
  4574. */
  4575. if (fstat(fd, &finfo2) == 0
  4576. && !S_ISREG(finfo2.st_mode)
  4577. && finfo.st_dev == finfo2.st_dev
  4578. && finfo.st_ino == finfo2.st_ino
  4579. ) {
  4580. return fd;
  4581. }
  4582. /* The file has been replaced. badness. */
  4583. close(fd);
  4584. errno = EEXIST;
  4585. return -1;
  4586. }
  4587. /*
  4588. * Handle here documents. Normally we fork off a process to write the
  4589. * data to a pipe. If the document is short, we can stuff the data in
  4590. * the pipe without forking.
  4591. */
  4592. /* openhere needs this forward reference */
  4593. static void expandhere(union node *arg, int fd);
  4594. static int
  4595. openhere(union node *redir)
  4596. {
  4597. int pip[2];
  4598. size_t len = 0;
  4599. if (pipe(pip) < 0)
  4600. ash_msg_and_raise_error("pipe call failed");
  4601. if (redir->type == NHERE) {
  4602. len = strlen(redir->nhere.doc->narg.text);
  4603. if (len <= PIPE_BUF) {
  4604. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4605. goto out;
  4606. }
  4607. }
  4608. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4609. /* child */
  4610. close(pip[0]);
  4611. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4612. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4613. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4614. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4615. signal(SIGPIPE, SIG_DFL);
  4616. if (redir->type == NHERE)
  4617. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4618. else /* NXHERE */
  4619. expandhere(redir->nhere.doc, pip[1]);
  4620. _exit(EXIT_SUCCESS);
  4621. }
  4622. out:
  4623. close(pip[1]);
  4624. return pip[0];
  4625. }
  4626. static int
  4627. openredirect(union node *redir)
  4628. {
  4629. char *fname;
  4630. int f;
  4631. fname = redir->nfile.expfname;
  4632. switch (redir->nfile.type) {
  4633. case NFROM:
  4634. f = open(fname, O_RDONLY);
  4635. if (f < 0)
  4636. goto eopen;
  4637. break;
  4638. case NFROMTO:
  4639. f = open(fname, O_RDWR|O_CREAT, 0666);
  4640. if (f < 0)
  4641. goto ecreate;
  4642. break;
  4643. case NTO:
  4644. #if ENABLE_ASH_BASH_COMPAT
  4645. case NTO2:
  4646. #endif
  4647. /* Take care of noclobber mode. */
  4648. if (Cflag) {
  4649. f = noclobberopen(fname);
  4650. if (f < 0)
  4651. goto ecreate;
  4652. break;
  4653. }
  4654. /* FALLTHROUGH */
  4655. case NCLOBBER:
  4656. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4657. if (f < 0)
  4658. goto ecreate;
  4659. break;
  4660. case NAPPEND:
  4661. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4662. if (f < 0)
  4663. goto ecreate;
  4664. break;
  4665. default:
  4666. #if DEBUG
  4667. abort();
  4668. #endif
  4669. /* Fall through to eliminate warning. */
  4670. /* Our single caller does this itself */
  4671. // case NTOFD:
  4672. // case NFROMFD:
  4673. // f = -1;
  4674. // break;
  4675. case NHERE:
  4676. case NXHERE:
  4677. f = openhere(redir);
  4678. break;
  4679. }
  4680. return f;
  4681. ecreate:
  4682. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4683. eopen:
  4684. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4685. }
  4686. /*
  4687. * Copy a file descriptor to be >= to. Returns -1
  4688. * if the source file descriptor is closed, EMPTY if there are no unused
  4689. * file descriptors left.
  4690. */
  4691. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4692. * old code was doing close(to) prior to copyfd() to achieve the same */
  4693. enum {
  4694. COPYFD_EXACT = (int)~(INT_MAX),
  4695. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4696. };
  4697. static int
  4698. copyfd(int from, int to)
  4699. {
  4700. int newfd;
  4701. if (to & COPYFD_EXACT) {
  4702. to &= ~COPYFD_EXACT;
  4703. /*if (from != to)*/
  4704. newfd = dup2(from, to);
  4705. } else {
  4706. newfd = fcntl(from, F_DUPFD, to);
  4707. }
  4708. if (newfd < 0) {
  4709. if (errno == EMFILE)
  4710. return EMPTY;
  4711. /* Happens when source fd is not open: try "echo >&99" */
  4712. ash_msg_and_raise_error("%d: %m", from);
  4713. }
  4714. return newfd;
  4715. }
  4716. /* Struct def and variable are moved down to the first usage site */
  4717. struct two_fd_t {
  4718. int orig, copy;
  4719. };
  4720. struct redirtab {
  4721. struct redirtab *next;
  4722. int nullredirs;
  4723. int pair_count;
  4724. struct two_fd_t two_fd[];
  4725. };
  4726. #define redirlist (G_var.redirlist)
  4727. static int need_to_remember(struct redirtab *rp, int fd)
  4728. {
  4729. int i;
  4730. if (!rp) /* remembering was not requested */
  4731. return 0;
  4732. for (i = 0; i < rp->pair_count; i++) {
  4733. if (rp->two_fd[i].orig == fd) {
  4734. /* already remembered */
  4735. return 0;
  4736. }
  4737. }
  4738. return 1;
  4739. }
  4740. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4741. static int is_hidden_fd(struct redirtab *rp, int fd)
  4742. {
  4743. int i;
  4744. struct parsefile *pf;
  4745. if (fd == -1)
  4746. return 0;
  4747. /* Check open scripts' fds */
  4748. pf = g_parsefile;
  4749. while (pf) {
  4750. /* We skip pf_fd == 0 case because of the following case:
  4751. * $ ash # running ash interactively
  4752. * $ . ./script.sh
  4753. * and in script.sh: "exec 9>&0".
  4754. * Even though top-level pf_fd _is_ 0,
  4755. * it's still ok to use it: "read" builtin uses it,
  4756. * why should we cripple "exec" builtin?
  4757. */
  4758. if (pf->pf_fd > 0 && fd == pf->pf_fd) {
  4759. return 1;
  4760. }
  4761. pf = pf->prev;
  4762. }
  4763. if (!rp)
  4764. return 0;
  4765. /* Check saved fds of redirects */
  4766. fd |= COPYFD_RESTORE;
  4767. for (i = 0; i < rp->pair_count; i++) {
  4768. if (rp->two_fd[i].copy == fd) {
  4769. return 1;
  4770. }
  4771. }
  4772. return 0;
  4773. }
  4774. /*
  4775. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4776. * old file descriptors are stashed away so that the redirection can be
  4777. * undone by calling popredir.
  4778. */
  4779. /* flags passed to redirect */
  4780. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4781. #define REDIR_SAVEFD2 03 /* set preverrout */
  4782. static void
  4783. redirect(union node *redir, int flags)
  4784. {
  4785. struct redirtab *sv;
  4786. int sv_pos;
  4787. int i;
  4788. int fd;
  4789. int newfd;
  4790. int copied_fd2 = -1;
  4791. g_nullredirs++;
  4792. if (!redir) {
  4793. return;
  4794. }
  4795. sv = NULL;
  4796. sv_pos = 0;
  4797. INT_OFF;
  4798. if (flags & REDIR_PUSH) {
  4799. union node *tmp = redir;
  4800. do {
  4801. sv_pos++;
  4802. #if ENABLE_ASH_BASH_COMPAT
  4803. if (tmp->nfile.type == NTO2)
  4804. sv_pos++;
  4805. #endif
  4806. tmp = tmp->nfile.next;
  4807. } while (tmp);
  4808. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4809. sv->next = redirlist;
  4810. sv->pair_count = sv_pos;
  4811. redirlist = sv;
  4812. sv->nullredirs = g_nullredirs - 1;
  4813. g_nullredirs = 0;
  4814. while (sv_pos > 0) {
  4815. sv_pos--;
  4816. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4817. }
  4818. }
  4819. do {
  4820. int right_fd = -1;
  4821. fd = redir->nfile.fd;
  4822. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4823. right_fd = redir->ndup.dupfd;
  4824. //bb_error_msg("doing %d > %d", fd, right_fd);
  4825. /* redirect from/to same file descriptor? */
  4826. if (right_fd == fd)
  4827. continue;
  4828. /* "echo >&10" and 10 is a fd opened to a sh script? */
  4829. if (is_hidden_fd(sv, right_fd)) {
  4830. errno = EBADF; /* as if it is closed */
  4831. ash_msg_and_raise_error("%d: %m", right_fd);
  4832. }
  4833. newfd = -1;
  4834. } else {
  4835. newfd = openredirect(redir); /* always >= 0 */
  4836. if (fd == newfd) {
  4837. /* Descriptor wasn't open before redirect.
  4838. * Mark it for close in the future */
  4839. if (need_to_remember(sv, fd)) {
  4840. goto remember_to_close;
  4841. }
  4842. continue;
  4843. }
  4844. }
  4845. #if ENABLE_ASH_BASH_COMPAT
  4846. redirect_more:
  4847. #endif
  4848. if (need_to_remember(sv, fd)) {
  4849. /* Copy old descriptor */
  4850. /* Careful to not accidentally "save"
  4851. * to the same fd as right side fd in N>&M */
  4852. int minfd = right_fd < 10 ? 10 : right_fd + 1;
  4853. i = fcntl(fd, F_DUPFD, minfd);
  4854. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4855. * are closed in popredir() in the child, preventing them from leaking
  4856. * into child. (popredir() also cleans up the mess in case of failures)
  4857. */
  4858. if (i == -1) {
  4859. i = errno;
  4860. if (i != EBADF) {
  4861. /* Strange error (e.g. "too many files" EMFILE?) */
  4862. if (newfd >= 0)
  4863. close(newfd);
  4864. errno = i;
  4865. ash_msg_and_raise_error("%d: %m", fd);
  4866. /* NOTREACHED */
  4867. }
  4868. /* EBADF: it is not open - good, remember to close it */
  4869. remember_to_close:
  4870. i = CLOSED;
  4871. } else { /* fd is open, save its copy */
  4872. /* "exec fd>&-" should not close fds
  4873. * which point to script file(s).
  4874. * Force them to be restored afterwards */
  4875. if (is_hidden_fd(sv, fd))
  4876. i |= COPYFD_RESTORE;
  4877. }
  4878. if (fd == 2)
  4879. copied_fd2 = i;
  4880. sv->two_fd[sv_pos].orig = fd;
  4881. sv->two_fd[sv_pos].copy = i;
  4882. sv_pos++;
  4883. }
  4884. if (newfd < 0) {
  4885. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4886. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4887. /* Don't want to trigger debugging */
  4888. if (fd != -1)
  4889. close(fd);
  4890. } else {
  4891. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4892. }
  4893. } else if (fd != newfd) { /* move newfd to fd */
  4894. copyfd(newfd, fd | COPYFD_EXACT);
  4895. #if ENABLE_ASH_BASH_COMPAT
  4896. if (!(redir->nfile.type == NTO2 && fd == 2))
  4897. #endif
  4898. close(newfd);
  4899. }
  4900. #if ENABLE_ASH_BASH_COMPAT
  4901. if (redir->nfile.type == NTO2 && fd == 1) {
  4902. /* We already redirected it to fd 1, now copy it to 2 */
  4903. newfd = 1;
  4904. fd = 2;
  4905. goto redirect_more;
  4906. }
  4907. #endif
  4908. } while ((redir = redir->nfile.next) != NULL);
  4909. INT_ON;
  4910. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4911. preverrout_fd = copied_fd2;
  4912. }
  4913. /*
  4914. * Undo the effects of the last redirection.
  4915. */
  4916. static void
  4917. popredir(int drop, int restore)
  4918. {
  4919. struct redirtab *rp;
  4920. int i;
  4921. if (--g_nullredirs >= 0 || redirlist == NULL)
  4922. return;
  4923. INT_OFF;
  4924. rp = redirlist;
  4925. for (i = 0; i < rp->pair_count; i++) {
  4926. int fd = rp->two_fd[i].orig;
  4927. int copy = rp->two_fd[i].copy;
  4928. if (copy == CLOSED) {
  4929. if (!drop)
  4930. close(fd);
  4931. continue;
  4932. }
  4933. if (copy != EMPTY) {
  4934. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4935. copy &= ~COPYFD_RESTORE;
  4936. /*close(fd);*/
  4937. copyfd(copy, fd | COPYFD_EXACT);
  4938. }
  4939. close(copy & ~COPYFD_RESTORE);
  4940. }
  4941. }
  4942. redirlist = rp->next;
  4943. g_nullredirs = rp->nullredirs;
  4944. free(rp);
  4945. INT_ON;
  4946. }
  4947. /*
  4948. * Undo all redirections. Called on error or interrupt.
  4949. */
  4950. /*
  4951. * Discard all saved file descriptors.
  4952. */
  4953. static void
  4954. clearredir(int drop)
  4955. {
  4956. for (;;) {
  4957. g_nullredirs = 0;
  4958. if (!redirlist)
  4959. break;
  4960. popredir(drop, /*restore:*/ 0);
  4961. }
  4962. }
  4963. static int
  4964. redirectsafe(union node *redir, int flags)
  4965. {
  4966. int err;
  4967. volatile int saveint;
  4968. struct jmploc *volatile savehandler = exception_handler;
  4969. struct jmploc jmploc;
  4970. SAVE_INT(saveint);
  4971. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4972. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4973. if (!err) {
  4974. exception_handler = &jmploc;
  4975. redirect(redir, flags);
  4976. }
  4977. exception_handler = savehandler;
  4978. if (err && exception_type != EXERROR)
  4979. longjmp(exception_handler->loc, 1);
  4980. RESTORE_INT(saveint);
  4981. return err;
  4982. }
  4983. /* ============ Routines to expand arguments to commands
  4984. *
  4985. * We have to deal with backquotes, shell variables, and file metacharacters.
  4986. */
  4987. #if ENABLE_SH_MATH_SUPPORT
  4988. static arith_t
  4989. ash_arith(const char *s)
  4990. {
  4991. arith_state_t math_state;
  4992. arith_t result;
  4993. math_state.lookupvar = lookupvar;
  4994. math_state.setvar = setvar0;
  4995. //math_state.endofname = endofname;
  4996. INT_OFF;
  4997. result = arith(&math_state, s);
  4998. if (math_state.errmsg)
  4999. ash_msg_and_raise_error(math_state.errmsg);
  5000. INT_ON;
  5001. return result;
  5002. }
  5003. #endif
  5004. /*
  5005. * expandarg flags
  5006. */
  5007. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5008. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5009. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5010. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5011. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5012. #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
  5013. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5014. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5015. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5016. /*
  5017. * rmescape() flags
  5018. */
  5019. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5020. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5021. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5022. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5023. #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
  5024. /* Add CTLESC when necessary. */
  5025. #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
  5026. /* Do not skip NUL characters. */
  5027. #define QUOTES_KEEPNUL EXP_TILDE
  5028. /*
  5029. * Structure specifying which parts of the string should be searched
  5030. * for IFS characters.
  5031. */
  5032. struct ifsregion {
  5033. struct ifsregion *next; /* next region in list */
  5034. int begoff; /* offset of start of region */
  5035. int endoff; /* offset of end of region */
  5036. int nulonly; /* search for nul bytes only */
  5037. };
  5038. struct arglist {
  5039. struct strlist *list;
  5040. struct strlist **lastp;
  5041. };
  5042. /* output of current string */
  5043. static char *expdest;
  5044. /* list of back quote expressions */
  5045. static struct nodelist *argbackq;
  5046. /* first struct in list of ifs regions */
  5047. static struct ifsregion ifsfirst;
  5048. /* last struct in list */
  5049. static struct ifsregion *ifslastp;
  5050. /* holds expanded arg list */
  5051. static struct arglist exparg;
  5052. /*
  5053. * Our own itoa().
  5054. */
  5055. #if !ENABLE_SH_MATH_SUPPORT
  5056. /* cvtnum() is used even if math support is off (to prepare $? values and such) */
  5057. typedef long arith_t;
  5058. # define ARITH_FMT "%ld"
  5059. #endif
  5060. static int
  5061. cvtnum(arith_t num)
  5062. {
  5063. int len;
  5064. expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
  5065. len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
  5066. STADJUST(len, expdest);
  5067. return len;
  5068. }
  5069. static size_t
  5070. esclen(const char *start, const char *p)
  5071. {
  5072. size_t esc = 0;
  5073. while (p > start && (unsigned char)*--p == CTLESC) {
  5074. esc++;
  5075. }
  5076. return esc;
  5077. }
  5078. /*
  5079. * Remove any CTLESC characters from a string.
  5080. */
  5081. static char *
  5082. rmescapes(char *str, int flag)
  5083. {
  5084. static const char qchars[] ALIGN1 = {
  5085. IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5086. char *p, *q, *r;
  5087. unsigned inquotes;
  5088. unsigned protect_against_glob;
  5089. unsigned globbing;
  5090. IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
  5091. p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
  5092. if (!p)
  5093. return str;
  5094. q = p;
  5095. r = str;
  5096. if (flag & RMESCAPE_ALLOC) {
  5097. size_t len = p - str;
  5098. size_t fulllen = len + strlen(p) + 1;
  5099. if (flag & RMESCAPE_GROW) {
  5100. int strloc = str - (char *)stackblock();
  5101. r = makestrspace(fulllen, expdest);
  5102. /* p and str may be invalidated by makestrspace */
  5103. str = (char *)stackblock() + strloc;
  5104. p = str + len;
  5105. } else if (flag & RMESCAPE_HEAP) {
  5106. r = ckmalloc(fulllen);
  5107. } else {
  5108. r = stalloc(fulllen);
  5109. }
  5110. q = r;
  5111. if (len > 0) {
  5112. q = (char *)memcpy(q, str, len) + len;
  5113. }
  5114. }
  5115. inquotes = 0;
  5116. globbing = flag & RMESCAPE_GLOB;
  5117. protect_against_glob = globbing;
  5118. while (*p) {
  5119. if ((unsigned char)*p == CTLQUOTEMARK) {
  5120. // Note: both inquotes and protect_against_glob only affect whether
  5121. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5122. inquotes = ~inquotes;
  5123. p++;
  5124. protect_against_glob = globbing;
  5125. continue;
  5126. }
  5127. if ((unsigned char)*p == CTLESC) {
  5128. p++;
  5129. if (protect_against_glob) {
  5130. *q++ = '\\';
  5131. }
  5132. } else if (*p == '\\' && !inquotes) {
  5133. /* naked back slash */
  5134. protect_against_glob = 0;
  5135. goto copy;
  5136. }
  5137. #if ENABLE_ASH_BASH_COMPAT
  5138. else if (*p == '/' && slash) {
  5139. /* stop handling globbing and mark location of slash */
  5140. globbing = slash = 0;
  5141. *p = CTLESC;
  5142. }
  5143. #endif
  5144. protect_against_glob = globbing;
  5145. copy:
  5146. *q++ = *p++;
  5147. }
  5148. *q = '\0';
  5149. if (flag & RMESCAPE_GROW) {
  5150. expdest = r;
  5151. STADJUST(q - r + 1, expdest);
  5152. }
  5153. return r;
  5154. }
  5155. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5156. /*
  5157. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5158. *
  5159. * Returns an stalloced string.
  5160. */
  5161. static char *
  5162. preglob(const char *pattern, int flag)
  5163. {
  5164. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
  5165. }
  5166. /*
  5167. * Put a string on the stack.
  5168. */
  5169. static void
  5170. memtodest(const char *p, size_t len, int syntax, int quotes)
  5171. {
  5172. char *q;
  5173. if (!len)
  5174. return;
  5175. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5176. do {
  5177. unsigned char c = *p++;
  5178. if (c) {
  5179. int n = SIT(c, syntax);
  5180. if ((quotes & QUOTES_ESC) &&
  5181. ((n == CCTL) ||
  5182. (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
  5183. n == CBACK)))
  5184. USTPUTC(CTLESC, q);
  5185. } else if (!(quotes & QUOTES_KEEPNUL))
  5186. continue;
  5187. USTPUTC(c, q);
  5188. } while (--len);
  5189. expdest = q;
  5190. }
  5191. static size_t
  5192. strtodest(const char *p, int syntax, int quotes)
  5193. {
  5194. size_t len = strlen(p);
  5195. memtodest(p, len, syntax, quotes);
  5196. return len;
  5197. }
  5198. /*
  5199. * Record the fact that we have to scan this region of the
  5200. * string for IFS characters.
  5201. */
  5202. static void
  5203. recordregion(int start, int end, int nulonly)
  5204. {
  5205. struct ifsregion *ifsp;
  5206. if (ifslastp == NULL) {
  5207. ifsp = &ifsfirst;
  5208. } else {
  5209. INT_OFF;
  5210. ifsp = ckzalloc(sizeof(*ifsp));
  5211. /*ifsp->next = NULL; - ckzalloc did it */
  5212. ifslastp->next = ifsp;
  5213. INT_ON;
  5214. }
  5215. ifslastp = ifsp;
  5216. ifslastp->begoff = start;
  5217. ifslastp->endoff = end;
  5218. ifslastp->nulonly = nulonly;
  5219. }
  5220. static void
  5221. removerecordregions(int endoff)
  5222. {
  5223. if (ifslastp == NULL)
  5224. return;
  5225. if (ifsfirst.endoff > endoff) {
  5226. while (ifsfirst.next) {
  5227. struct ifsregion *ifsp;
  5228. INT_OFF;
  5229. ifsp = ifsfirst.next->next;
  5230. free(ifsfirst.next);
  5231. ifsfirst.next = ifsp;
  5232. INT_ON;
  5233. }
  5234. if (ifsfirst.begoff > endoff) {
  5235. ifslastp = NULL;
  5236. } else {
  5237. ifslastp = &ifsfirst;
  5238. ifsfirst.endoff = endoff;
  5239. }
  5240. return;
  5241. }
  5242. ifslastp = &ifsfirst;
  5243. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5244. ifslastp = ifslastp->next;
  5245. while (ifslastp->next) {
  5246. struct ifsregion *ifsp;
  5247. INT_OFF;
  5248. ifsp = ifslastp->next->next;
  5249. free(ifslastp->next);
  5250. ifslastp->next = ifsp;
  5251. INT_ON;
  5252. }
  5253. if (ifslastp->endoff > endoff)
  5254. ifslastp->endoff = endoff;
  5255. }
  5256. static char *
  5257. exptilde(char *startp, char *p, int flags)
  5258. {
  5259. unsigned char c;
  5260. char *name;
  5261. struct passwd *pw;
  5262. const char *home;
  5263. int quotes = flags & QUOTES_ESC;
  5264. name = p + 1;
  5265. while ((c = *++p) != '\0') {
  5266. switch (c) {
  5267. case CTLESC:
  5268. return startp;
  5269. case CTLQUOTEMARK:
  5270. return startp;
  5271. case ':':
  5272. if (flags & EXP_VARTILDE)
  5273. goto done;
  5274. break;
  5275. case '/':
  5276. case CTLENDVAR:
  5277. goto done;
  5278. }
  5279. }
  5280. done:
  5281. *p = '\0';
  5282. if (*name == '\0') {
  5283. home = lookupvar("HOME");
  5284. } else {
  5285. pw = getpwnam(name);
  5286. if (pw == NULL)
  5287. goto lose;
  5288. home = pw->pw_dir;
  5289. }
  5290. if (!home || !*home)
  5291. goto lose;
  5292. *p = c;
  5293. strtodest(home, SQSYNTAX, quotes);
  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 flag)
  5359. {
  5360. struct backcmd in;
  5361. int i;
  5362. char buf[128];
  5363. char *p;
  5364. char *dest;
  5365. int startloc;
  5366. int syntax = flag & EXP_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, flag & QUOTES_ESC);
  5381. read:
  5382. if (in.fd < 0)
  5383. break;
  5384. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  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 (!(flag & EXP_QUOTED))
  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 flag)
  5415. {
  5416. char *p, *start;
  5417. int begoff;
  5418. int len;
  5419. /* ifsfree(); */
  5420. /*
  5421. * This routine is slightly over-complicated for
  5422. * efficiency. Next we scan backwards looking for the
  5423. * start of arithmetic.
  5424. */
  5425. start = stackblock();
  5426. p = expdest - 1;
  5427. *p = '\0';
  5428. p--;
  5429. while (1) {
  5430. int esc;
  5431. while ((unsigned char)*p != CTLARI) {
  5432. p--;
  5433. #if DEBUG
  5434. if (p < start) {
  5435. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5436. }
  5437. #endif
  5438. }
  5439. esc = esclen(start, p);
  5440. if (!(esc % 2)) {
  5441. break;
  5442. }
  5443. p -= esc + 1;
  5444. }
  5445. begoff = p - start;
  5446. removerecordregions(begoff);
  5447. expdest = p;
  5448. if (flag & QUOTES_ESC)
  5449. rmescapes(p + 1, 0);
  5450. len = cvtnum(ash_arith(p + 1));
  5451. if (!(flag & EXP_QUOTED))
  5452. recordregion(begoff, begoff + len, 0);
  5453. }
  5454. #endif
  5455. /* argstr needs it */
  5456. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5457. /*
  5458. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5459. * characters to allow for further processing. Otherwise treat
  5460. * $@ like $* since no splitting will be performed.
  5461. *
  5462. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5463. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5464. * for correct expansion of "B=$A" word.
  5465. */
  5466. static void
  5467. argstr(char *p, int flags, struct strlist *var_str_list)
  5468. {
  5469. static const char spclchars[] ALIGN1 = {
  5470. '=',
  5471. ':',
  5472. CTLQUOTEMARK,
  5473. CTLENDVAR,
  5474. CTLESC,
  5475. CTLVAR,
  5476. CTLBACKQ,
  5477. #if ENABLE_SH_MATH_SUPPORT
  5478. CTLENDARI,
  5479. #endif
  5480. '\0'
  5481. };
  5482. const char *reject = spclchars;
  5483. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5484. int inquotes;
  5485. size_t length;
  5486. int startloc;
  5487. if (!(flags & EXP_VARTILDE)) {
  5488. reject += 2;
  5489. } else if (flags & EXP_VARTILDE2) {
  5490. reject++;
  5491. }
  5492. inquotes = 0;
  5493. length = 0;
  5494. if (flags & EXP_TILDE) {
  5495. char *q;
  5496. flags &= ~EXP_TILDE;
  5497. tilde:
  5498. q = p;
  5499. if (*q == '~')
  5500. p = exptilde(p, q, flags);
  5501. }
  5502. start:
  5503. startloc = expdest - (char *)stackblock();
  5504. for (;;) {
  5505. unsigned char c;
  5506. length += strcspn(p + length, reject);
  5507. c = p[length];
  5508. if (c) {
  5509. if (!(c & 0x80)
  5510. IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
  5511. ) {
  5512. /* c == '=' || c == ':' || c == CTLENDARI */
  5513. length++;
  5514. }
  5515. }
  5516. if (length > 0) {
  5517. int newloc;
  5518. expdest = stack_nputstr(p, length, expdest);
  5519. newloc = expdest - (char *)stackblock();
  5520. if (breakall && !inquotes && newloc > startloc) {
  5521. recordregion(startloc, newloc, 0);
  5522. }
  5523. startloc = newloc;
  5524. }
  5525. p += length + 1;
  5526. length = 0;
  5527. switch (c) {
  5528. case '\0':
  5529. goto breakloop;
  5530. case '=':
  5531. if (flags & EXP_VARTILDE2) {
  5532. p--;
  5533. continue;
  5534. }
  5535. flags |= EXP_VARTILDE2;
  5536. reject++;
  5537. /* fall through */
  5538. case ':':
  5539. /*
  5540. * sort of a hack - expand tildes in variable
  5541. * assignments (after the first '=' and after ':'s).
  5542. */
  5543. if (*--p == '~') {
  5544. goto tilde;
  5545. }
  5546. continue;
  5547. }
  5548. switch (c) {
  5549. case CTLENDVAR: /* ??? */
  5550. goto breakloop;
  5551. case CTLQUOTEMARK:
  5552. inquotes ^= EXP_QUOTED;
  5553. /* "$@" syntax adherence hack */
  5554. if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  5555. p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
  5556. goto start;
  5557. }
  5558. addquote:
  5559. if (flags & QUOTES_ESC) {
  5560. p--;
  5561. length++;
  5562. startloc++;
  5563. }
  5564. break;
  5565. case CTLESC:
  5566. startloc++;
  5567. length++;
  5568. /*
  5569. * Quoted parameter expansion pattern: remove quote
  5570. * unless inside inner quotes or we have a literal
  5571. * backslash.
  5572. */
  5573. if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
  5574. EXP_QPAT && *p != '\\')
  5575. break;
  5576. goto addquote;
  5577. case CTLVAR:
  5578. TRACE(("argstr: evalvar('%s')\n", p));
  5579. p = evalvar(p, flags | inquotes, var_str_list);
  5580. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  5581. goto start;
  5582. case CTLBACKQ:
  5583. expbackq(argbackq->n, flags | inquotes);
  5584. argbackq = argbackq->next;
  5585. goto start;
  5586. #if ENABLE_SH_MATH_SUPPORT
  5587. case CTLENDARI:
  5588. p--;
  5589. expari(flags | inquotes);
  5590. goto start;
  5591. #endif
  5592. }
  5593. }
  5594. breakloop: ;
  5595. }
  5596. static char *
  5597. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  5598. char *pattern, int quotes, int zero)
  5599. {
  5600. char *loc, *loc2;
  5601. char c;
  5602. loc = startp;
  5603. loc2 = rmesc;
  5604. do {
  5605. int match;
  5606. const char *s = loc2;
  5607. c = *loc2;
  5608. if (zero) {
  5609. *loc2 = '\0';
  5610. s = rmesc;
  5611. }
  5612. match = pmatch(pattern, s);
  5613. *loc2 = c;
  5614. if (match)
  5615. return loc;
  5616. if (quotes && (unsigned char)*loc == CTLESC)
  5617. loc++;
  5618. loc++;
  5619. loc2++;
  5620. } while (c);
  5621. return NULL;
  5622. }
  5623. static char *
  5624. scanright(char *startp, char *rmesc, char *rmescend,
  5625. char *pattern, int quotes, int match_at_start)
  5626. {
  5627. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5628. int try2optimize = match_at_start;
  5629. #endif
  5630. int esc = 0;
  5631. char *loc;
  5632. char *loc2;
  5633. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5634. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5635. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5636. * Logic:
  5637. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5638. * and on each iteration they go back two/one char until they reach the beginning.
  5639. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5640. */
  5641. /* TODO: document in what other circumstances we are called. */
  5642. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5643. int match;
  5644. char c = *loc2;
  5645. const char *s = loc2;
  5646. if (match_at_start) {
  5647. *loc2 = '\0';
  5648. s = rmesc;
  5649. }
  5650. match = pmatch(pattern, s);
  5651. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5652. *loc2 = c;
  5653. if (match)
  5654. return loc;
  5655. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5656. if (try2optimize) {
  5657. /* Maybe we can optimize this:
  5658. * if pattern ends with unescaped *, we can avoid checking
  5659. * shorter strings: if "foo*" doesnt match "raw_value_of_v",
  5660. * it wont match truncated "raw_value_of_" strings too.
  5661. */
  5662. unsigned plen = strlen(pattern);
  5663. /* Does it end with "*"? */
  5664. if (plen != 0 && pattern[--plen] == '*') {
  5665. /* "xxxx*" is not escaped */
  5666. /* "xxx\*" is escaped */
  5667. /* "xx\\*" is not escaped */
  5668. /* "x\\\*" is escaped */
  5669. int slashes = 0;
  5670. while (plen != 0 && pattern[--plen] == '\\')
  5671. slashes++;
  5672. if (!(slashes & 1))
  5673. break; /* ends with unescaped "*" */
  5674. }
  5675. try2optimize = 0;
  5676. }
  5677. #endif
  5678. loc--;
  5679. if (quotes) {
  5680. if (--esc < 0) {
  5681. esc = esclen(startp, loc);
  5682. }
  5683. if (esc % 2) {
  5684. esc--;
  5685. loc--;
  5686. }
  5687. }
  5688. }
  5689. return NULL;
  5690. }
  5691. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5692. static void
  5693. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5694. {
  5695. const char *msg;
  5696. const char *tail;
  5697. tail = nullstr;
  5698. msg = "parameter not set";
  5699. if (umsg) {
  5700. if ((unsigned char)*end == CTLENDVAR) {
  5701. if (varflags & VSNUL)
  5702. tail = " or null";
  5703. } else {
  5704. msg = umsg;
  5705. }
  5706. }
  5707. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  5708. }
  5709. static const char *
  5710. subevalvar(char *p, char *varname, int strloc, int subtype,
  5711. int startloc, int varflags, int flag, struct strlist *var_str_list)
  5712. {
  5713. struct nodelist *saveargbackq = argbackq;
  5714. int quotes = flag & QUOTES_ESC;
  5715. char *startp;
  5716. char *loc;
  5717. char *rmesc, *rmescend;
  5718. char *str;
  5719. IF_ASH_BASH_COMPAT(char *repl = NULL;)
  5720. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5721. int saveherefd = herefd;
  5722. int amount, resetloc;
  5723. IF_ASH_BASH_COMPAT(int workloc;)
  5724. int zero;
  5725. char *(*scan)(char*, char*, char*, char*, int, int);
  5726. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  5727. // p, varname, strloc, subtype, startloc, varflags, quotes);
  5728. herefd = -1;
  5729. argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
  5730. (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
  5731. var_str_list);
  5732. STPUTC('\0', expdest);
  5733. herefd = saveherefd;
  5734. argbackq = saveargbackq;
  5735. startp = (char *)stackblock() + startloc;
  5736. switch (subtype) {
  5737. case VSASSIGN:
  5738. setvar0(varname, startp);
  5739. amount = startp - expdest;
  5740. STADJUST(amount, expdest);
  5741. return startp;
  5742. case VSQUESTION:
  5743. varunset(p, varname, startp, varflags);
  5744. /* NOTREACHED */
  5745. #if ENABLE_ASH_BASH_COMPAT
  5746. case VSSUBSTR:
  5747. loc = str = stackblock() + strloc;
  5748. /* Read POS in ${var:POS:LEN} */
  5749. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5750. len = str - startp - 1;
  5751. /* *loc != '\0', guaranteed by parser */
  5752. if (quotes) {
  5753. char *ptr;
  5754. /* Adjust the length by the number of escapes */
  5755. for (ptr = startp; ptr < (str - 1); ptr++) {
  5756. if ((unsigned char)*ptr == CTLESC) {
  5757. len--;
  5758. ptr++;
  5759. }
  5760. }
  5761. }
  5762. orig_len = len;
  5763. if (*loc++ == ':') {
  5764. /* ${var::LEN} */
  5765. len = number(loc);
  5766. } else {
  5767. /* Skip POS in ${var:POS:LEN} */
  5768. len = orig_len;
  5769. while (*loc && *loc != ':') {
  5770. /* TODO?
  5771. * bash complains on: var=qwe; echo ${var:1a:123}
  5772. if (!isdigit(*loc))
  5773. ash_msg_and_raise_error(msg_illnum, str);
  5774. */
  5775. loc++;
  5776. }
  5777. if (*loc++ == ':') {
  5778. len = number(loc);
  5779. }
  5780. }
  5781. if (pos < 0) {
  5782. /* ${VAR:$((-n)):l} starts n chars from the end */
  5783. pos = orig_len + pos;
  5784. }
  5785. if ((unsigned)pos >= orig_len) {
  5786. /* apart from obvious ${VAR:999999:l},
  5787. * covers ${VAR:$((-9999999)):l} - result is ""
  5788. * (bash-compat)
  5789. */
  5790. pos = 0;
  5791. len = 0;
  5792. }
  5793. if (len > (orig_len - pos))
  5794. len = orig_len - pos;
  5795. for (str = startp; pos; str++, pos--) {
  5796. if (quotes && (unsigned char)*str == CTLESC)
  5797. str++;
  5798. }
  5799. for (loc = startp; len; len--) {
  5800. if (quotes && (unsigned char)*str == CTLESC)
  5801. *loc++ = *str++;
  5802. *loc++ = *str++;
  5803. }
  5804. *loc = '\0';
  5805. amount = loc - expdest;
  5806. STADJUST(amount, expdest);
  5807. return loc;
  5808. #endif
  5809. }
  5810. resetloc = expdest - (char *)stackblock();
  5811. /* We'll comeback here if we grow the stack while handling
  5812. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5813. * stack will need rebasing, and we'll need to remove our work
  5814. * areas each time
  5815. */
  5816. IF_ASH_BASH_COMPAT(restart:)
  5817. amount = expdest - ((char *)stackblock() + resetloc);
  5818. STADJUST(-amount, expdest);
  5819. startp = (char *)stackblock() + startloc;
  5820. rmesc = startp;
  5821. rmescend = (char *)stackblock() + strloc;
  5822. if (quotes) {
  5823. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5824. if (rmesc != startp) {
  5825. rmescend = expdest;
  5826. startp = (char *)stackblock() + startloc;
  5827. }
  5828. }
  5829. rmescend--;
  5830. str = (char *)stackblock() + strloc;
  5831. /*
  5832. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  5833. * The result is a_\_z_c (not a\_\_z_c)!
  5834. *
  5835. * The search pattern and replace string treat backslashes differently!
  5836. * RMESCAPE_SLASH causes preglob to work differently on the pattern
  5837. * and string. It's only used on the first call.
  5838. */
  5839. preglob(str, IF_ASH_BASH_COMPAT(
  5840. (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
  5841. RMESCAPE_SLASH :) 0);
  5842. #if ENABLE_ASH_BASH_COMPAT
  5843. workloc = expdest - (char *)stackblock();
  5844. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5845. char *idx, *end;
  5846. if (!repl) {
  5847. if ((repl=strchr(str, CTLESC)))
  5848. *repl++ = '\0';
  5849. else
  5850. repl = nullstr;
  5851. }
  5852. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  5853. /* If there's no pattern to match, return the expansion unmolested */
  5854. if (str[0] == '\0')
  5855. return NULL;
  5856. len = 0;
  5857. idx = startp;
  5858. end = str - 1;
  5859. while (idx < end) {
  5860. try_to_match:
  5861. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5862. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  5863. if (!loc) {
  5864. /* No match, advance */
  5865. char *restart_detect = stackblock();
  5866. skip_matching:
  5867. STPUTC(*idx, expdest);
  5868. if (quotes && (unsigned char)*idx == CTLESC) {
  5869. idx++;
  5870. len++;
  5871. STPUTC(*idx, expdest);
  5872. }
  5873. if (stackblock() != restart_detect)
  5874. goto restart;
  5875. idx++;
  5876. len++;
  5877. rmesc++;
  5878. /* continue; - prone to quadratic behavior, smarter code: */
  5879. if (idx >= end)
  5880. break;
  5881. if (str[0] == '*') {
  5882. /* Pattern is "*foo". If "*foo" does not match "long_string",
  5883. * it would never match "ong_string" etc, no point in trying.
  5884. */
  5885. goto skip_matching;
  5886. }
  5887. goto try_to_match;
  5888. }
  5889. if (subtype == VSREPLACEALL) {
  5890. while (idx < loc) {
  5891. if (quotes && (unsigned char)*idx == CTLESC)
  5892. idx++;
  5893. idx++;
  5894. rmesc++;
  5895. }
  5896. } else {
  5897. idx = loc;
  5898. }
  5899. //bb_error_msg("repl:'%s'", repl);
  5900. for (loc = (char*)repl; *loc; loc++) {
  5901. char *restart_detect = stackblock();
  5902. if (quotes && *loc == '\\') {
  5903. STPUTC(CTLESC, expdest);
  5904. len++;
  5905. }
  5906. STPUTC(*loc, expdest);
  5907. if (stackblock() != restart_detect)
  5908. goto restart;
  5909. len++;
  5910. }
  5911. if (subtype == VSREPLACE) {
  5912. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  5913. while (*idx) {
  5914. char *restart_detect = stackblock();
  5915. STPUTC(*idx, expdest);
  5916. if (stackblock() != restart_detect)
  5917. goto restart;
  5918. len++;
  5919. idx++;
  5920. }
  5921. break;
  5922. }
  5923. }
  5924. /* We've put the replaced text into a buffer at workloc, now
  5925. * move it to the right place and adjust the stack.
  5926. */
  5927. STPUTC('\0', expdest);
  5928. startp = (char *)stackblock() + startloc;
  5929. memmove(startp, (char *)stackblock() + workloc, len + 1);
  5930. //bb_error_msg("startp:'%s'", startp);
  5931. amount = expdest - (startp + len);
  5932. STADJUST(-amount, expdest);
  5933. return startp;
  5934. }
  5935. #endif /* ENABLE_ASH_BASH_COMPAT */
  5936. subtype -= VSTRIMRIGHT;
  5937. #if DEBUG
  5938. if (subtype < 0 || subtype > 7)
  5939. abort();
  5940. #endif
  5941. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  5942. zero = subtype >> 1;
  5943. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5944. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5945. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5946. if (loc) {
  5947. if (zero) {
  5948. memmove(startp, loc, str - loc);
  5949. loc = startp + (str - loc) - 1;
  5950. }
  5951. *loc = '\0';
  5952. amount = loc - expdest;
  5953. STADJUST(amount, expdest);
  5954. }
  5955. return loc;
  5956. }
  5957. /*
  5958. * Add the value of a specialized variable to the stack string.
  5959. * name parameter (examples):
  5960. * ash -c 'echo $1' name:'1='
  5961. * ash -c 'echo $qwe' name:'qwe='
  5962. * ash -c 'echo $$' name:'$='
  5963. * ash -c 'echo ${$}' name:'$='
  5964. * ash -c 'echo ${$##q}' name:'$=q'
  5965. * ash -c 'echo ${#$}' name:'$='
  5966. * note: examples with bad shell syntax:
  5967. * ash -c 'echo ${#$1}' name:'$=1'
  5968. * ash -c 'echo ${#1#}' name:'1=#'
  5969. */
  5970. static NOINLINE ssize_t
  5971. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5972. {
  5973. const char *p;
  5974. int num;
  5975. int i;
  5976. ssize_t len = 0;
  5977. int sep;
  5978. int quoted = flags & EXP_QUOTED;
  5979. int subtype = varflags & VSTYPE;
  5980. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  5981. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  5982. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5983. sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
  5984. switch (*name) {
  5985. case '$':
  5986. num = rootpid;
  5987. goto numvar;
  5988. case '?':
  5989. num = exitstatus;
  5990. goto numvar;
  5991. case '#':
  5992. num = shellparam.nparam;
  5993. goto numvar;
  5994. case '!':
  5995. num = backgndpid;
  5996. if (num == 0)
  5997. return -1;
  5998. numvar:
  5999. len = cvtnum(num);
  6000. goto check_1char_name;
  6001. case '-':
  6002. expdest = makestrspace(NOPTS, expdest);
  6003. for (i = NOPTS - 1; i >= 0; i--) {
  6004. if (optlist[i]) {
  6005. USTPUTC(optletters(i), expdest);
  6006. len++;
  6007. }
  6008. }
  6009. check_1char_name:
  6010. #if 0
  6011. /* handles cases similar to ${#$1} */
  6012. if (name[2] != '\0')
  6013. raise_error_syntax("bad substitution");
  6014. #endif
  6015. break;
  6016. case '@': {
  6017. char **ap;
  6018. char sepc;
  6019. if (quoted && (flags & EXP_FULL)) {
  6020. /* note: this is not meant as PEOF value */
  6021. sep = 1 << CHAR_BIT;
  6022. goto param;
  6023. }
  6024. /* fall through */
  6025. case '*':
  6026. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  6027. param:
  6028. ap = shellparam.p;
  6029. sepc = sep;
  6030. if (!ap)
  6031. return -1;
  6032. while ((p = *ap++) != NULL) {
  6033. len += strtodest(p, syntax, quotes);
  6034. if (*ap && sep) {
  6035. len++;
  6036. memtodest(&sepc, 1, syntax, quotes);
  6037. }
  6038. }
  6039. break;
  6040. } /* case '@' and '*' */
  6041. case '0':
  6042. case '1':
  6043. case '2':
  6044. case '3':
  6045. case '4':
  6046. case '5':
  6047. case '6':
  6048. case '7':
  6049. case '8':
  6050. case '9':
  6051. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6052. if (num < 0 || num > shellparam.nparam)
  6053. return -1;
  6054. p = num ? shellparam.p[num - 1] : arg0;
  6055. goto value;
  6056. default:
  6057. /* NB: name has form "VAR=..." */
  6058. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  6059. * which should be considered before we check variables. */
  6060. if (var_str_list) {
  6061. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  6062. p = NULL;
  6063. do {
  6064. char *str, *eq;
  6065. str = var_str_list->text;
  6066. eq = strchr(str, '=');
  6067. if (!eq) /* stop at first non-assignment */
  6068. break;
  6069. eq++;
  6070. if (name_len == (unsigned)(eq - str)
  6071. && strncmp(str, name, name_len) == 0
  6072. ) {
  6073. p = eq;
  6074. /* goto value; - WRONG! */
  6075. /* think "A=1 A=2 B=$A" */
  6076. }
  6077. var_str_list = var_str_list->next;
  6078. } while (var_str_list);
  6079. if (p)
  6080. goto value;
  6081. }
  6082. p = lookupvar(name);
  6083. value:
  6084. if (!p)
  6085. return -1;
  6086. len = strtodest(p, syntax, quotes);
  6087. #if ENABLE_UNICODE_SUPPORT
  6088. if (subtype == VSLENGTH && len > 0) {
  6089. reinit_unicode_for_ash();
  6090. if (unicode_status == UNICODE_ON) {
  6091. STADJUST(-len, expdest);
  6092. discard = 0;
  6093. len = unicode_strlen(p);
  6094. }
  6095. }
  6096. #endif
  6097. break;
  6098. }
  6099. if (discard)
  6100. STADJUST(-len, expdest);
  6101. return len;
  6102. }
  6103. /*
  6104. * Expand a variable, and return a pointer to the next character in the
  6105. * input string.
  6106. */
  6107. static char *
  6108. evalvar(char *p, int flags, struct strlist *var_str_list)
  6109. {
  6110. char varflags;
  6111. char subtype;
  6112. int quoted;
  6113. char easy;
  6114. char *var;
  6115. int patloc;
  6116. int startloc;
  6117. ssize_t varlen;
  6118. varflags = (unsigned char) *p++;
  6119. subtype = varflags & VSTYPE;
  6120. quoted = flags & EXP_QUOTED;
  6121. var = p;
  6122. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6123. startloc = expdest - (char *)stackblock();
  6124. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6125. again:
  6126. varlen = varvalue(var, varflags, flags, var_str_list);
  6127. if (varflags & VSNUL)
  6128. varlen--;
  6129. if (subtype == VSPLUS) {
  6130. varlen = -1 - varlen;
  6131. goto vsplus;
  6132. }
  6133. if (subtype == VSMINUS) {
  6134. vsplus:
  6135. if (varlen < 0) {
  6136. argstr(
  6137. p,
  6138. flags | EXP_TILDE | EXP_WORD,
  6139. var_str_list
  6140. );
  6141. goto end;
  6142. }
  6143. if (easy)
  6144. goto record;
  6145. goto end;
  6146. }
  6147. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6148. if (varlen < 0) {
  6149. if (subevalvar(p, var, /* strloc: */ 0,
  6150. subtype, startloc, varflags,
  6151. /* quotes: */ flags & ~QUOTES_ESC,
  6152. var_str_list)
  6153. ) {
  6154. varflags &= ~VSNUL;
  6155. /*
  6156. * Remove any recorded regions beyond
  6157. * start of variable
  6158. */
  6159. removerecordregions(startloc);
  6160. goto again;
  6161. }
  6162. goto end;
  6163. }
  6164. if (easy)
  6165. goto record;
  6166. goto end;
  6167. }
  6168. if (varlen < 0 && uflag)
  6169. varunset(p, var, 0, 0);
  6170. if (subtype == VSLENGTH) {
  6171. cvtnum(varlen > 0 ? varlen : 0);
  6172. goto record;
  6173. }
  6174. if (subtype == VSNORMAL) {
  6175. if (easy)
  6176. goto record;
  6177. goto end;
  6178. }
  6179. #if DEBUG
  6180. switch (subtype) {
  6181. case VSTRIMLEFT:
  6182. case VSTRIMLEFTMAX:
  6183. case VSTRIMRIGHT:
  6184. case VSTRIMRIGHTMAX:
  6185. #if ENABLE_ASH_BASH_COMPAT
  6186. case VSSUBSTR:
  6187. case VSREPLACE:
  6188. case VSREPLACEALL:
  6189. #endif
  6190. break;
  6191. default:
  6192. abort();
  6193. }
  6194. #endif
  6195. if (varlen >= 0) {
  6196. /*
  6197. * Terminate the string and start recording the pattern
  6198. * right after it
  6199. */
  6200. STPUTC('\0', expdest);
  6201. patloc = expdest - (char *)stackblock();
  6202. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6203. startloc, varflags, flags, var_str_list)) {
  6204. int amount = expdest - (
  6205. (char *)stackblock() + patloc - 1
  6206. );
  6207. STADJUST(-amount, expdest);
  6208. }
  6209. /* Remove any recorded regions beyond start of variable */
  6210. removerecordregions(startloc);
  6211. record:
  6212. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6213. }
  6214. end:
  6215. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6216. int nesting = 1;
  6217. for (;;) {
  6218. unsigned char c = *p++;
  6219. if (c == CTLESC)
  6220. p++;
  6221. else if (c == CTLBACKQ) {
  6222. if (varlen >= 0)
  6223. argbackq = argbackq->next;
  6224. } else if (c == CTLVAR) {
  6225. if ((*p++ & VSTYPE) != VSNORMAL)
  6226. nesting++;
  6227. } else if (c == CTLENDVAR) {
  6228. if (--nesting == 0)
  6229. break;
  6230. }
  6231. }
  6232. }
  6233. return p;
  6234. }
  6235. /*
  6236. * Break the argument string into pieces based upon IFS and add the
  6237. * strings to the argument list. The regions of the string to be
  6238. * searched for IFS characters have been stored by recordregion.
  6239. */
  6240. static void
  6241. ifsbreakup(char *string, struct arglist *arglist)
  6242. {
  6243. struct ifsregion *ifsp;
  6244. struct strlist *sp;
  6245. char *start;
  6246. char *p;
  6247. char *q;
  6248. const char *ifs, *realifs;
  6249. int ifsspc;
  6250. int nulonly;
  6251. start = string;
  6252. if (ifslastp != NULL) {
  6253. ifsspc = 0;
  6254. nulonly = 0;
  6255. realifs = ifsset() ? ifsval() : defifs;
  6256. ifsp = &ifsfirst;
  6257. do {
  6258. p = string + ifsp->begoff;
  6259. nulonly = ifsp->nulonly;
  6260. ifs = nulonly ? nullstr : realifs;
  6261. ifsspc = 0;
  6262. while (p < string + ifsp->endoff) {
  6263. q = p;
  6264. if ((unsigned char)*p == CTLESC)
  6265. p++;
  6266. if (!strchr(ifs, *p)) {
  6267. p++;
  6268. continue;
  6269. }
  6270. if (!nulonly)
  6271. ifsspc = (strchr(defifs, *p) != NULL);
  6272. /* Ignore IFS whitespace at start */
  6273. if (q == start && ifsspc) {
  6274. p++;
  6275. start = p;
  6276. continue;
  6277. }
  6278. *q = '\0';
  6279. sp = stzalloc(sizeof(*sp));
  6280. sp->text = start;
  6281. *arglist->lastp = sp;
  6282. arglist->lastp = &sp->next;
  6283. p++;
  6284. if (!nulonly) {
  6285. for (;;) {
  6286. if (p >= string + ifsp->endoff) {
  6287. break;
  6288. }
  6289. q = p;
  6290. if ((unsigned char)*p == CTLESC)
  6291. p++;
  6292. if (strchr(ifs, *p) == NULL) {
  6293. p = q;
  6294. break;
  6295. }
  6296. if (strchr(defifs, *p) == NULL) {
  6297. if (ifsspc) {
  6298. p++;
  6299. ifsspc = 0;
  6300. } else {
  6301. p = q;
  6302. break;
  6303. }
  6304. } else
  6305. p++;
  6306. }
  6307. }
  6308. start = p;
  6309. } /* while */
  6310. ifsp = ifsp->next;
  6311. } while (ifsp != NULL);
  6312. if (nulonly)
  6313. goto add;
  6314. }
  6315. if (!*start)
  6316. return;
  6317. add:
  6318. sp = stzalloc(sizeof(*sp));
  6319. sp->text = start;
  6320. *arglist->lastp = sp;
  6321. arglist->lastp = &sp->next;
  6322. }
  6323. static void
  6324. ifsfree(void)
  6325. {
  6326. struct ifsregion *p;
  6327. INT_OFF;
  6328. p = ifsfirst.next;
  6329. do {
  6330. struct ifsregion *ifsp;
  6331. ifsp = p->next;
  6332. free(p);
  6333. p = ifsp;
  6334. } while (p);
  6335. ifslastp = NULL;
  6336. ifsfirst.next = NULL;
  6337. INT_ON;
  6338. }
  6339. /*
  6340. * Add a file name to the list.
  6341. */
  6342. static void
  6343. addfname(const char *name)
  6344. {
  6345. struct strlist *sp;
  6346. sp = stzalloc(sizeof(*sp));
  6347. sp->text = ststrdup(name);
  6348. *exparg.lastp = sp;
  6349. exparg.lastp = &sp->next;
  6350. }
  6351. /*
  6352. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6353. */
  6354. static void
  6355. expmeta(char *expdir, char *enddir, char *name)
  6356. {
  6357. char *p;
  6358. const char *cp;
  6359. char *start;
  6360. char *endname;
  6361. int metaflag;
  6362. struct stat statb;
  6363. DIR *dirp;
  6364. struct dirent *dp;
  6365. int atend;
  6366. int matchdot;
  6367. int esc;
  6368. metaflag = 0;
  6369. start = name;
  6370. for (p = name; esc = 0, *p; p += esc + 1) {
  6371. if (*p == '*' || *p == '?')
  6372. metaflag = 1;
  6373. else if (*p == '[') {
  6374. char *q = p + 1;
  6375. if (*q == '!')
  6376. q++;
  6377. for (;;) {
  6378. if (*q == '\\')
  6379. q++;
  6380. if (*q == '/' || *q == '\0')
  6381. break;
  6382. if (*++q == ']') {
  6383. metaflag = 1;
  6384. break;
  6385. }
  6386. }
  6387. } else {
  6388. if (*p == '\\')
  6389. esc++;
  6390. if (p[esc] == '/') {
  6391. if (metaflag)
  6392. break;
  6393. start = p + esc + 1;
  6394. }
  6395. }
  6396. }
  6397. if (metaflag == 0) { /* we've reached the end of the file name */
  6398. if (enddir != expdir)
  6399. metaflag++;
  6400. p = name;
  6401. do {
  6402. if (*p == '\\')
  6403. p++;
  6404. *enddir++ = *p;
  6405. } while (*p++);
  6406. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6407. addfname(expdir);
  6408. return;
  6409. }
  6410. endname = p;
  6411. if (name < start) {
  6412. p = name;
  6413. do {
  6414. if (*p == '\\')
  6415. p++;
  6416. *enddir++ = *p++;
  6417. } while (p < start);
  6418. }
  6419. if (enddir == expdir) {
  6420. cp = ".";
  6421. } else if (enddir == expdir + 1 && *expdir == '/') {
  6422. cp = "/";
  6423. } else {
  6424. cp = expdir;
  6425. enddir[-1] = '\0';
  6426. }
  6427. dirp = opendir(cp);
  6428. if (dirp == NULL)
  6429. return;
  6430. if (enddir != expdir)
  6431. enddir[-1] = '/';
  6432. if (*endname == 0) {
  6433. atend = 1;
  6434. } else {
  6435. atend = 0;
  6436. *endname = '\0';
  6437. endname += esc + 1;
  6438. }
  6439. matchdot = 0;
  6440. p = start;
  6441. if (*p == '\\')
  6442. p++;
  6443. if (*p == '.')
  6444. matchdot++;
  6445. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6446. if (dp->d_name[0] == '.' && !matchdot)
  6447. continue;
  6448. if (pmatch(start, dp->d_name)) {
  6449. if (atend) {
  6450. strcpy(enddir, dp->d_name);
  6451. addfname(expdir);
  6452. } else {
  6453. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6454. continue;
  6455. p[-1] = '/';
  6456. expmeta(expdir, p, endname);
  6457. }
  6458. }
  6459. }
  6460. closedir(dirp);
  6461. if (!atend)
  6462. endname[-esc - 1] = esc ? '\\' : '/';
  6463. }
  6464. static struct strlist *
  6465. msort(struct strlist *list, int len)
  6466. {
  6467. struct strlist *p, *q = NULL;
  6468. struct strlist **lpp;
  6469. int half;
  6470. int n;
  6471. if (len <= 1)
  6472. return list;
  6473. half = len >> 1;
  6474. p = list;
  6475. for (n = half; --n >= 0;) {
  6476. q = p;
  6477. p = p->next;
  6478. }
  6479. q->next = NULL; /* terminate first half of list */
  6480. q = msort(list, half); /* sort first half of list */
  6481. p = msort(p, len - half); /* sort second half */
  6482. lpp = &list;
  6483. for (;;) {
  6484. #if ENABLE_LOCALE_SUPPORT
  6485. if (strcoll(p->text, q->text) < 0)
  6486. #else
  6487. if (strcmp(p->text, q->text) < 0)
  6488. #endif
  6489. {
  6490. *lpp = p;
  6491. lpp = &p->next;
  6492. p = *lpp;
  6493. if (p == NULL) {
  6494. *lpp = q;
  6495. break;
  6496. }
  6497. } else {
  6498. *lpp = q;
  6499. lpp = &q->next;
  6500. q = *lpp;
  6501. if (q == NULL) {
  6502. *lpp = p;
  6503. break;
  6504. }
  6505. }
  6506. }
  6507. return list;
  6508. }
  6509. /*
  6510. * Sort the results of file name expansion. It calculates the number of
  6511. * strings to sort and then calls msort (short for merge sort) to do the
  6512. * work.
  6513. */
  6514. static struct strlist *
  6515. expsort(struct strlist *str)
  6516. {
  6517. int len;
  6518. struct strlist *sp;
  6519. len = 0;
  6520. for (sp = str; sp; sp = sp->next)
  6521. len++;
  6522. return msort(str, len);
  6523. }
  6524. static void
  6525. expandmeta(struct strlist *str /*, int flag*/)
  6526. {
  6527. static const char metachars[] ALIGN1 = {
  6528. '*', '?', '[', 0
  6529. };
  6530. /* TODO - EXP_REDIR */
  6531. while (str) {
  6532. char *expdir;
  6533. struct strlist **savelastp;
  6534. struct strlist *sp;
  6535. char *p;
  6536. if (fflag)
  6537. goto nometa;
  6538. if (!strpbrk(str->text, metachars))
  6539. goto nometa;
  6540. savelastp = exparg.lastp;
  6541. INT_OFF;
  6542. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6543. {
  6544. int i = strlen(str->text);
  6545. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6546. }
  6547. expmeta(expdir, expdir, p);
  6548. free(expdir);
  6549. if (p != str->text)
  6550. free(p);
  6551. INT_ON;
  6552. if (exparg.lastp == savelastp) {
  6553. /*
  6554. * no matches
  6555. */
  6556. nometa:
  6557. *exparg.lastp = str;
  6558. rmescapes(str->text, 0);
  6559. exparg.lastp = &str->next;
  6560. } else {
  6561. *exparg.lastp = NULL;
  6562. *savelastp = sp = expsort(*savelastp);
  6563. while (sp->next != NULL)
  6564. sp = sp->next;
  6565. exparg.lastp = &sp->next;
  6566. }
  6567. str = str->next;
  6568. }
  6569. }
  6570. /*
  6571. * Perform variable substitution and command substitution on an argument,
  6572. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6573. * perform splitting and file name expansion. When arglist is NULL, perform
  6574. * here document expansion.
  6575. */
  6576. static void
  6577. expandarg(union node *arg, struct arglist *arglist, int flag)
  6578. {
  6579. struct strlist *sp;
  6580. char *p;
  6581. argbackq = arg->narg.backquote;
  6582. STARTSTACKSTR(expdest);
  6583. ifsfirst.next = NULL;
  6584. ifslastp = NULL;
  6585. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  6586. argstr(arg->narg.text, flag,
  6587. /* var_str_list: */ arglist ? arglist->list : NULL);
  6588. p = _STPUTC('\0', expdest);
  6589. expdest = p - 1;
  6590. if (arglist == NULL) {
  6591. return; /* here document expanded */
  6592. }
  6593. p = grabstackstr(p);
  6594. TRACE(("expandarg: p:'%s'\n", p));
  6595. exparg.lastp = &exparg.list;
  6596. /*
  6597. * TODO - EXP_REDIR
  6598. */
  6599. if (flag & EXP_FULL) {
  6600. ifsbreakup(p, &exparg);
  6601. *exparg.lastp = NULL;
  6602. exparg.lastp = &exparg.list;
  6603. expandmeta(exparg.list /*, flag*/);
  6604. } else {
  6605. if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
  6606. rmescapes(p, 0);
  6607. TRACE(("expandarg: rmescapes:'%s'\n", p));
  6608. }
  6609. sp = stzalloc(sizeof(*sp));
  6610. sp->text = p;
  6611. *exparg.lastp = sp;
  6612. exparg.lastp = &sp->next;
  6613. }
  6614. if (ifsfirst.next)
  6615. ifsfree();
  6616. *exparg.lastp = NULL;
  6617. if (exparg.list) {
  6618. *arglist->lastp = exparg.list;
  6619. arglist->lastp = exparg.lastp;
  6620. }
  6621. }
  6622. /*
  6623. * Expand shell variables and backquotes inside a here document.
  6624. */
  6625. static void
  6626. expandhere(union node *arg, int fd)
  6627. {
  6628. herefd = fd;
  6629. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  6630. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6631. }
  6632. /*
  6633. * Returns true if the pattern matches the string.
  6634. */
  6635. static int
  6636. patmatch(char *pattern, const char *string)
  6637. {
  6638. return pmatch(preglob(pattern, 0), string);
  6639. }
  6640. /*
  6641. * See if a pattern matches in a case statement.
  6642. */
  6643. static int
  6644. casematch(union node *pattern, char *val)
  6645. {
  6646. struct stackmark smark;
  6647. int result;
  6648. setstackmark(&smark);
  6649. argbackq = pattern->narg.backquote;
  6650. STARTSTACKSTR(expdest);
  6651. ifslastp = NULL;
  6652. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6653. /* var_str_list: */ NULL);
  6654. STACKSTRNUL(expdest);
  6655. result = patmatch(stackblock(), val);
  6656. popstackmark(&smark);
  6657. return result;
  6658. }
  6659. /* ============ find_command */
  6660. struct builtincmd {
  6661. const char *name;
  6662. int (*builtin)(int, char **) FAST_FUNC;
  6663. /* unsigned flags; */
  6664. };
  6665. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6666. /* "regular" builtins always take precedence over commands,
  6667. * regardless of PATH=....%builtin... position */
  6668. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6669. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6670. struct cmdentry {
  6671. smallint cmdtype; /* CMDxxx */
  6672. union param {
  6673. int index;
  6674. /* index >= 0 for commands without path (slashes) */
  6675. /* (TODO: what exactly does the value mean? PATH position?) */
  6676. /* index == -1 for commands with slashes */
  6677. /* index == (-2 - applet_no) for NOFORK applets */
  6678. const struct builtincmd *cmd;
  6679. struct funcnode *func;
  6680. } u;
  6681. };
  6682. /* values of cmdtype */
  6683. #define CMDUNKNOWN -1 /* no entry in table for command */
  6684. #define CMDNORMAL 0 /* command is an executable program */
  6685. #define CMDFUNCTION 1 /* command is a shell function */
  6686. #define CMDBUILTIN 2 /* command is a shell builtin */
  6687. /* action to find_command() */
  6688. #define DO_ERR 0x01 /* prints errors */
  6689. #define DO_ABS 0x02 /* checks absolute paths */
  6690. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6691. #define DO_ALTPATH 0x08 /* using alternate path */
  6692. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6693. static void find_command(char *, struct cmdentry *, int, const char *);
  6694. /* ============ Hashing commands */
  6695. /*
  6696. * When commands are first encountered, they are entered in a hash table.
  6697. * This ensures that a full path search will not have to be done for them
  6698. * on each invocation.
  6699. *
  6700. * We should investigate converting to a linear search, even though that
  6701. * would make the command name "hash" a misnomer.
  6702. */
  6703. struct tblentry {
  6704. struct tblentry *next; /* next entry in hash chain */
  6705. union param param; /* definition of builtin function */
  6706. smallint cmdtype; /* CMDxxx */
  6707. char rehash; /* if set, cd done since entry created */
  6708. char cmdname[1]; /* name of command */
  6709. };
  6710. static struct tblentry **cmdtable;
  6711. #define INIT_G_cmdtable() do { \
  6712. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6713. } while (0)
  6714. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6715. static void
  6716. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6717. {
  6718. #if ENABLE_FEATURE_SH_STANDALONE
  6719. if (applet_no >= 0) {
  6720. if (APPLET_IS_NOEXEC(applet_no)) {
  6721. clearenv();
  6722. while (*envp)
  6723. putenv(*envp++);
  6724. run_applet_no_and_exit(applet_no, argv);
  6725. }
  6726. /* re-exec ourselves with the new arguments */
  6727. execve(bb_busybox_exec_path, argv, envp);
  6728. /* If they called chroot or otherwise made the binary no longer
  6729. * executable, fall through */
  6730. }
  6731. #endif
  6732. repeat:
  6733. #ifdef SYSV
  6734. do {
  6735. execve(cmd, argv, envp);
  6736. } while (errno == EINTR);
  6737. #else
  6738. execve(cmd, argv, envp);
  6739. #endif
  6740. if (cmd == (char*) bb_busybox_exec_path) {
  6741. /* We already visited ENOEXEC branch below, don't do it again */
  6742. //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
  6743. free(argv);
  6744. return;
  6745. }
  6746. if (errno == ENOEXEC) {
  6747. /* Run "cmd" as a shell script:
  6748. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  6749. * "If the execve() function fails with ENOEXEC, the shell
  6750. * shall execute a command equivalent to having a shell invoked
  6751. * with the command name as its first operand,
  6752. * with any remaining arguments passed to the new shell"
  6753. *
  6754. * That is, do not use $SHELL, user's shell, or /bin/sh;
  6755. * just call ourselves.
  6756. *
  6757. * Note that bash reads ~80 chars of the file, and if it sees
  6758. * a zero byte before it sees newline, it doesn't try to
  6759. * interpret it, but fails with "cannot execute binary file"
  6760. * message and exit code 126. For one, this prevents attempts
  6761. * to interpret foreign ELF binaries as shell scripts.
  6762. */
  6763. char **ap;
  6764. char **new;
  6765. for (ap = argv; *ap; ap++)
  6766. continue;
  6767. new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
  6768. new[0] = (char*) "ash";
  6769. new[1] = cmd;
  6770. ap = new + 2;
  6771. while ((*ap++ = *++argv) != NULL)
  6772. continue;
  6773. cmd = (char*) bb_busybox_exec_path;
  6774. argv = new;
  6775. goto repeat;
  6776. }
  6777. }
  6778. /*
  6779. * Exec a program. Never returns. If you change this routine, you may
  6780. * have to change the find_command routine as well.
  6781. */
  6782. static void shellexec(char **, const char *, int) NORETURN;
  6783. static void
  6784. shellexec(char **argv, const char *path, int idx)
  6785. {
  6786. char *cmdname;
  6787. int e;
  6788. char **envp;
  6789. int exerrno;
  6790. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  6791. clearredir(/*drop:*/ 1);
  6792. envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
  6793. if (strchr(argv[0], '/') != NULL
  6794. #if ENABLE_FEATURE_SH_STANDALONE
  6795. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6796. #endif
  6797. ) {
  6798. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6799. if (applet_no >= 0) {
  6800. /* We tried execing ourself, but it didn't work.
  6801. * Maybe /proc/self/exe doesn't exist?
  6802. * Try $PATH search.
  6803. */
  6804. goto try_PATH;
  6805. }
  6806. e = errno;
  6807. } else {
  6808. try_PATH:
  6809. e = ENOENT;
  6810. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6811. if (--idx < 0 && pathopt == NULL) {
  6812. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6813. if (errno != ENOENT && errno != ENOTDIR)
  6814. e = errno;
  6815. }
  6816. stunalloc(cmdname);
  6817. }
  6818. }
  6819. /* Map to POSIX errors */
  6820. switch (e) {
  6821. case EACCES:
  6822. exerrno = 126;
  6823. break;
  6824. case ENOENT:
  6825. exerrno = 127;
  6826. break;
  6827. default:
  6828. exerrno = 2;
  6829. break;
  6830. }
  6831. exitstatus = exerrno;
  6832. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6833. argv[0], e, suppress_int));
  6834. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6835. /* NOTREACHED */
  6836. }
  6837. static void
  6838. printentry(struct tblentry *cmdp)
  6839. {
  6840. int idx;
  6841. const char *path;
  6842. char *name;
  6843. idx = cmdp->param.index;
  6844. path = pathval();
  6845. do {
  6846. name = path_advance(&path, cmdp->cmdname);
  6847. stunalloc(name);
  6848. } while (--idx >= 0);
  6849. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6850. }
  6851. /*
  6852. * Clear out command entries. The argument specifies the first entry in
  6853. * PATH which has changed.
  6854. */
  6855. static void
  6856. clearcmdentry(int firstchange)
  6857. {
  6858. struct tblentry **tblp;
  6859. struct tblentry **pp;
  6860. struct tblentry *cmdp;
  6861. INT_OFF;
  6862. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6863. pp = tblp;
  6864. while ((cmdp = *pp) != NULL) {
  6865. if ((cmdp->cmdtype == CMDNORMAL &&
  6866. cmdp->param.index >= firstchange)
  6867. || (cmdp->cmdtype == CMDBUILTIN &&
  6868. builtinloc >= firstchange)
  6869. ) {
  6870. *pp = cmdp->next;
  6871. free(cmdp);
  6872. } else {
  6873. pp = &cmdp->next;
  6874. }
  6875. }
  6876. }
  6877. INT_ON;
  6878. }
  6879. /*
  6880. * Locate a command in the command hash table. If "add" is nonzero,
  6881. * add the command to the table if it is not already present. The
  6882. * variable "lastcmdentry" is set to point to the address of the link
  6883. * pointing to the entry, so that delete_cmd_entry can delete the
  6884. * entry.
  6885. *
  6886. * Interrupts must be off if called with add != 0.
  6887. */
  6888. static struct tblentry **lastcmdentry;
  6889. static struct tblentry *
  6890. cmdlookup(const char *name, int add)
  6891. {
  6892. unsigned int hashval;
  6893. const char *p;
  6894. struct tblentry *cmdp;
  6895. struct tblentry **pp;
  6896. p = name;
  6897. hashval = (unsigned char)*p << 4;
  6898. while (*p)
  6899. hashval += (unsigned char)*p++;
  6900. hashval &= 0x7FFF;
  6901. pp = &cmdtable[hashval % CMDTABLESIZE];
  6902. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6903. if (strcmp(cmdp->cmdname, name) == 0)
  6904. break;
  6905. pp = &cmdp->next;
  6906. }
  6907. if (add && cmdp == NULL) {
  6908. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6909. + strlen(name)
  6910. /* + 1 - already done because
  6911. * tblentry::cmdname is char[1] */);
  6912. /*cmdp->next = NULL; - ckzalloc did it */
  6913. cmdp->cmdtype = CMDUNKNOWN;
  6914. strcpy(cmdp->cmdname, name);
  6915. }
  6916. lastcmdentry = pp;
  6917. return cmdp;
  6918. }
  6919. /*
  6920. * Delete the command entry returned on the last lookup.
  6921. */
  6922. static void
  6923. delete_cmd_entry(void)
  6924. {
  6925. struct tblentry *cmdp;
  6926. INT_OFF;
  6927. cmdp = *lastcmdentry;
  6928. *lastcmdentry = cmdp->next;
  6929. if (cmdp->cmdtype == CMDFUNCTION)
  6930. freefunc(cmdp->param.func);
  6931. free(cmdp);
  6932. INT_ON;
  6933. }
  6934. /*
  6935. * Add a new command entry, replacing any existing command entry for
  6936. * the same name - except special builtins.
  6937. */
  6938. static void
  6939. addcmdentry(char *name, struct cmdentry *entry)
  6940. {
  6941. struct tblentry *cmdp;
  6942. cmdp = cmdlookup(name, 1);
  6943. if (cmdp->cmdtype == CMDFUNCTION) {
  6944. freefunc(cmdp->param.func);
  6945. }
  6946. cmdp->cmdtype = entry->cmdtype;
  6947. cmdp->param = entry->u;
  6948. cmdp->rehash = 0;
  6949. }
  6950. static int FAST_FUNC
  6951. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6952. {
  6953. struct tblentry **pp;
  6954. struct tblentry *cmdp;
  6955. int c;
  6956. struct cmdentry entry;
  6957. char *name;
  6958. if (nextopt("r") != '\0') {
  6959. clearcmdentry(0);
  6960. return 0;
  6961. }
  6962. if (*argptr == NULL) {
  6963. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6964. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6965. if (cmdp->cmdtype == CMDNORMAL)
  6966. printentry(cmdp);
  6967. }
  6968. }
  6969. return 0;
  6970. }
  6971. c = 0;
  6972. while ((name = *argptr) != NULL) {
  6973. cmdp = cmdlookup(name, 0);
  6974. if (cmdp != NULL
  6975. && (cmdp->cmdtype == CMDNORMAL
  6976. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6977. ) {
  6978. delete_cmd_entry();
  6979. }
  6980. find_command(name, &entry, DO_ERR, pathval());
  6981. if (entry.cmdtype == CMDUNKNOWN)
  6982. c = 1;
  6983. argptr++;
  6984. }
  6985. return c;
  6986. }
  6987. /*
  6988. * Called when a cd is done. Marks all commands so the next time they
  6989. * are executed they will be rehashed.
  6990. */
  6991. static void
  6992. hashcd(void)
  6993. {
  6994. struct tblentry **pp;
  6995. struct tblentry *cmdp;
  6996. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6997. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6998. if (cmdp->cmdtype == CMDNORMAL
  6999. || (cmdp->cmdtype == CMDBUILTIN
  7000. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7001. && builtinloc > 0)
  7002. ) {
  7003. cmdp->rehash = 1;
  7004. }
  7005. }
  7006. }
  7007. }
  7008. /*
  7009. * Fix command hash table when PATH changed.
  7010. * Called before PATH is changed. The argument is the new value of PATH;
  7011. * pathval() still returns the old value at this point.
  7012. * Called with interrupts off.
  7013. */
  7014. static void FAST_FUNC
  7015. changepath(const char *new)
  7016. {
  7017. const char *old;
  7018. int firstchange;
  7019. int idx;
  7020. int idx_bltin;
  7021. old = pathval();
  7022. firstchange = 9999; /* assume no change */
  7023. idx = 0;
  7024. idx_bltin = -1;
  7025. for (;;) {
  7026. if (*old != *new) {
  7027. firstchange = idx;
  7028. if ((*old == '\0' && *new == ':')
  7029. || (*old == ':' && *new == '\0')
  7030. ) {
  7031. firstchange++;
  7032. }
  7033. old = new; /* ignore subsequent differences */
  7034. }
  7035. if (*new == '\0')
  7036. break;
  7037. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7038. idx_bltin = idx;
  7039. if (*new == ':')
  7040. idx++;
  7041. new++;
  7042. old++;
  7043. }
  7044. if (builtinloc < 0 && idx_bltin >= 0)
  7045. builtinloc = idx_bltin; /* zap builtins */
  7046. if (builtinloc >= 0 && idx_bltin < 0)
  7047. firstchange = 0;
  7048. clearcmdentry(firstchange);
  7049. builtinloc = idx_bltin;
  7050. }
  7051. enum {
  7052. TEOF,
  7053. TNL,
  7054. TREDIR,
  7055. TWORD,
  7056. TSEMI,
  7057. TBACKGND,
  7058. TAND,
  7059. TOR,
  7060. TPIPE,
  7061. TLP,
  7062. TRP,
  7063. TENDCASE,
  7064. TENDBQUOTE,
  7065. TNOT,
  7066. TCASE,
  7067. TDO,
  7068. TDONE,
  7069. TELIF,
  7070. TELSE,
  7071. TESAC,
  7072. TFI,
  7073. TFOR,
  7074. #if ENABLE_ASH_BASH_COMPAT
  7075. TFUNCTION,
  7076. #endif
  7077. TIF,
  7078. TIN,
  7079. TTHEN,
  7080. TUNTIL,
  7081. TWHILE,
  7082. TBEGIN,
  7083. TEND
  7084. };
  7085. typedef smallint token_id_t;
  7086. /* first char is indicating which tokens mark the end of a list */
  7087. static const char *const tokname_array[] = {
  7088. "\1end of file",
  7089. "\0newline",
  7090. "\0redirection",
  7091. "\0word",
  7092. "\0;",
  7093. "\0&",
  7094. "\0&&",
  7095. "\0||",
  7096. "\0|",
  7097. "\0(",
  7098. "\1)",
  7099. "\1;;",
  7100. "\1`",
  7101. #define KWDOFFSET 13
  7102. /* the following are keywords */
  7103. "\0!",
  7104. "\0case",
  7105. "\1do",
  7106. "\1done",
  7107. "\1elif",
  7108. "\1else",
  7109. "\1esac",
  7110. "\1fi",
  7111. "\0for",
  7112. #if ENABLE_ASH_BASH_COMPAT
  7113. "\0function",
  7114. #endif
  7115. "\0if",
  7116. "\0in",
  7117. "\1then",
  7118. "\0until",
  7119. "\0while",
  7120. "\0{",
  7121. "\1}",
  7122. };
  7123. /* Wrapper around strcmp for qsort/bsearch/... */
  7124. static int
  7125. pstrcmp(const void *a, const void *b)
  7126. {
  7127. return strcmp((char*) a, (*(char**) b) + 1);
  7128. }
  7129. static const char *const *
  7130. findkwd(const char *s)
  7131. {
  7132. return bsearch(s, tokname_array + KWDOFFSET,
  7133. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7134. sizeof(tokname_array[0]), pstrcmp);
  7135. }
  7136. /*
  7137. * Locate and print what a word is...
  7138. */
  7139. static int
  7140. describe_command(char *command, const char *path, int describe_command_verbose)
  7141. {
  7142. struct cmdentry entry;
  7143. struct tblentry *cmdp;
  7144. #if ENABLE_ASH_ALIAS
  7145. const struct alias *ap;
  7146. #endif
  7147. path = path ? path : pathval();
  7148. if (describe_command_verbose) {
  7149. out1str(command);
  7150. }
  7151. /* First look at the keywords */
  7152. if (findkwd(command)) {
  7153. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7154. goto out;
  7155. }
  7156. #if ENABLE_ASH_ALIAS
  7157. /* Then look at the aliases */
  7158. ap = lookupalias(command, 0);
  7159. if (ap != NULL) {
  7160. if (!describe_command_verbose) {
  7161. out1str("alias ");
  7162. printalias(ap);
  7163. return 0;
  7164. }
  7165. out1fmt(" is an alias for %s", ap->val);
  7166. goto out;
  7167. }
  7168. #endif
  7169. /* Then check if it is a tracked alias */
  7170. cmdp = cmdlookup(command, 0);
  7171. if (cmdp != NULL) {
  7172. entry.cmdtype = cmdp->cmdtype;
  7173. entry.u = cmdp->param;
  7174. } else {
  7175. /* Finally use brute force */
  7176. find_command(command, &entry, DO_ABS, path);
  7177. }
  7178. switch (entry.cmdtype) {
  7179. case CMDNORMAL: {
  7180. int j = entry.u.index;
  7181. char *p;
  7182. if (j < 0) {
  7183. p = command;
  7184. } else {
  7185. do {
  7186. p = path_advance(&path, command);
  7187. stunalloc(p);
  7188. } while (--j >= 0);
  7189. }
  7190. if (describe_command_verbose) {
  7191. out1fmt(" is%s %s",
  7192. (cmdp ? " a tracked alias for" : nullstr), p
  7193. );
  7194. } else {
  7195. out1str(p);
  7196. }
  7197. break;
  7198. }
  7199. case CMDFUNCTION:
  7200. if (describe_command_verbose) {
  7201. out1str(" is a shell function");
  7202. } else {
  7203. out1str(command);
  7204. }
  7205. break;
  7206. case CMDBUILTIN:
  7207. if (describe_command_verbose) {
  7208. out1fmt(" is a %sshell builtin",
  7209. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7210. "special " : nullstr
  7211. );
  7212. } else {
  7213. out1str(command);
  7214. }
  7215. break;
  7216. default:
  7217. if (describe_command_verbose) {
  7218. out1str(": not found\n");
  7219. }
  7220. return 127;
  7221. }
  7222. out:
  7223. out1str("\n");
  7224. return 0;
  7225. }
  7226. static int FAST_FUNC
  7227. typecmd(int argc UNUSED_PARAM, char **argv)
  7228. {
  7229. int i = 1;
  7230. int err = 0;
  7231. int verbose = 1;
  7232. /* type -p ... ? (we don't bother checking for 'p') */
  7233. if (argv[1] && argv[1][0] == '-') {
  7234. i++;
  7235. verbose = 0;
  7236. }
  7237. while (argv[i]) {
  7238. err |= describe_command(argv[i++], NULL, verbose);
  7239. }
  7240. return err;
  7241. }
  7242. #if ENABLE_ASH_CMDCMD
  7243. static int FAST_FUNC
  7244. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7245. {
  7246. int c;
  7247. enum {
  7248. VERIFY_BRIEF = 1,
  7249. VERIFY_VERBOSE = 2,
  7250. } verify = 0;
  7251. const char *path = NULL;
  7252. while ((c = nextopt("pvV")) != '\0')
  7253. if (c == 'V')
  7254. verify |= VERIFY_VERBOSE;
  7255. else if (c == 'v')
  7256. verify |= VERIFY_BRIEF;
  7257. #if DEBUG
  7258. else if (c != 'p')
  7259. abort();
  7260. #endif
  7261. else
  7262. path = bb_default_path;
  7263. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7264. if (verify && (*argptr != NULL)) {
  7265. return describe_command(*argptr, path, verify - VERIFY_BRIEF);
  7266. }
  7267. return 0;
  7268. }
  7269. #endif
  7270. /* ============ eval.c */
  7271. static int funcblocksize; /* size of structures in function */
  7272. static int funcstringsize; /* size of strings in node */
  7273. static void *funcblock; /* block to allocate function from */
  7274. static char *funcstring; /* block to allocate strings from */
  7275. /* flags in argument to evaltree */
  7276. #define EV_EXIT 01 /* exit after evaluating tree */
  7277. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7278. #define EV_BACKCMD 04 /* command executing within back quotes */
  7279. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7280. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7281. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7282. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7283. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7284. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7285. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7286. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7287. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7288. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7289. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7290. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7291. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7292. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7293. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7294. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7295. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7296. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7297. #if ENABLE_ASH_BASH_COMPAT
  7298. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7299. #endif
  7300. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7301. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7302. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7303. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7304. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7305. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7306. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7307. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7308. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7309. };
  7310. static void calcsize(union node *n);
  7311. static void
  7312. sizenodelist(struct nodelist *lp)
  7313. {
  7314. while (lp) {
  7315. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7316. calcsize(lp->n);
  7317. lp = lp->next;
  7318. }
  7319. }
  7320. static void
  7321. calcsize(union node *n)
  7322. {
  7323. if (n == NULL)
  7324. return;
  7325. funcblocksize += nodesize[n->type];
  7326. switch (n->type) {
  7327. case NCMD:
  7328. calcsize(n->ncmd.redirect);
  7329. calcsize(n->ncmd.args);
  7330. calcsize(n->ncmd.assign);
  7331. break;
  7332. case NPIPE:
  7333. sizenodelist(n->npipe.cmdlist);
  7334. break;
  7335. case NREDIR:
  7336. case NBACKGND:
  7337. case NSUBSHELL:
  7338. calcsize(n->nredir.redirect);
  7339. calcsize(n->nredir.n);
  7340. break;
  7341. case NAND:
  7342. case NOR:
  7343. case NSEMI:
  7344. case NWHILE:
  7345. case NUNTIL:
  7346. calcsize(n->nbinary.ch2);
  7347. calcsize(n->nbinary.ch1);
  7348. break;
  7349. case NIF:
  7350. calcsize(n->nif.elsepart);
  7351. calcsize(n->nif.ifpart);
  7352. calcsize(n->nif.test);
  7353. break;
  7354. case NFOR:
  7355. funcstringsize += strlen(n->nfor.var) + 1;
  7356. calcsize(n->nfor.body);
  7357. calcsize(n->nfor.args);
  7358. break;
  7359. case NCASE:
  7360. calcsize(n->ncase.cases);
  7361. calcsize(n->ncase.expr);
  7362. break;
  7363. case NCLIST:
  7364. calcsize(n->nclist.body);
  7365. calcsize(n->nclist.pattern);
  7366. calcsize(n->nclist.next);
  7367. break;
  7368. case NDEFUN:
  7369. case NARG:
  7370. sizenodelist(n->narg.backquote);
  7371. funcstringsize += strlen(n->narg.text) + 1;
  7372. calcsize(n->narg.next);
  7373. break;
  7374. case NTO:
  7375. #if ENABLE_ASH_BASH_COMPAT
  7376. case NTO2:
  7377. #endif
  7378. case NCLOBBER:
  7379. case NFROM:
  7380. case NFROMTO:
  7381. case NAPPEND:
  7382. calcsize(n->nfile.fname);
  7383. calcsize(n->nfile.next);
  7384. break;
  7385. case NTOFD:
  7386. case NFROMFD:
  7387. calcsize(n->ndup.vname);
  7388. calcsize(n->ndup.next);
  7389. break;
  7390. case NHERE:
  7391. case NXHERE:
  7392. calcsize(n->nhere.doc);
  7393. calcsize(n->nhere.next);
  7394. break;
  7395. case NNOT:
  7396. calcsize(n->nnot.com);
  7397. break;
  7398. };
  7399. }
  7400. static char *
  7401. nodeckstrdup(char *s)
  7402. {
  7403. char *rtn = funcstring;
  7404. strcpy(funcstring, s);
  7405. funcstring += strlen(s) + 1;
  7406. return rtn;
  7407. }
  7408. static union node *copynode(union node *);
  7409. static struct nodelist *
  7410. copynodelist(struct nodelist *lp)
  7411. {
  7412. struct nodelist *start;
  7413. struct nodelist **lpp;
  7414. lpp = &start;
  7415. while (lp) {
  7416. *lpp = funcblock;
  7417. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7418. (*lpp)->n = copynode(lp->n);
  7419. lp = lp->next;
  7420. lpp = &(*lpp)->next;
  7421. }
  7422. *lpp = NULL;
  7423. return start;
  7424. }
  7425. static union node *
  7426. copynode(union node *n)
  7427. {
  7428. union node *new;
  7429. if (n == NULL)
  7430. return NULL;
  7431. new = funcblock;
  7432. funcblock = (char *) funcblock + nodesize[n->type];
  7433. switch (n->type) {
  7434. case NCMD:
  7435. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7436. new->ncmd.args = copynode(n->ncmd.args);
  7437. new->ncmd.assign = copynode(n->ncmd.assign);
  7438. break;
  7439. case NPIPE:
  7440. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7441. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7442. break;
  7443. case NREDIR:
  7444. case NBACKGND:
  7445. case NSUBSHELL:
  7446. new->nredir.redirect = copynode(n->nredir.redirect);
  7447. new->nredir.n = copynode(n->nredir.n);
  7448. break;
  7449. case NAND:
  7450. case NOR:
  7451. case NSEMI:
  7452. case NWHILE:
  7453. case NUNTIL:
  7454. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7455. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7456. break;
  7457. case NIF:
  7458. new->nif.elsepart = copynode(n->nif.elsepart);
  7459. new->nif.ifpart = copynode(n->nif.ifpart);
  7460. new->nif.test = copynode(n->nif.test);
  7461. break;
  7462. case NFOR:
  7463. new->nfor.var = nodeckstrdup(n->nfor.var);
  7464. new->nfor.body = copynode(n->nfor.body);
  7465. new->nfor.args = copynode(n->nfor.args);
  7466. break;
  7467. case NCASE:
  7468. new->ncase.cases = copynode(n->ncase.cases);
  7469. new->ncase.expr = copynode(n->ncase.expr);
  7470. break;
  7471. case NCLIST:
  7472. new->nclist.body = copynode(n->nclist.body);
  7473. new->nclist.pattern = copynode(n->nclist.pattern);
  7474. new->nclist.next = copynode(n->nclist.next);
  7475. break;
  7476. case NDEFUN:
  7477. case NARG:
  7478. new->narg.backquote = copynodelist(n->narg.backquote);
  7479. new->narg.text = nodeckstrdup(n->narg.text);
  7480. new->narg.next = copynode(n->narg.next);
  7481. break;
  7482. case NTO:
  7483. #if ENABLE_ASH_BASH_COMPAT
  7484. case NTO2:
  7485. #endif
  7486. case NCLOBBER:
  7487. case NFROM:
  7488. case NFROMTO:
  7489. case NAPPEND:
  7490. new->nfile.fname = copynode(n->nfile.fname);
  7491. new->nfile.fd = n->nfile.fd;
  7492. new->nfile.next = copynode(n->nfile.next);
  7493. break;
  7494. case NTOFD:
  7495. case NFROMFD:
  7496. new->ndup.vname = copynode(n->ndup.vname);
  7497. new->ndup.dupfd = n->ndup.dupfd;
  7498. new->ndup.fd = n->ndup.fd;
  7499. new->ndup.next = copynode(n->ndup.next);
  7500. break;
  7501. case NHERE:
  7502. case NXHERE:
  7503. new->nhere.doc = copynode(n->nhere.doc);
  7504. new->nhere.fd = n->nhere.fd;
  7505. new->nhere.next = copynode(n->nhere.next);
  7506. break;
  7507. case NNOT:
  7508. new->nnot.com = copynode(n->nnot.com);
  7509. break;
  7510. };
  7511. new->type = n->type;
  7512. return new;
  7513. }
  7514. /*
  7515. * Make a copy of a parse tree.
  7516. */
  7517. static struct funcnode *
  7518. copyfunc(union node *n)
  7519. {
  7520. struct funcnode *f;
  7521. size_t blocksize;
  7522. funcblocksize = offsetof(struct funcnode, n);
  7523. funcstringsize = 0;
  7524. calcsize(n);
  7525. blocksize = funcblocksize;
  7526. f = ckmalloc(blocksize + funcstringsize);
  7527. funcblock = (char *) f + offsetof(struct funcnode, n);
  7528. funcstring = (char *) f + blocksize;
  7529. copynode(n);
  7530. f->count = 0;
  7531. return f;
  7532. }
  7533. /*
  7534. * Define a shell function.
  7535. */
  7536. static void
  7537. defun(char *name, union node *func)
  7538. {
  7539. struct cmdentry entry;
  7540. INT_OFF;
  7541. entry.cmdtype = CMDFUNCTION;
  7542. entry.u.func = copyfunc(func);
  7543. addcmdentry(name, &entry);
  7544. INT_ON;
  7545. }
  7546. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7547. #define SKIPBREAK (1 << 0)
  7548. #define SKIPCONT (1 << 1)
  7549. #define SKIPFUNC (1 << 2)
  7550. #define SKIPFILE (1 << 3)
  7551. #define SKIPEVAL (1 << 4)
  7552. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7553. static int skipcount; /* number of levels to skip */
  7554. static int funcnest; /* depth of function calls */
  7555. static int loopnest; /* current loop nesting level */
  7556. /* Forward decl way out to parsing code - dotrap needs it */
  7557. static int evalstring(char *s, int mask);
  7558. /* Called to execute a trap.
  7559. * Single callsite - at the end of evaltree().
  7560. * If we return non-zero, evaltree raises EXEXIT exception.
  7561. *
  7562. * Perhaps we should avoid entering new trap handlers
  7563. * while we are executing a trap handler. [is it a TODO?]
  7564. */
  7565. static int
  7566. dotrap(void)
  7567. {
  7568. uint8_t *g;
  7569. int sig;
  7570. uint8_t savestatus;
  7571. savestatus = exitstatus;
  7572. pending_sig = 0;
  7573. xbarrier();
  7574. TRACE(("dotrap entered\n"));
  7575. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7576. int want_exexit;
  7577. char *t;
  7578. if (*g == 0)
  7579. continue;
  7580. t = trap[sig];
  7581. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7582. * don't upset it by resetting gotsig[SIGINT-1] */
  7583. if (sig == SIGINT && !t)
  7584. continue;
  7585. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7586. *g = 0;
  7587. if (!t)
  7588. continue;
  7589. want_exexit = evalstring(t, SKIPEVAL);
  7590. exitstatus = savestatus;
  7591. if (want_exexit) {
  7592. TRACE(("dotrap returns %d\n", want_exexit));
  7593. return want_exexit;
  7594. }
  7595. }
  7596. TRACE(("dotrap returns 0\n"));
  7597. return 0;
  7598. }
  7599. /* forward declarations - evaluation is fairly recursive business... */
  7600. static void evalloop(union node *, int);
  7601. static void evalfor(union node *, int);
  7602. static void evalcase(union node *, int);
  7603. static void evalsubshell(union node *, int);
  7604. static void expredir(union node *);
  7605. static void evalpipe(union node *, int);
  7606. static void evalcommand(union node *, int);
  7607. static int evalbltin(const struct builtincmd *, int, char **);
  7608. static void prehash(union node *);
  7609. /*
  7610. * Evaluate a parse tree. The value is left in the global variable
  7611. * exitstatus.
  7612. */
  7613. static void
  7614. evaltree(union node *n, int flags)
  7615. {
  7616. struct jmploc *volatile savehandler = exception_handler;
  7617. struct jmploc jmploc;
  7618. int checkexit = 0;
  7619. void (*evalfn)(union node *, int);
  7620. int status;
  7621. int int_level;
  7622. SAVE_INT(int_level);
  7623. if (n == NULL) {
  7624. TRACE(("evaltree(NULL) called\n"));
  7625. goto out1;
  7626. }
  7627. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7628. exception_handler = &jmploc;
  7629. {
  7630. int err = setjmp(jmploc.loc);
  7631. if (err) {
  7632. /* if it was a signal, check for trap handlers */
  7633. if (exception_type == EXSIG) {
  7634. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7635. exception_type, err));
  7636. goto out;
  7637. }
  7638. /* continue on the way out */
  7639. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7640. exception_type, err));
  7641. exception_handler = savehandler;
  7642. longjmp(exception_handler->loc, err);
  7643. }
  7644. }
  7645. switch (n->type) {
  7646. default:
  7647. #if DEBUG
  7648. out1fmt("Node type = %d\n", n->type);
  7649. fflush_all();
  7650. break;
  7651. #endif
  7652. case NNOT:
  7653. evaltree(n->nnot.com, EV_TESTED);
  7654. status = !exitstatus;
  7655. goto setstatus;
  7656. case NREDIR:
  7657. expredir(n->nredir.redirect);
  7658. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7659. if (!status) {
  7660. evaltree(n->nredir.n, flags & EV_TESTED);
  7661. status = exitstatus;
  7662. }
  7663. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7664. goto setstatus;
  7665. case NCMD:
  7666. evalfn = evalcommand;
  7667. checkexit:
  7668. if (eflag && !(flags & EV_TESTED))
  7669. checkexit = ~0;
  7670. goto calleval;
  7671. case NFOR:
  7672. evalfn = evalfor;
  7673. goto calleval;
  7674. case NWHILE:
  7675. case NUNTIL:
  7676. evalfn = evalloop;
  7677. goto calleval;
  7678. case NSUBSHELL:
  7679. case NBACKGND:
  7680. evalfn = evalsubshell;
  7681. goto calleval;
  7682. case NPIPE:
  7683. evalfn = evalpipe;
  7684. goto checkexit;
  7685. case NCASE:
  7686. evalfn = evalcase;
  7687. goto calleval;
  7688. case NAND:
  7689. case NOR:
  7690. case NSEMI: {
  7691. #if NAND + 1 != NOR
  7692. #error NAND + 1 != NOR
  7693. #endif
  7694. #if NOR + 1 != NSEMI
  7695. #error NOR + 1 != NSEMI
  7696. #endif
  7697. unsigned is_or = n->type - NAND;
  7698. evaltree(
  7699. n->nbinary.ch1,
  7700. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7701. );
  7702. if ((!exitstatus) == is_or)
  7703. break;
  7704. if (!evalskip) {
  7705. n = n->nbinary.ch2;
  7706. evaln:
  7707. evalfn = evaltree;
  7708. calleval:
  7709. evalfn(n, flags);
  7710. break;
  7711. }
  7712. break;
  7713. }
  7714. case NIF:
  7715. evaltree(n->nif.test, EV_TESTED);
  7716. if (evalskip)
  7717. break;
  7718. if (exitstatus == 0) {
  7719. n = n->nif.ifpart;
  7720. goto evaln;
  7721. }
  7722. if (n->nif.elsepart) {
  7723. n = n->nif.elsepart;
  7724. goto evaln;
  7725. }
  7726. goto success;
  7727. case NDEFUN:
  7728. defun(n->narg.text, n->narg.next);
  7729. success:
  7730. status = 0;
  7731. setstatus:
  7732. exitstatus = status;
  7733. break;
  7734. }
  7735. out:
  7736. exception_handler = savehandler;
  7737. out1:
  7738. /* Order of checks below is important:
  7739. * signal handlers trigger before exit caused by "set -e".
  7740. */
  7741. if (pending_sig && dotrap())
  7742. goto exexit;
  7743. if (checkexit & exitstatus)
  7744. evalskip |= SKIPEVAL;
  7745. if (flags & EV_EXIT) {
  7746. exexit:
  7747. raise_exception(EXEXIT);
  7748. }
  7749. RESTORE_INT(int_level);
  7750. TRACE(("leaving evaltree (no interrupts)\n"));
  7751. }
  7752. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7753. static
  7754. #endif
  7755. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7756. static void
  7757. evalloop(union node *n, int flags)
  7758. {
  7759. int status;
  7760. loopnest++;
  7761. status = 0;
  7762. flags &= EV_TESTED;
  7763. for (;;) {
  7764. int i;
  7765. evaltree(n->nbinary.ch1, EV_TESTED);
  7766. if (evalskip) {
  7767. skipping:
  7768. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7769. evalskip = 0;
  7770. continue;
  7771. }
  7772. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7773. evalskip = 0;
  7774. break;
  7775. }
  7776. i = exitstatus;
  7777. if (n->type != NWHILE)
  7778. i = !i;
  7779. if (i != 0)
  7780. break;
  7781. evaltree(n->nbinary.ch2, flags);
  7782. status = exitstatus;
  7783. if (evalskip)
  7784. goto skipping;
  7785. }
  7786. loopnest--;
  7787. exitstatus = status;
  7788. }
  7789. static void
  7790. evalfor(union node *n, int flags)
  7791. {
  7792. struct arglist arglist;
  7793. union node *argp;
  7794. struct strlist *sp;
  7795. struct stackmark smark;
  7796. setstackmark(&smark);
  7797. arglist.list = NULL;
  7798. arglist.lastp = &arglist.list;
  7799. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7800. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  7801. /* XXX */
  7802. if (evalskip)
  7803. goto out;
  7804. }
  7805. *arglist.lastp = NULL;
  7806. exitstatus = 0;
  7807. loopnest++;
  7808. flags &= EV_TESTED;
  7809. for (sp = arglist.list; sp; sp = sp->next) {
  7810. setvar0(n->nfor.var, sp->text);
  7811. evaltree(n->nfor.body, flags);
  7812. if (evalskip) {
  7813. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7814. evalskip = 0;
  7815. continue;
  7816. }
  7817. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7818. evalskip = 0;
  7819. break;
  7820. }
  7821. }
  7822. loopnest--;
  7823. out:
  7824. popstackmark(&smark);
  7825. }
  7826. static void
  7827. evalcase(union node *n, int flags)
  7828. {
  7829. union node *cp;
  7830. union node *patp;
  7831. struct arglist arglist;
  7832. struct stackmark smark;
  7833. setstackmark(&smark);
  7834. arglist.list = NULL;
  7835. arglist.lastp = &arglist.list;
  7836. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7837. exitstatus = 0;
  7838. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7839. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7840. if (casematch(patp, arglist.list->text)) {
  7841. if (evalskip == 0) {
  7842. evaltree(cp->nclist.body, flags);
  7843. }
  7844. goto out;
  7845. }
  7846. }
  7847. }
  7848. out:
  7849. popstackmark(&smark);
  7850. }
  7851. /*
  7852. * Kick off a subshell to evaluate a tree.
  7853. */
  7854. static void
  7855. evalsubshell(union node *n, int flags)
  7856. {
  7857. struct job *jp;
  7858. int backgnd = (n->type == NBACKGND);
  7859. int status;
  7860. expredir(n->nredir.redirect);
  7861. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  7862. goto nofork;
  7863. INT_OFF;
  7864. jp = makejob(/*n,*/ 1);
  7865. if (forkshell(jp, n, backgnd) == 0) {
  7866. /* child */
  7867. INT_ON;
  7868. flags |= EV_EXIT;
  7869. if (backgnd)
  7870. flags &= ~EV_TESTED;
  7871. nofork:
  7872. redirect(n->nredir.redirect, 0);
  7873. evaltreenr(n->nredir.n, flags);
  7874. /* never returns */
  7875. }
  7876. status = 0;
  7877. if (!backgnd)
  7878. status = waitforjob(jp);
  7879. exitstatus = status;
  7880. INT_ON;
  7881. }
  7882. /*
  7883. * Compute the names of the files in a redirection list.
  7884. */
  7885. static void fixredir(union node *, const char *, int);
  7886. static void
  7887. expredir(union node *n)
  7888. {
  7889. union node *redir;
  7890. for (redir = n; redir; redir = redir->nfile.next) {
  7891. struct arglist fn;
  7892. fn.list = NULL;
  7893. fn.lastp = &fn.list;
  7894. switch (redir->type) {
  7895. case NFROMTO:
  7896. case NFROM:
  7897. case NTO:
  7898. #if ENABLE_ASH_BASH_COMPAT
  7899. case NTO2:
  7900. #endif
  7901. case NCLOBBER:
  7902. case NAPPEND:
  7903. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7904. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  7905. #if ENABLE_ASH_BASH_COMPAT
  7906. store_expfname:
  7907. #endif
  7908. #if 0
  7909. // By the design of stack allocator, the loop of this kind:
  7910. // while true; do while true; do break; done </dev/null; done
  7911. // will look like a memory leak: ash plans to free expfname's
  7912. // of "/dev/null" as soon as it finishes running the loop
  7913. // (in this case, never).
  7914. // This "fix" is wrong:
  7915. if (redir->nfile.expfname)
  7916. stunalloc(redir->nfile.expfname);
  7917. // It results in corrupted state of stacked allocations.
  7918. #endif
  7919. redir->nfile.expfname = fn.list->text;
  7920. break;
  7921. case NFROMFD:
  7922. case NTOFD: /* >& */
  7923. if (redir->ndup.vname) {
  7924. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7925. if (fn.list == NULL)
  7926. ash_msg_and_raise_error("redir error");
  7927. #if ENABLE_ASH_BASH_COMPAT
  7928. //FIXME: we used expandarg with different args!
  7929. if (!isdigit_str9(fn.list->text)) {
  7930. /* >&file, not >&fd */
  7931. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7932. ash_msg_and_raise_error("redir error");
  7933. redir->type = NTO2;
  7934. goto store_expfname;
  7935. }
  7936. #endif
  7937. fixredir(redir, fn.list->text, 1);
  7938. }
  7939. break;
  7940. }
  7941. }
  7942. }
  7943. /*
  7944. * Evaluate a pipeline. All the processes in the pipeline are children
  7945. * of the process creating the pipeline. (This differs from some versions
  7946. * of the shell, which make the last process in a pipeline the parent
  7947. * of all the rest.)
  7948. */
  7949. static void
  7950. evalpipe(union node *n, int flags)
  7951. {
  7952. struct job *jp;
  7953. struct nodelist *lp;
  7954. int pipelen;
  7955. int prevfd;
  7956. int pip[2];
  7957. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7958. pipelen = 0;
  7959. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7960. pipelen++;
  7961. flags |= EV_EXIT;
  7962. INT_OFF;
  7963. jp = makejob(/*n,*/ pipelen);
  7964. prevfd = -1;
  7965. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7966. prehash(lp->n);
  7967. pip[1] = -1;
  7968. if (lp->next) {
  7969. if (pipe(pip) < 0) {
  7970. close(prevfd);
  7971. ash_msg_and_raise_error("pipe call failed");
  7972. }
  7973. }
  7974. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7975. INT_ON;
  7976. if (pip[1] >= 0) {
  7977. close(pip[0]);
  7978. }
  7979. if (prevfd > 0) {
  7980. dup2(prevfd, 0);
  7981. close(prevfd);
  7982. }
  7983. if (pip[1] > 1) {
  7984. dup2(pip[1], 1);
  7985. close(pip[1]);
  7986. }
  7987. evaltreenr(lp->n, flags);
  7988. /* never returns */
  7989. }
  7990. if (prevfd >= 0)
  7991. close(prevfd);
  7992. prevfd = pip[0];
  7993. /* Don't want to trigger debugging */
  7994. if (pip[1] != -1)
  7995. close(pip[1]);
  7996. }
  7997. if (n->npipe.pipe_backgnd == 0) {
  7998. exitstatus = waitforjob(jp);
  7999. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  8000. }
  8001. INT_ON;
  8002. }
  8003. /*
  8004. * Controls whether the shell is interactive or not.
  8005. */
  8006. static void
  8007. setinteractive(int on)
  8008. {
  8009. static smallint is_interactive;
  8010. if (++on == is_interactive)
  8011. return;
  8012. is_interactive = on;
  8013. setsignal(SIGINT);
  8014. setsignal(SIGQUIT);
  8015. setsignal(SIGTERM);
  8016. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8017. if (is_interactive > 1) {
  8018. /* Looks like they want an interactive shell */
  8019. static smallint did_banner;
  8020. if (!did_banner) {
  8021. /* note: ash and hush share this string */
  8022. out1fmt("\n\n%s %s\n"
  8023. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8024. "\n",
  8025. bb_banner,
  8026. "built-in shell (ash)"
  8027. );
  8028. did_banner = 1;
  8029. }
  8030. }
  8031. #endif
  8032. }
  8033. static void
  8034. optschanged(void)
  8035. {
  8036. #if DEBUG
  8037. opentrace();
  8038. #endif
  8039. setinteractive(iflag);
  8040. setjobctl(mflag);
  8041. #if ENABLE_FEATURE_EDITING_VI
  8042. if (viflag)
  8043. line_input_state->flags |= VI_MODE;
  8044. else
  8045. line_input_state->flags &= ~VI_MODE;
  8046. #else
  8047. viflag = 0; /* forcibly keep the option off */
  8048. #endif
  8049. }
  8050. static struct localvar *localvars;
  8051. /*
  8052. * Called after a function returns.
  8053. * Interrupts must be off.
  8054. */
  8055. static void
  8056. poplocalvars(void)
  8057. {
  8058. struct localvar *lvp;
  8059. struct var *vp;
  8060. while ((lvp = localvars) != NULL) {
  8061. localvars = lvp->next;
  8062. vp = lvp->vp;
  8063. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8064. if (vp == NULL) { /* $- saved */
  8065. memcpy(optlist, lvp->text, sizeof(optlist));
  8066. free((char*)lvp->text);
  8067. optschanged();
  8068. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  8069. unsetvar(vp->var_text);
  8070. } else {
  8071. if (vp->var_func)
  8072. vp->var_func(var_end(lvp->text));
  8073. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8074. free((char*)vp->var_text);
  8075. vp->flags = lvp->flags;
  8076. vp->var_text = lvp->text;
  8077. }
  8078. free(lvp);
  8079. }
  8080. }
  8081. static int
  8082. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8083. {
  8084. volatile struct shparam saveparam;
  8085. struct localvar *volatile savelocalvars;
  8086. struct jmploc *volatile savehandler;
  8087. struct jmploc jmploc;
  8088. int e;
  8089. saveparam = shellparam;
  8090. savelocalvars = localvars;
  8091. e = setjmp(jmploc.loc);
  8092. if (e) {
  8093. goto funcdone;
  8094. }
  8095. INT_OFF;
  8096. savehandler = exception_handler;
  8097. exception_handler = &jmploc;
  8098. localvars = NULL;
  8099. shellparam.malloced = 0;
  8100. func->count++;
  8101. funcnest++;
  8102. INT_ON;
  8103. shellparam.nparam = argc - 1;
  8104. shellparam.p = argv + 1;
  8105. #if ENABLE_ASH_GETOPTS
  8106. shellparam.optind = 1;
  8107. shellparam.optoff = -1;
  8108. #endif
  8109. evaltree(&func->n, flags & EV_TESTED);
  8110. funcdone:
  8111. INT_OFF;
  8112. funcnest--;
  8113. freefunc(func);
  8114. poplocalvars();
  8115. localvars = savelocalvars;
  8116. freeparam(&shellparam);
  8117. shellparam = saveparam;
  8118. exception_handler = savehandler;
  8119. INT_ON;
  8120. evalskip &= ~SKIPFUNC;
  8121. return e;
  8122. }
  8123. #if ENABLE_ASH_CMDCMD
  8124. static char **
  8125. parse_command_args(char **argv, const char **path)
  8126. {
  8127. char *cp, c;
  8128. for (;;) {
  8129. cp = *++argv;
  8130. if (!cp)
  8131. return NULL;
  8132. if (*cp++ != '-')
  8133. break;
  8134. c = *cp++;
  8135. if (!c)
  8136. break;
  8137. if (c == '-' && !*cp) {
  8138. if (!*++argv)
  8139. return NULL;
  8140. break;
  8141. }
  8142. do {
  8143. switch (c) {
  8144. case 'p':
  8145. *path = bb_default_path;
  8146. break;
  8147. default:
  8148. /* run 'typecmd' for other options */
  8149. return NULL;
  8150. }
  8151. c = *cp++;
  8152. } while (c);
  8153. }
  8154. return argv;
  8155. }
  8156. #endif
  8157. /*
  8158. * Make a variable a local variable. When a variable is made local, it's
  8159. * value and flags are saved in a localvar structure. The saved values
  8160. * will be restored when the shell function returns. We handle the name
  8161. * "-" as a special case: it makes changes to "set +-options" local
  8162. * (options will be restored on return from the function).
  8163. */
  8164. static void
  8165. mklocal(char *name)
  8166. {
  8167. struct localvar *lvp;
  8168. struct var **vpp;
  8169. struct var *vp;
  8170. char *eq = strchr(name, '=');
  8171. INT_OFF;
  8172. /* Cater for duplicate "local". Examples:
  8173. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8174. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8175. */
  8176. lvp = localvars;
  8177. while (lvp) {
  8178. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8179. if (eq)
  8180. setvareq(name, 0);
  8181. /* else:
  8182. * it's a duplicate "local VAR" declaration, do nothing
  8183. */
  8184. return;
  8185. }
  8186. lvp = lvp->next;
  8187. }
  8188. lvp = ckzalloc(sizeof(*lvp));
  8189. if (LONE_DASH(name)) {
  8190. char *p;
  8191. p = ckmalloc(sizeof(optlist));
  8192. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8193. vp = NULL;
  8194. } else {
  8195. vpp = hashvar(name);
  8196. vp = *findvar(vpp, name);
  8197. if (vp == NULL) {
  8198. /* variable did not exist yet */
  8199. if (eq)
  8200. setvareq(name, VSTRFIXED);
  8201. else
  8202. setvar(name, NULL, VSTRFIXED);
  8203. vp = *vpp; /* the new variable */
  8204. lvp->flags = VUNSET;
  8205. } else {
  8206. lvp->text = vp->var_text;
  8207. lvp->flags = vp->flags;
  8208. /* make sure neither "struct var" nor string gets freed
  8209. * during (un)setting:
  8210. */
  8211. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8212. if (eq)
  8213. setvareq(name, 0);
  8214. else
  8215. /* "local VAR" unsets VAR: */
  8216. setvar0(name, NULL);
  8217. }
  8218. }
  8219. lvp->vp = vp;
  8220. lvp->next = localvars;
  8221. localvars = lvp;
  8222. INT_ON;
  8223. }
  8224. /*
  8225. * The "local" command.
  8226. */
  8227. static int FAST_FUNC
  8228. localcmd(int argc UNUSED_PARAM, char **argv)
  8229. {
  8230. char *name;
  8231. if (!funcnest)
  8232. ash_msg_and_raise_error("not in a function");
  8233. argv = argptr;
  8234. while ((name = *argv++) != NULL) {
  8235. mklocal(name);
  8236. }
  8237. return 0;
  8238. }
  8239. static int FAST_FUNC
  8240. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8241. {
  8242. return 1;
  8243. }
  8244. static int FAST_FUNC
  8245. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8246. {
  8247. return 0;
  8248. }
  8249. static int FAST_FUNC
  8250. execcmd(int argc UNUSED_PARAM, char **argv)
  8251. {
  8252. if (argv[1]) {
  8253. iflag = 0; /* exit on error */
  8254. mflag = 0;
  8255. optschanged();
  8256. shellexec(argv + 1, pathval(), 0);
  8257. }
  8258. return 0;
  8259. }
  8260. /*
  8261. * The return command.
  8262. */
  8263. static int FAST_FUNC
  8264. returncmd(int argc UNUSED_PARAM, char **argv)
  8265. {
  8266. /*
  8267. * If called outside a function, do what ksh does;
  8268. * skip the rest of the file.
  8269. */
  8270. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8271. return argv[1] ? number(argv[1]) : exitstatus;
  8272. }
  8273. /* Forward declarations for builtintab[] */
  8274. static int breakcmd(int, char **) FAST_FUNC;
  8275. static int dotcmd(int, char **) FAST_FUNC;
  8276. static int evalcmd(int, char **) FAST_FUNC;
  8277. static int exitcmd(int, char **) FAST_FUNC;
  8278. static int exportcmd(int, char **) FAST_FUNC;
  8279. #if ENABLE_ASH_GETOPTS
  8280. static int getoptscmd(int, char **) FAST_FUNC;
  8281. #endif
  8282. #if ENABLE_ASH_HELP
  8283. static int helpcmd(int, char **) FAST_FUNC;
  8284. #endif
  8285. #if MAX_HISTORY
  8286. static int historycmd(int, char **) FAST_FUNC;
  8287. #endif
  8288. #if ENABLE_SH_MATH_SUPPORT
  8289. static int letcmd(int, char **) FAST_FUNC;
  8290. #endif
  8291. static int readcmd(int, char **) FAST_FUNC;
  8292. static int setcmd(int, char **) FAST_FUNC;
  8293. static int shiftcmd(int, char **) FAST_FUNC;
  8294. static int timescmd(int, char **) FAST_FUNC;
  8295. static int trapcmd(int, char **) FAST_FUNC;
  8296. static int umaskcmd(int, char **) FAST_FUNC;
  8297. static int unsetcmd(int, char **) FAST_FUNC;
  8298. static int ulimitcmd(int, char **) FAST_FUNC;
  8299. #define BUILTIN_NOSPEC "0"
  8300. #define BUILTIN_SPECIAL "1"
  8301. #define BUILTIN_REGULAR "2"
  8302. #define BUILTIN_SPEC_REG "3"
  8303. #define BUILTIN_ASSIGN "4"
  8304. #define BUILTIN_SPEC_ASSG "5"
  8305. #define BUILTIN_REG_ASSG "6"
  8306. #define BUILTIN_SPEC_REG_ASSG "7"
  8307. /* Stubs for calling non-FAST_FUNC's */
  8308. #if ENABLE_ASH_BUILTIN_ECHO
  8309. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8310. #endif
  8311. #if ENABLE_ASH_BUILTIN_PRINTF
  8312. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8313. #endif
  8314. #if ENABLE_ASH_BUILTIN_TEST
  8315. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8316. #endif
  8317. /* Keep these in proper order since it is searched via bsearch() */
  8318. static const struct builtincmd builtintab[] = {
  8319. { BUILTIN_SPEC_REG "." , dotcmd },
  8320. { BUILTIN_SPEC_REG ":" , truecmd },
  8321. #if ENABLE_ASH_BUILTIN_TEST
  8322. { BUILTIN_REGULAR "[" , testcmd },
  8323. #if ENABLE_ASH_BASH_COMPAT
  8324. { BUILTIN_REGULAR "[[" , testcmd },
  8325. #endif
  8326. #endif
  8327. #if ENABLE_ASH_ALIAS
  8328. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8329. #endif
  8330. #if JOBS
  8331. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8332. #endif
  8333. { BUILTIN_SPEC_REG "break" , breakcmd },
  8334. { BUILTIN_REGULAR "cd" , cdcmd },
  8335. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8336. #if ENABLE_ASH_CMDCMD
  8337. { BUILTIN_REGULAR "command" , commandcmd },
  8338. #endif
  8339. { BUILTIN_SPEC_REG "continue", breakcmd },
  8340. #if ENABLE_ASH_BUILTIN_ECHO
  8341. { BUILTIN_REGULAR "echo" , echocmd },
  8342. #endif
  8343. { BUILTIN_SPEC_REG "eval" , evalcmd },
  8344. { BUILTIN_SPEC_REG "exec" , execcmd },
  8345. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8346. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8347. { BUILTIN_REGULAR "false" , falsecmd },
  8348. #if JOBS
  8349. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8350. #endif
  8351. #if ENABLE_ASH_GETOPTS
  8352. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8353. #endif
  8354. { BUILTIN_NOSPEC "hash" , hashcmd },
  8355. #if ENABLE_ASH_HELP
  8356. { BUILTIN_NOSPEC "help" , helpcmd },
  8357. #endif
  8358. #if MAX_HISTORY
  8359. { BUILTIN_NOSPEC "history" , historycmd },
  8360. #endif
  8361. #if JOBS
  8362. { BUILTIN_REGULAR "jobs" , jobscmd },
  8363. { BUILTIN_REGULAR "kill" , killcmd },
  8364. #endif
  8365. #if ENABLE_SH_MATH_SUPPORT
  8366. { BUILTIN_NOSPEC "let" , letcmd },
  8367. #endif
  8368. { BUILTIN_ASSIGN "local" , localcmd },
  8369. #if ENABLE_ASH_BUILTIN_PRINTF
  8370. { BUILTIN_REGULAR "printf" , printfcmd },
  8371. #endif
  8372. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8373. { BUILTIN_REGULAR "read" , readcmd },
  8374. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8375. { BUILTIN_SPEC_REG "return" , returncmd },
  8376. { BUILTIN_SPEC_REG "set" , setcmd },
  8377. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8378. #if ENABLE_ASH_BASH_COMPAT
  8379. { BUILTIN_SPEC_REG "source" , dotcmd },
  8380. #endif
  8381. #if ENABLE_ASH_BUILTIN_TEST
  8382. { BUILTIN_REGULAR "test" , testcmd },
  8383. #endif
  8384. { BUILTIN_SPEC_REG "times" , timescmd },
  8385. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8386. { BUILTIN_REGULAR "true" , truecmd },
  8387. { BUILTIN_NOSPEC "type" , typecmd },
  8388. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8389. { BUILTIN_REGULAR "umask" , umaskcmd },
  8390. #if ENABLE_ASH_ALIAS
  8391. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8392. #endif
  8393. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8394. { BUILTIN_REGULAR "wait" , waitcmd },
  8395. };
  8396. /* Should match the above table! */
  8397. #define COMMANDCMD (builtintab + \
  8398. 2 + \
  8399. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8400. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8401. 1 * ENABLE_ASH_ALIAS + \
  8402. 1 * ENABLE_ASH_JOB_CONTROL + \
  8403. 3)
  8404. #define EXECCMD (builtintab + \
  8405. 2 + \
  8406. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8407. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8408. 1 * ENABLE_ASH_ALIAS + \
  8409. 1 * ENABLE_ASH_JOB_CONTROL + \
  8410. 3 + \
  8411. 1 * ENABLE_ASH_CMDCMD + \
  8412. 1 + \
  8413. ENABLE_ASH_BUILTIN_ECHO + \
  8414. 1)
  8415. /*
  8416. * Search the table of builtin commands.
  8417. */
  8418. static struct builtincmd *
  8419. find_builtin(const char *name)
  8420. {
  8421. struct builtincmd *bp;
  8422. bp = bsearch(
  8423. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8424. pstrcmp
  8425. );
  8426. return bp;
  8427. }
  8428. /*
  8429. * Execute a simple command.
  8430. */
  8431. static int
  8432. isassignment(const char *p)
  8433. {
  8434. const char *q = endofname(p);
  8435. if (p == q)
  8436. return 0;
  8437. return *q == '=';
  8438. }
  8439. static int FAST_FUNC
  8440. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8441. {
  8442. /* Preserve exitstatus of a previous possible redirection
  8443. * as POSIX mandates */
  8444. return back_exitstatus;
  8445. }
  8446. static void
  8447. evalcommand(union node *cmd, int flags)
  8448. {
  8449. static const struct builtincmd null_bltin = {
  8450. "\0\0", bltincmd /* why three NULs? */
  8451. };
  8452. struct stackmark smark;
  8453. union node *argp;
  8454. struct arglist arglist;
  8455. struct arglist varlist;
  8456. char **argv;
  8457. int argc;
  8458. const struct strlist *sp;
  8459. struct cmdentry cmdentry;
  8460. struct job *jp;
  8461. char *lastarg;
  8462. const char *path;
  8463. int spclbltin;
  8464. int status;
  8465. char **nargv;
  8466. struct builtincmd *bcmd;
  8467. smallint cmd_is_exec;
  8468. smallint pseudovarflag = 0;
  8469. /* First expand the arguments. */
  8470. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8471. setstackmark(&smark);
  8472. back_exitstatus = 0;
  8473. cmdentry.cmdtype = CMDBUILTIN;
  8474. cmdentry.u.cmd = &null_bltin;
  8475. varlist.lastp = &varlist.list;
  8476. *varlist.lastp = NULL;
  8477. arglist.lastp = &arglist.list;
  8478. *arglist.lastp = NULL;
  8479. argc = 0;
  8480. if (cmd->ncmd.args) {
  8481. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8482. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8483. }
  8484. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8485. struct strlist **spp;
  8486. spp = arglist.lastp;
  8487. if (pseudovarflag && isassignment(argp->narg.text))
  8488. expandarg(argp, &arglist, EXP_VARTILDE);
  8489. else
  8490. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8491. for (sp = *spp; sp; sp = sp->next)
  8492. argc++;
  8493. }
  8494. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8495. for (sp = arglist.list; sp; sp = sp->next) {
  8496. TRACE(("evalcommand arg: %s\n", sp->text));
  8497. *nargv++ = sp->text;
  8498. }
  8499. *nargv = NULL;
  8500. lastarg = NULL;
  8501. if (iflag && funcnest == 0 && argc > 0)
  8502. lastarg = nargv[-1];
  8503. preverrout_fd = 2;
  8504. expredir(cmd->ncmd.redirect);
  8505. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8506. path = vpath.var_text;
  8507. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8508. struct strlist **spp;
  8509. char *p;
  8510. spp = varlist.lastp;
  8511. expandarg(argp, &varlist, EXP_VARTILDE);
  8512. /*
  8513. * Modify the command lookup path, if a PATH= assignment
  8514. * is present
  8515. */
  8516. p = (*spp)->text;
  8517. if (varcmp(p, path) == 0)
  8518. path = p;
  8519. }
  8520. /* Print the command if xflag is set. */
  8521. if (xflag) {
  8522. int n;
  8523. const char *p = " %s" + 1;
  8524. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8525. sp = varlist.list;
  8526. for (n = 0; n < 2; n++) {
  8527. while (sp) {
  8528. fdprintf(preverrout_fd, p, sp->text);
  8529. sp = sp->next;
  8530. p = " %s";
  8531. }
  8532. sp = arglist.list;
  8533. }
  8534. safe_write(preverrout_fd, "\n", 1);
  8535. }
  8536. cmd_is_exec = 0;
  8537. spclbltin = -1;
  8538. /* Now locate the command. */
  8539. if (argc) {
  8540. int cmd_flag = DO_ERR;
  8541. #if ENABLE_ASH_CMDCMD
  8542. const char *oldpath = path + 5;
  8543. #endif
  8544. path += 5;
  8545. for (;;) {
  8546. find_command(argv[0], &cmdentry, cmd_flag, path);
  8547. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8548. flush_stdout_stderr();
  8549. status = 127;
  8550. goto bail;
  8551. }
  8552. /* implement bltin and command here */
  8553. if (cmdentry.cmdtype != CMDBUILTIN)
  8554. break;
  8555. if (spclbltin < 0)
  8556. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8557. if (cmdentry.u.cmd == EXECCMD)
  8558. cmd_is_exec = 1;
  8559. #if ENABLE_ASH_CMDCMD
  8560. if (cmdentry.u.cmd == COMMANDCMD) {
  8561. path = oldpath;
  8562. nargv = parse_command_args(argv, &path);
  8563. if (!nargv)
  8564. break;
  8565. argc -= nargv - argv;
  8566. argv = nargv;
  8567. cmd_flag |= DO_NOFUNC;
  8568. } else
  8569. #endif
  8570. break;
  8571. }
  8572. }
  8573. if (status) {
  8574. /* We have a redirection error. */
  8575. if (spclbltin > 0)
  8576. raise_exception(EXERROR);
  8577. bail:
  8578. exitstatus = status;
  8579. goto out;
  8580. }
  8581. /* Execute the command. */
  8582. switch (cmdentry.cmdtype) {
  8583. default: {
  8584. #if ENABLE_FEATURE_SH_NOFORK
  8585. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  8586. * around run_nofork_applet() call.
  8587. * (2) Should this check also be done in forkshell()?
  8588. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  8589. */
  8590. /* find_command() encodes applet_no as (-2 - applet_no) */
  8591. int applet_no = (- cmdentry.u.index - 2);
  8592. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8593. listsetvar(varlist.list, VEXPORT|VSTACK);
  8594. /* run <applet>_main() */
  8595. exitstatus = run_nofork_applet(applet_no, argv);
  8596. break;
  8597. }
  8598. #endif
  8599. /* Can we avoid forking off? For example, very last command
  8600. * in a script or a subshell does not need forking,
  8601. * we can just exec it.
  8602. */
  8603. if (!(flags & EV_EXIT) || may_have_traps) {
  8604. /* No, forking off a child is necessary */
  8605. INT_OFF;
  8606. jp = makejob(/*cmd,*/ 1);
  8607. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8608. /* parent */
  8609. exitstatus = waitforjob(jp);
  8610. INT_ON;
  8611. TRACE(("forked child exited with %d\n", exitstatus));
  8612. break;
  8613. }
  8614. /* child */
  8615. FORCE_INT_ON;
  8616. /* fall through to exec'ing external program */
  8617. }
  8618. listsetvar(varlist.list, VEXPORT|VSTACK);
  8619. shellexec(argv, path, cmdentry.u.index);
  8620. /* NOTREACHED */
  8621. } /* default */
  8622. case CMDBUILTIN:
  8623. cmdenviron = varlist.list;
  8624. if (cmdenviron) {
  8625. struct strlist *list = cmdenviron;
  8626. int i = VNOSET;
  8627. if (spclbltin > 0 || argc == 0) {
  8628. i = 0;
  8629. if (cmd_is_exec && argc > 1)
  8630. i = VEXPORT;
  8631. }
  8632. listsetvar(list, i);
  8633. }
  8634. /* Tight loop with builtins only:
  8635. * "while kill -0 $child; do true; done"
  8636. * will never exit even if $child died, unless we do this
  8637. * to reap the zombie and make kill detect that it's gone: */
  8638. dowait(DOWAIT_NONBLOCK, NULL);
  8639. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8640. int exit_status;
  8641. int i = exception_type;
  8642. if (i == EXEXIT || i == EXEXEC)
  8643. goto raise;
  8644. exit_status = 2;
  8645. if (i == EXINT)
  8646. exit_status = 128 + SIGINT;
  8647. if (i == EXSIG)
  8648. exit_status = 128 + pending_sig;
  8649. exitstatus = exit_status;
  8650. if (i == EXINT || spclbltin > 0) {
  8651. raise:
  8652. longjmp(exception_handler->loc, 1);
  8653. }
  8654. FORCE_INT_ON;
  8655. }
  8656. break;
  8657. case CMDFUNCTION:
  8658. listsetvar(varlist.list, 0);
  8659. /* See above for the rationale */
  8660. dowait(DOWAIT_NONBLOCK, NULL);
  8661. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8662. goto raise;
  8663. break;
  8664. } /* switch */
  8665. out:
  8666. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8667. if (lastarg) {
  8668. /* dsl: I think this is intended to be used to support
  8669. * '_' in 'vi' command mode during line editing...
  8670. * However I implemented that within libedit itself.
  8671. */
  8672. setvar0("_", lastarg);
  8673. }
  8674. popstackmark(&smark);
  8675. }
  8676. static int
  8677. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8678. {
  8679. char *volatile savecmdname;
  8680. struct jmploc *volatile savehandler;
  8681. struct jmploc jmploc;
  8682. int i;
  8683. savecmdname = commandname;
  8684. i = setjmp(jmploc.loc);
  8685. if (i)
  8686. goto cmddone;
  8687. savehandler = exception_handler;
  8688. exception_handler = &jmploc;
  8689. commandname = argv[0];
  8690. argptr = argv + 1;
  8691. optptr = NULL; /* initialize nextopt */
  8692. exitstatus = (*cmd->builtin)(argc, argv);
  8693. flush_stdout_stderr();
  8694. cmddone:
  8695. exitstatus |= ferror(stdout);
  8696. clearerr(stdout);
  8697. commandname = savecmdname;
  8698. exception_handler = savehandler;
  8699. return i;
  8700. }
  8701. static int
  8702. goodname(const char *p)
  8703. {
  8704. return endofname(p)[0] == '\0';
  8705. }
  8706. /*
  8707. * Search for a command. This is called before we fork so that the
  8708. * location of the command will be available in the parent as well as
  8709. * the child. The check for "goodname" is an overly conservative
  8710. * check that the name will not be subject to expansion.
  8711. */
  8712. static void
  8713. prehash(union node *n)
  8714. {
  8715. struct cmdentry entry;
  8716. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8717. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8718. }
  8719. /* ============ Builtin commands
  8720. *
  8721. * Builtin commands whose functions are closely tied to evaluation
  8722. * are implemented here.
  8723. */
  8724. /*
  8725. * Handle break and continue commands. Break, continue, and return are
  8726. * all handled by setting the evalskip flag. The evaluation routines
  8727. * above all check this flag, and if it is set they start skipping
  8728. * commands rather than executing them. The variable skipcount is
  8729. * the number of loops to break/continue, or the number of function
  8730. * levels to return. (The latter is always 1.) It should probably
  8731. * be an error to break out of more loops than exist, but it isn't
  8732. * in the standard shell so we don't make it one here.
  8733. */
  8734. static int FAST_FUNC
  8735. breakcmd(int argc UNUSED_PARAM, char **argv)
  8736. {
  8737. int n = argv[1] ? number(argv[1]) : 1;
  8738. if (n <= 0)
  8739. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8740. if (n > loopnest)
  8741. n = loopnest;
  8742. if (n > 0) {
  8743. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8744. skipcount = n;
  8745. }
  8746. return 0;
  8747. }
  8748. /* ============ input.c
  8749. *
  8750. * This implements the input routines used by the parser.
  8751. */
  8752. enum {
  8753. INPUT_PUSH_FILE = 1,
  8754. INPUT_NOFILE_OK = 2,
  8755. };
  8756. static smallint checkkwd;
  8757. /* values of checkkwd variable */
  8758. #define CHKALIAS 0x1
  8759. #define CHKKWD 0x2
  8760. #define CHKNL 0x4
  8761. /*
  8762. * Push a string back onto the input at this current parsefile level.
  8763. * We handle aliases this way.
  8764. */
  8765. #if !ENABLE_ASH_ALIAS
  8766. #define pushstring(s, ap) pushstring(s)
  8767. #endif
  8768. static void
  8769. pushstring(char *s, struct alias *ap)
  8770. {
  8771. struct strpush *sp;
  8772. int len;
  8773. len = strlen(s);
  8774. INT_OFF;
  8775. if (g_parsefile->strpush) {
  8776. sp = ckzalloc(sizeof(*sp));
  8777. sp->prev = g_parsefile->strpush;
  8778. } else {
  8779. sp = &(g_parsefile->basestrpush);
  8780. }
  8781. g_parsefile->strpush = sp;
  8782. sp->prev_string = g_parsefile->next_to_pgetc;
  8783. sp->prev_left_in_line = g_parsefile->left_in_line;
  8784. #if ENABLE_ASH_ALIAS
  8785. sp->ap = ap;
  8786. if (ap) {
  8787. ap->flag |= ALIASINUSE;
  8788. sp->string = s;
  8789. }
  8790. #endif
  8791. g_parsefile->next_to_pgetc = s;
  8792. g_parsefile->left_in_line = len;
  8793. INT_ON;
  8794. }
  8795. static void
  8796. popstring(void)
  8797. {
  8798. struct strpush *sp = g_parsefile->strpush;
  8799. INT_OFF;
  8800. #if ENABLE_ASH_ALIAS
  8801. if (sp->ap) {
  8802. if (g_parsefile->next_to_pgetc[-1] == ' '
  8803. || g_parsefile->next_to_pgetc[-1] == '\t'
  8804. ) {
  8805. checkkwd |= CHKALIAS;
  8806. }
  8807. if (sp->string != sp->ap->val) {
  8808. free(sp->string);
  8809. }
  8810. sp->ap->flag &= ~ALIASINUSE;
  8811. if (sp->ap->flag & ALIASDEAD) {
  8812. unalias(sp->ap->name);
  8813. }
  8814. }
  8815. #endif
  8816. g_parsefile->next_to_pgetc = sp->prev_string;
  8817. g_parsefile->left_in_line = sp->prev_left_in_line;
  8818. g_parsefile->strpush = sp->prev;
  8819. if (sp != &(g_parsefile->basestrpush))
  8820. free(sp);
  8821. INT_ON;
  8822. }
  8823. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8824. //it peeks whether it is &>, and then pushes back both chars.
  8825. //This function needs to save last *next_to_pgetc to buf[0]
  8826. //to make two pungetc() reliable. Currently,
  8827. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8828. static int
  8829. preadfd(void)
  8830. {
  8831. int nr;
  8832. char *buf = g_parsefile->buf;
  8833. g_parsefile->next_to_pgetc = buf;
  8834. #if ENABLE_FEATURE_EDITING
  8835. retry:
  8836. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  8837. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  8838. else {
  8839. int timeout = -1;
  8840. # if ENABLE_ASH_IDLE_TIMEOUT
  8841. if (iflag) {
  8842. const char *tmout_var = lookupvar("TMOUT");
  8843. if (tmout_var) {
  8844. timeout = atoi(tmout_var) * 1000;
  8845. if (timeout <= 0)
  8846. timeout = -1;
  8847. }
  8848. }
  8849. # endif
  8850. # if ENABLE_FEATURE_TAB_COMPLETION
  8851. line_input_state->path_lookup = pathval();
  8852. # endif
  8853. reinit_unicode_for_ash();
  8854. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
  8855. if (nr == 0) {
  8856. /* Ctrl+C pressed */
  8857. if (trap[SIGINT]) {
  8858. buf[0] = '\n';
  8859. buf[1] = '\0';
  8860. raise(SIGINT);
  8861. return 1;
  8862. }
  8863. goto retry;
  8864. }
  8865. if (nr < 0) {
  8866. if (errno == 0) {
  8867. /* Ctrl+D pressed */
  8868. nr = 0;
  8869. }
  8870. # if ENABLE_ASH_IDLE_TIMEOUT
  8871. else if (errno == EAGAIN && timeout > 0) {
  8872. puts("\007timed out waiting for input: auto-logout");
  8873. exitshell();
  8874. }
  8875. # endif
  8876. }
  8877. }
  8878. #else
  8879. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  8880. #endif
  8881. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  8882. if (nr < 0) {
  8883. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8884. int flags = fcntl(0, F_GETFL);
  8885. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8886. flags &= ~O_NONBLOCK;
  8887. if (fcntl(0, F_SETFL, flags) >= 0) {
  8888. out2str("sh: turning off NDELAY mode\n");
  8889. goto retry;
  8890. }
  8891. }
  8892. }
  8893. }
  8894. #endif
  8895. return nr;
  8896. }
  8897. /*
  8898. * Refill the input buffer and return the next input character:
  8899. *
  8900. * 1) If a string was pushed back on the input, pop it;
  8901. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8902. * or we are reading from a string so we can't refill the buffer,
  8903. * return EOF.
  8904. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8905. * 4) Process input up to the next newline, deleting nul characters.
  8906. */
  8907. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8908. #define pgetc_debug(...) ((void)0)
  8909. static int
  8910. preadbuffer(void)
  8911. {
  8912. char *q;
  8913. int more;
  8914. while (g_parsefile->strpush) {
  8915. #if ENABLE_ASH_ALIAS
  8916. if (g_parsefile->left_in_line == -1
  8917. && g_parsefile->strpush->ap
  8918. && g_parsefile->next_to_pgetc[-1] != ' '
  8919. && g_parsefile->next_to_pgetc[-1] != '\t'
  8920. ) {
  8921. pgetc_debug("preadbuffer PEOA");
  8922. return PEOA;
  8923. }
  8924. #endif
  8925. popstring();
  8926. /* try "pgetc" now: */
  8927. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8928. g_parsefile->left_in_line,
  8929. g_parsefile->next_to_pgetc,
  8930. g_parsefile->next_to_pgetc);
  8931. if (--g_parsefile->left_in_line >= 0)
  8932. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8933. }
  8934. /* on both branches above g_parsefile->left_in_line < 0.
  8935. * "pgetc" needs refilling.
  8936. */
  8937. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8938. * pungetc() may increment it a few times.
  8939. * Assuming it won't increment it to less than -90.
  8940. */
  8941. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8942. pgetc_debug("preadbuffer PEOF1");
  8943. /* even in failure keep left_in_line and next_to_pgetc
  8944. * in lock step, for correct multi-layer pungetc.
  8945. * left_in_line was decremented before preadbuffer(),
  8946. * must inc next_to_pgetc: */
  8947. g_parsefile->next_to_pgetc++;
  8948. return PEOF;
  8949. }
  8950. more = g_parsefile->left_in_buffer;
  8951. if (more <= 0) {
  8952. flush_stdout_stderr();
  8953. again:
  8954. more = preadfd();
  8955. if (more <= 0) {
  8956. /* don't try reading again */
  8957. g_parsefile->left_in_line = -99;
  8958. pgetc_debug("preadbuffer PEOF2");
  8959. g_parsefile->next_to_pgetc++;
  8960. return PEOF;
  8961. }
  8962. }
  8963. /* Find out where's the end of line.
  8964. * Set g_parsefile->left_in_line
  8965. * and g_parsefile->left_in_buffer acordingly.
  8966. * NUL chars are deleted.
  8967. */
  8968. q = g_parsefile->next_to_pgetc;
  8969. for (;;) {
  8970. char c;
  8971. more--;
  8972. c = *q;
  8973. if (c == '\0') {
  8974. memmove(q, q + 1, more);
  8975. } else {
  8976. q++;
  8977. if (c == '\n') {
  8978. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8979. break;
  8980. }
  8981. }
  8982. if (more <= 0) {
  8983. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8984. if (g_parsefile->left_in_line < 0)
  8985. goto again;
  8986. break;
  8987. }
  8988. }
  8989. g_parsefile->left_in_buffer = more;
  8990. if (vflag) {
  8991. char save = *q;
  8992. *q = '\0';
  8993. out2str(g_parsefile->next_to_pgetc);
  8994. *q = save;
  8995. }
  8996. pgetc_debug("preadbuffer at %d:%p'%s'",
  8997. g_parsefile->left_in_line,
  8998. g_parsefile->next_to_pgetc,
  8999. g_parsefile->next_to_pgetc);
  9000. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9001. }
  9002. #define pgetc_as_macro() \
  9003. (--g_parsefile->left_in_line >= 0 \
  9004. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  9005. : preadbuffer() \
  9006. )
  9007. static int
  9008. pgetc(void)
  9009. {
  9010. pgetc_debug("pgetc_fast at %d:%p'%s'",
  9011. g_parsefile->left_in_line,
  9012. g_parsefile->next_to_pgetc,
  9013. g_parsefile->next_to_pgetc);
  9014. return pgetc_as_macro();
  9015. }
  9016. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  9017. # define pgetc_fast() pgetc()
  9018. #else
  9019. # define pgetc_fast() pgetc_as_macro()
  9020. #endif
  9021. #if ENABLE_ASH_ALIAS
  9022. static int
  9023. pgetc_without_PEOA(void)
  9024. {
  9025. int c;
  9026. do {
  9027. pgetc_debug("pgetc_fast at %d:%p'%s'",
  9028. g_parsefile->left_in_line,
  9029. g_parsefile->next_to_pgetc,
  9030. g_parsefile->next_to_pgetc);
  9031. c = pgetc_fast();
  9032. } while (c == PEOA);
  9033. return c;
  9034. }
  9035. #else
  9036. # define pgetc_without_PEOA() pgetc()
  9037. #endif
  9038. /*
  9039. * Read a line from the script.
  9040. */
  9041. static char *
  9042. pfgets(char *line, int len)
  9043. {
  9044. char *p = line;
  9045. int nleft = len;
  9046. int c;
  9047. while (--nleft > 0) {
  9048. c = pgetc_without_PEOA();
  9049. if (c == PEOF) {
  9050. if (p == line)
  9051. return NULL;
  9052. break;
  9053. }
  9054. *p++ = c;
  9055. if (c == '\n')
  9056. break;
  9057. }
  9058. *p = '\0';
  9059. return line;
  9060. }
  9061. /*
  9062. * Undo the last call to pgetc. Only one character may be pushed back.
  9063. * PEOF may be pushed back.
  9064. */
  9065. static void
  9066. pungetc(void)
  9067. {
  9068. g_parsefile->left_in_line++;
  9069. g_parsefile->next_to_pgetc--;
  9070. pgetc_debug("pushed back to %d:%p'%s'",
  9071. g_parsefile->left_in_line,
  9072. g_parsefile->next_to_pgetc,
  9073. g_parsefile->next_to_pgetc);
  9074. }
  9075. /*
  9076. * To handle the "." command, a stack of input files is used. Pushfile
  9077. * adds a new entry to the stack and popfile restores the previous level.
  9078. */
  9079. static void
  9080. pushfile(void)
  9081. {
  9082. struct parsefile *pf;
  9083. pf = ckzalloc(sizeof(*pf));
  9084. pf->prev = g_parsefile;
  9085. pf->pf_fd = -1;
  9086. /*pf->strpush = NULL; - ckzalloc did it */
  9087. /*pf->basestrpush.prev = NULL;*/
  9088. g_parsefile = pf;
  9089. }
  9090. static void
  9091. popfile(void)
  9092. {
  9093. struct parsefile *pf = g_parsefile;
  9094. INT_OFF;
  9095. if (pf->pf_fd >= 0)
  9096. close(pf->pf_fd);
  9097. free(pf->buf);
  9098. while (pf->strpush)
  9099. popstring();
  9100. g_parsefile = pf->prev;
  9101. free(pf);
  9102. INT_ON;
  9103. }
  9104. /*
  9105. * Return to top level.
  9106. */
  9107. static void
  9108. popallfiles(void)
  9109. {
  9110. while (g_parsefile != &basepf)
  9111. popfile();
  9112. }
  9113. /*
  9114. * Close the file(s) that the shell is reading commands from. Called
  9115. * after a fork is done.
  9116. */
  9117. static void
  9118. closescript(void)
  9119. {
  9120. popallfiles();
  9121. if (g_parsefile->pf_fd > 0) {
  9122. close(g_parsefile->pf_fd);
  9123. g_parsefile->pf_fd = 0;
  9124. }
  9125. }
  9126. /*
  9127. * Like setinputfile, but takes an open file descriptor. Call this with
  9128. * interrupts off.
  9129. */
  9130. static void
  9131. setinputfd(int fd, int push)
  9132. {
  9133. close_on_exec_on(fd);
  9134. if (push) {
  9135. pushfile();
  9136. g_parsefile->buf = NULL;
  9137. }
  9138. g_parsefile->pf_fd = fd;
  9139. if (g_parsefile->buf == NULL)
  9140. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9141. g_parsefile->left_in_buffer = 0;
  9142. g_parsefile->left_in_line = 0;
  9143. g_parsefile->linno = 1;
  9144. }
  9145. /*
  9146. * Set the input to take input from a file. If push is set, push the
  9147. * old input onto the stack first.
  9148. */
  9149. static int
  9150. setinputfile(const char *fname, int flags)
  9151. {
  9152. int fd;
  9153. int fd2;
  9154. INT_OFF;
  9155. fd = open(fname, O_RDONLY);
  9156. if (fd < 0) {
  9157. if (flags & INPUT_NOFILE_OK)
  9158. goto out;
  9159. ash_msg_and_raise_error("can't open '%s'", fname);
  9160. }
  9161. if (fd < 10) {
  9162. fd2 = copyfd(fd, 10);
  9163. close(fd);
  9164. if (fd2 < 0)
  9165. ash_msg_and_raise_error("out of file descriptors");
  9166. fd = fd2;
  9167. }
  9168. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9169. out:
  9170. INT_ON;
  9171. return fd;
  9172. }
  9173. /*
  9174. * Like setinputfile, but takes input from a string.
  9175. */
  9176. static void
  9177. setinputstring(char *string)
  9178. {
  9179. INT_OFF;
  9180. pushfile();
  9181. g_parsefile->next_to_pgetc = string;
  9182. g_parsefile->left_in_line = strlen(string);
  9183. g_parsefile->buf = NULL;
  9184. g_parsefile->linno = 1;
  9185. INT_ON;
  9186. }
  9187. /* ============ mail.c
  9188. *
  9189. * Routines to check for mail.
  9190. */
  9191. #if ENABLE_ASH_MAIL
  9192. /* Hash of mtimes of mailboxes */
  9193. static unsigned mailtime_hash;
  9194. /* Set if MAIL or MAILPATH is changed. */
  9195. static smallint mail_var_path_changed;
  9196. /*
  9197. * Print appropriate message(s) if mail has arrived.
  9198. * If mail_var_path_changed is set,
  9199. * then the value of MAIL has mail_var_path_changed,
  9200. * so we just update the values.
  9201. */
  9202. static void
  9203. chkmail(void)
  9204. {
  9205. const char *mpath;
  9206. char *p;
  9207. char *q;
  9208. unsigned new_hash;
  9209. struct stackmark smark;
  9210. struct stat statb;
  9211. setstackmark(&smark);
  9212. mpath = mpathset() ? mpathval() : mailval();
  9213. new_hash = 0;
  9214. for (;;) {
  9215. p = path_advance(&mpath, nullstr);
  9216. if (p == NULL)
  9217. break;
  9218. if (*p == '\0')
  9219. continue;
  9220. for (q = p; *q; q++)
  9221. continue;
  9222. #if DEBUG
  9223. if (q[-1] != '/')
  9224. abort();
  9225. #endif
  9226. q[-1] = '\0'; /* delete trailing '/' */
  9227. if (stat(p, &statb) < 0) {
  9228. continue;
  9229. }
  9230. /* Very simplistic "hash": just a sum of all mtimes */
  9231. new_hash += (unsigned)statb.st_mtime;
  9232. }
  9233. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9234. if (mailtime_hash != 0)
  9235. out2str("you have mail\n");
  9236. mailtime_hash = new_hash;
  9237. }
  9238. mail_var_path_changed = 0;
  9239. popstackmark(&smark);
  9240. }
  9241. static void FAST_FUNC
  9242. changemail(const char *val UNUSED_PARAM)
  9243. {
  9244. mail_var_path_changed = 1;
  9245. }
  9246. #endif /* ASH_MAIL */
  9247. /* ============ ??? */
  9248. /*
  9249. * Set the shell parameters.
  9250. */
  9251. static void
  9252. setparam(char **argv)
  9253. {
  9254. char **newparam;
  9255. char **ap;
  9256. int nparam;
  9257. for (nparam = 0; argv[nparam]; nparam++)
  9258. continue;
  9259. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9260. while (*argv) {
  9261. *ap++ = ckstrdup(*argv++);
  9262. }
  9263. *ap = NULL;
  9264. freeparam(&shellparam);
  9265. shellparam.malloced = 1;
  9266. shellparam.nparam = nparam;
  9267. shellparam.p = newparam;
  9268. #if ENABLE_ASH_GETOPTS
  9269. shellparam.optind = 1;
  9270. shellparam.optoff = -1;
  9271. #endif
  9272. }
  9273. /*
  9274. * Process shell options. The global variable argptr contains a pointer
  9275. * to the argument list; we advance it past the options.
  9276. *
  9277. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9278. * For a non-interactive shell, an error condition encountered
  9279. * by a special built-in ... shall cause the shell to write a diagnostic message
  9280. * to standard error and exit as shown in the following table:
  9281. * Error Special Built-In
  9282. * ...
  9283. * Utility syntax error (option or operand error) Shall exit
  9284. * ...
  9285. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9286. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9287. * and shell continues), and people rely on this behavior!
  9288. * Testcase:
  9289. * set -o barfoo 2>/dev/null
  9290. * echo $?
  9291. *
  9292. * Oh well. Let's mimic that.
  9293. */
  9294. static int
  9295. plus_minus_o(char *name, int val)
  9296. {
  9297. int i;
  9298. if (name) {
  9299. for (i = 0; i < NOPTS; i++) {
  9300. if (strcmp(name, optnames(i)) == 0) {
  9301. optlist[i] = val;
  9302. return 0;
  9303. }
  9304. }
  9305. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9306. return 1;
  9307. }
  9308. for (i = 0; i < NOPTS; i++) {
  9309. if (val) {
  9310. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9311. } else {
  9312. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9313. }
  9314. }
  9315. return 0;
  9316. }
  9317. static void
  9318. setoption(int flag, int val)
  9319. {
  9320. int i;
  9321. for (i = 0; i < NOPTS; i++) {
  9322. if (optletters(i) == flag) {
  9323. optlist[i] = val;
  9324. return;
  9325. }
  9326. }
  9327. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9328. /* NOTREACHED */
  9329. }
  9330. static int
  9331. options(int cmdline)
  9332. {
  9333. char *p;
  9334. int val;
  9335. int c;
  9336. if (cmdline)
  9337. minusc = NULL;
  9338. while ((p = *argptr) != NULL) {
  9339. c = *p++;
  9340. if (c != '-' && c != '+')
  9341. break;
  9342. argptr++;
  9343. val = 0; /* val = 0 if c == '+' */
  9344. if (c == '-') {
  9345. val = 1;
  9346. if (p[0] == '\0' || LONE_DASH(p)) {
  9347. if (!cmdline) {
  9348. /* "-" means turn off -x and -v */
  9349. if (p[0] == '\0')
  9350. xflag = vflag = 0;
  9351. /* "--" means reset params */
  9352. else if (*argptr == NULL)
  9353. setparam(argptr);
  9354. }
  9355. break; /* "-" or "--" terminates options */
  9356. }
  9357. }
  9358. /* first char was + or - */
  9359. while ((c = *p++) != '\0') {
  9360. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9361. if (c == 'c' && cmdline) {
  9362. minusc = p; /* command is after shell args */
  9363. } else if (c == 'o') {
  9364. if (plus_minus_o(*argptr, val)) {
  9365. /* it already printed err message */
  9366. return 1; /* error */
  9367. }
  9368. if (*argptr)
  9369. argptr++;
  9370. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9371. isloginsh = 1;
  9372. /* bash does not accept +-login, we also won't */
  9373. } else if (cmdline && val && (c == '-')) { /* long options */
  9374. if (strcmp(p, "login") == 0)
  9375. isloginsh = 1;
  9376. break;
  9377. } else {
  9378. setoption(c, val);
  9379. }
  9380. }
  9381. }
  9382. return 0;
  9383. }
  9384. /*
  9385. * The shift builtin command.
  9386. */
  9387. static int FAST_FUNC
  9388. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9389. {
  9390. int n;
  9391. char **ap1, **ap2;
  9392. n = 1;
  9393. if (argv[1])
  9394. n = number(argv[1]);
  9395. if (n > shellparam.nparam)
  9396. n = 0; /* bash compat, was = shellparam.nparam; */
  9397. INT_OFF;
  9398. shellparam.nparam -= n;
  9399. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9400. if (shellparam.malloced)
  9401. free(*ap1);
  9402. }
  9403. ap2 = shellparam.p;
  9404. while ((*ap2++ = *ap1++) != NULL)
  9405. continue;
  9406. #if ENABLE_ASH_GETOPTS
  9407. shellparam.optind = 1;
  9408. shellparam.optoff = -1;
  9409. #endif
  9410. INT_ON;
  9411. return 0;
  9412. }
  9413. /*
  9414. * POSIX requires that 'set' (but not export or readonly) output the
  9415. * variables in lexicographic order - by the locale's collating order (sigh).
  9416. * Maybe we could keep them in an ordered balanced binary tree
  9417. * instead of hashed lists.
  9418. * For now just roll 'em through qsort for printing...
  9419. */
  9420. static int
  9421. showvars(const char *sep_prefix, int on, int off)
  9422. {
  9423. const char *sep;
  9424. char **ep, **epend;
  9425. ep = listvars(on, off, &epend);
  9426. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9427. sep = *sep_prefix ? " " : sep_prefix;
  9428. for (; ep < epend; ep++) {
  9429. const char *p;
  9430. const char *q;
  9431. p = strchrnul(*ep, '=');
  9432. q = nullstr;
  9433. if (*p)
  9434. q = single_quote(++p);
  9435. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9436. }
  9437. return 0;
  9438. }
  9439. /*
  9440. * The set command builtin.
  9441. */
  9442. static int FAST_FUNC
  9443. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9444. {
  9445. int retval;
  9446. if (!argv[1])
  9447. return showvars(nullstr, 0, VUNSET);
  9448. INT_OFF;
  9449. retval = options(/*cmdline:*/ 0);
  9450. if (retval == 0) { /* if no parse error... */
  9451. optschanged();
  9452. if (*argptr != NULL) {
  9453. setparam(argptr);
  9454. }
  9455. }
  9456. INT_ON;
  9457. return retval;
  9458. }
  9459. #if ENABLE_ASH_RANDOM_SUPPORT
  9460. static void FAST_FUNC
  9461. change_random(const char *value)
  9462. {
  9463. uint32_t t;
  9464. if (value == NULL) {
  9465. /* "get", generate */
  9466. t = next_random(&random_gen);
  9467. /* set without recursion */
  9468. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9469. vrandom.flags &= ~VNOFUNC;
  9470. } else {
  9471. /* set/reset */
  9472. t = strtoul(value, NULL, 10);
  9473. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9474. }
  9475. }
  9476. #endif
  9477. #if ENABLE_ASH_GETOPTS
  9478. static int
  9479. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9480. {
  9481. char *p, *q;
  9482. char c = '?';
  9483. int done = 0;
  9484. int err = 0;
  9485. char sbuf[2];
  9486. char **optnext;
  9487. sbuf[1] = '\0';
  9488. if (*param_optind < 1)
  9489. return 1;
  9490. optnext = optfirst + *param_optind - 1;
  9491. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9492. p = NULL;
  9493. else
  9494. p = optnext[-1] + *optoff;
  9495. if (p == NULL || *p == '\0') {
  9496. /* Current word is done, advance */
  9497. p = *optnext;
  9498. if (p == NULL || *p != '-' || *++p == '\0') {
  9499. atend:
  9500. p = NULL;
  9501. done = 1;
  9502. goto out;
  9503. }
  9504. optnext++;
  9505. if (LONE_DASH(p)) /* check for "--" */
  9506. goto atend;
  9507. }
  9508. c = *p++;
  9509. for (q = optstr; *q != c;) {
  9510. if (*q == '\0') {
  9511. if (optstr[0] == ':') {
  9512. sbuf[0] = c;
  9513. /*sbuf[1] = '\0'; - already is */
  9514. err |= setvarsafe("OPTARG", sbuf, 0);
  9515. } else {
  9516. fprintf(stderr, "Illegal option -%c\n", c);
  9517. unsetvar("OPTARG");
  9518. }
  9519. c = '?';
  9520. goto out;
  9521. }
  9522. if (*++q == ':')
  9523. q++;
  9524. }
  9525. if (*++q == ':') {
  9526. if (*p == '\0' && (p = *optnext) == NULL) {
  9527. if (optstr[0] == ':') {
  9528. sbuf[0] = c;
  9529. /*sbuf[1] = '\0'; - already is */
  9530. err |= setvarsafe("OPTARG", sbuf, 0);
  9531. c = ':';
  9532. } else {
  9533. fprintf(stderr, "No arg for -%c option\n", c);
  9534. unsetvar("OPTARG");
  9535. c = '?';
  9536. }
  9537. goto out;
  9538. }
  9539. if (p == *optnext)
  9540. optnext++;
  9541. err |= setvarsafe("OPTARG", p, 0);
  9542. p = NULL;
  9543. } else
  9544. err |= setvarsafe("OPTARG", nullstr, 0);
  9545. out:
  9546. *optoff = p ? p - *(optnext - 1) : -1;
  9547. *param_optind = optnext - optfirst + 1;
  9548. err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
  9549. sbuf[0] = c;
  9550. /*sbuf[1] = '\0'; - already is */
  9551. err |= setvarsafe(optvar, sbuf, 0);
  9552. if (err) {
  9553. *param_optind = 1;
  9554. *optoff = -1;
  9555. flush_stdout_stderr();
  9556. raise_exception(EXERROR);
  9557. }
  9558. return done;
  9559. }
  9560. /*
  9561. * The getopts builtin. Shellparam.optnext points to the next argument
  9562. * to be processed. Shellparam.optptr points to the next character to
  9563. * be processed in the current argument. If shellparam.optnext is NULL,
  9564. * then it's the first time getopts has been called.
  9565. */
  9566. static int FAST_FUNC
  9567. getoptscmd(int argc, char **argv)
  9568. {
  9569. char **optbase;
  9570. if (argc < 3)
  9571. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9572. if (argc == 3) {
  9573. optbase = shellparam.p;
  9574. if (shellparam.optind > shellparam.nparam + 1) {
  9575. shellparam.optind = 1;
  9576. shellparam.optoff = -1;
  9577. }
  9578. } else {
  9579. optbase = &argv[3];
  9580. if (shellparam.optind > argc - 2) {
  9581. shellparam.optind = 1;
  9582. shellparam.optoff = -1;
  9583. }
  9584. }
  9585. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9586. &shellparam.optoff);
  9587. }
  9588. #endif /* ASH_GETOPTS */
  9589. /* ============ Shell parser */
  9590. struct heredoc {
  9591. struct heredoc *next; /* next here document in list */
  9592. union node *here; /* redirection node */
  9593. char *eofmark; /* string indicating end of input */
  9594. smallint striptabs; /* if set, strip leading tabs */
  9595. };
  9596. static smallint tokpushback; /* last token pushed back */
  9597. static smallint quoteflag; /* set if (part of) last token was quoted */
  9598. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9599. static struct heredoc *heredoclist; /* list of here documents to read */
  9600. static char *wordtext; /* text of last word returned by readtoken */
  9601. static struct nodelist *backquotelist;
  9602. static union node *redirnode;
  9603. static struct heredoc *heredoc;
  9604. static const char *
  9605. tokname(char *buf, int tok)
  9606. {
  9607. if (tok < TSEMI)
  9608. return tokname_array[tok] + 1;
  9609. sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  9610. return buf;
  9611. }
  9612. /* raise_error_unexpected_syntax:
  9613. * Called when an unexpected token is read during the parse. The argument
  9614. * is the token that is expected, or -1 if more than one type of token can
  9615. * occur at this point.
  9616. */
  9617. static void raise_error_unexpected_syntax(int) NORETURN;
  9618. static void
  9619. raise_error_unexpected_syntax(int token)
  9620. {
  9621. char msg[64];
  9622. char buf[16];
  9623. int l;
  9624. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  9625. if (token >= 0)
  9626. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  9627. raise_error_syntax(msg);
  9628. /* NOTREACHED */
  9629. }
  9630. #define EOFMARKLEN 79
  9631. /* parsing is heavily cross-recursive, need these forward decls */
  9632. static union node *andor(void);
  9633. static union node *pipeline(void);
  9634. static union node *parse_command(void);
  9635. static void parseheredoc(void);
  9636. static int peektoken(void);
  9637. static int readtoken(void);
  9638. static union node *
  9639. list(int nlflag)
  9640. {
  9641. union node *n1, *n2, *n3;
  9642. int tok;
  9643. n1 = NULL;
  9644. for (;;) {
  9645. switch (peektoken()) {
  9646. case TNL:
  9647. if (!(nlflag & 1))
  9648. break;
  9649. parseheredoc();
  9650. return n1;
  9651. case TEOF:
  9652. if (!n1 && (nlflag & 1))
  9653. n1 = NODE_EOF;
  9654. parseheredoc();
  9655. return n1;
  9656. }
  9657. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9658. if (nlflag == 2 && tokname_array[peektoken()][0])
  9659. return n1;
  9660. nlflag |= 2;
  9661. n2 = andor();
  9662. tok = readtoken();
  9663. if (tok == TBACKGND) {
  9664. if (n2->type == NPIPE) {
  9665. n2->npipe.pipe_backgnd = 1;
  9666. } else {
  9667. if (n2->type != NREDIR) {
  9668. n3 = stzalloc(sizeof(struct nredir));
  9669. n3->nredir.n = n2;
  9670. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9671. n2 = n3;
  9672. }
  9673. n2->type = NBACKGND;
  9674. }
  9675. }
  9676. if (n1 == NULL) {
  9677. n1 = n2;
  9678. } else {
  9679. n3 = stzalloc(sizeof(struct nbinary));
  9680. n3->type = NSEMI;
  9681. n3->nbinary.ch1 = n1;
  9682. n3->nbinary.ch2 = n2;
  9683. n1 = n3;
  9684. }
  9685. switch (tok) {
  9686. case TNL:
  9687. case TEOF:
  9688. tokpushback = 1;
  9689. /* fall through */
  9690. case TBACKGND:
  9691. case TSEMI:
  9692. break;
  9693. default:
  9694. if ((nlflag & 1))
  9695. raise_error_unexpected_syntax(-1);
  9696. tokpushback = 1;
  9697. return n1;
  9698. }
  9699. }
  9700. }
  9701. static union node *
  9702. andor(void)
  9703. {
  9704. union node *n1, *n2, *n3;
  9705. int t;
  9706. n1 = pipeline();
  9707. for (;;) {
  9708. t = readtoken();
  9709. if (t == TAND) {
  9710. t = NAND;
  9711. } else if (t == TOR) {
  9712. t = NOR;
  9713. } else {
  9714. tokpushback = 1;
  9715. return n1;
  9716. }
  9717. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9718. n2 = pipeline();
  9719. n3 = stzalloc(sizeof(struct nbinary));
  9720. n3->type = t;
  9721. n3->nbinary.ch1 = n1;
  9722. n3->nbinary.ch2 = n2;
  9723. n1 = n3;
  9724. }
  9725. }
  9726. static union node *
  9727. pipeline(void)
  9728. {
  9729. union node *n1, *n2, *pipenode;
  9730. struct nodelist *lp, *prev;
  9731. int negate;
  9732. negate = 0;
  9733. TRACE(("pipeline: entered\n"));
  9734. if (readtoken() == TNOT) {
  9735. negate = !negate;
  9736. checkkwd = CHKKWD | CHKALIAS;
  9737. } else
  9738. tokpushback = 1;
  9739. n1 = parse_command();
  9740. if (readtoken() == TPIPE) {
  9741. pipenode = stzalloc(sizeof(struct npipe));
  9742. pipenode->type = NPIPE;
  9743. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9744. lp = stzalloc(sizeof(struct nodelist));
  9745. pipenode->npipe.cmdlist = lp;
  9746. lp->n = n1;
  9747. do {
  9748. prev = lp;
  9749. lp = stzalloc(sizeof(struct nodelist));
  9750. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9751. lp->n = parse_command();
  9752. prev->next = lp;
  9753. } while (readtoken() == TPIPE);
  9754. lp->next = NULL;
  9755. n1 = pipenode;
  9756. }
  9757. tokpushback = 1;
  9758. if (negate) {
  9759. n2 = stzalloc(sizeof(struct nnot));
  9760. n2->type = NNOT;
  9761. n2->nnot.com = n1;
  9762. return n2;
  9763. }
  9764. return n1;
  9765. }
  9766. static union node *
  9767. makename(void)
  9768. {
  9769. union node *n;
  9770. n = stzalloc(sizeof(struct narg));
  9771. n->type = NARG;
  9772. /*n->narg.next = NULL; - stzalloc did it */
  9773. n->narg.text = wordtext;
  9774. n->narg.backquote = backquotelist;
  9775. return n;
  9776. }
  9777. static void
  9778. fixredir(union node *n, const char *text, int err)
  9779. {
  9780. int fd;
  9781. TRACE(("Fix redir %s %d\n", text, err));
  9782. if (!err)
  9783. n->ndup.vname = NULL;
  9784. fd = bb_strtou(text, NULL, 10);
  9785. if (!errno && fd >= 0)
  9786. n->ndup.dupfd = fd;
  9787. else if (LONE_DASH(text))
  9788. n->ndup.dupfd = -1;
  9789. else {
  9790. if (err)
  9791. raise_error_syntax("bad fd number");
  9792. n->ndup.vname = makename();
  9793. }
  9794. }
  9795. /*
  9796. * Returns true if the text contains nothing to expand (no dollar signs
  9797. * or backquotes).
  9798. */
  9799. static int
  9800. noexpand(const char *text)
  9801. {
  9802. unsigned char c;
  9803. while ((c = *text++) != '\0') {
  9804. if (c == CTLQUOTEMARK)
  9805. continue;
  9806. if (c == CTLESC)
  9807. text++;
  9808. else if (SIT(c, BASESYNTAX) == CCTL)
  9809. return 0;
  9810. }
  9811. return 1;
  9812. }
  9813. static void
  9814. parsefname(void)
  9815. {
  9816. union node *n = redirnode;
  9817. if (readtoken() != TWORD)
  9818. raise_error_unexpected_syntax(-1);
  9819. if (n->type == NHERE) {
  9820. struct heredoc *here = heredoc;
  9821. struct heredoc *p;
  9822. int i;
  9823. if (quoteflag == 0)
  9824. n->type = NXHERE;
  9825. TRACE(("Here document %d\n", n->type));
  9826. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9827. raise_error_syntax("illegal eof marker for << redirection");
  9828. rmescapes(wordtext, 0);
  9829. here->eofmark = wordtext;
  9830. here->next = NULL;
  9831. if (heredoclist == NULL)
  9832. heredoclist = here;
  9833. else {
  9834. for (p = heredoclist; p->next; p = p->next)
  9835. continue;
  9836. p->next = here;
  9837. }
  9838. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9839. fixredir(n, wordtext, 0);
  9840. } else {
  9841. n->nfile.fname = makename();
  9842. }
  9843. }
  9844. static union node *
  9845. simplecmd(void)
  9846. {
  9847. union node *args, **app;
  9848. union node *n = NULL;
  9849. union node *vars, **vpp;
  9850. union node **rpp, *redir;
  9851. int savecheckkwd;
  9852. #if ENABLE_ASH_BASH_COMPAT
  9853. smallint double_brackets_flag = 0;
  9854. smallint function_flag = 0;
  9855. #endif
  9856. args = NULL;
  9857. app = &args;
  9858. vars = NULL;
  9859. vpp = &vars;
  9860. redir = NULL;
  9861. rpp = &redir;
  9862. savecheckkwd = CHKALIAS;
  9863. for (;;) {
  9864. int t;
  9865. checkkwd = savecheckkwd;
  9866. t = readtoken();
  9867. switch (t) {
  9868. #if ENABLE_ASH_BASH_COMPAT
  9869. case TFUNCTION:
  9870. if (peektoken() != TWORD)
  9871. raise_error_unexpected_syntax(TWORD);
  9872. function_flag = 1;
  9873. break;
  9874. case TAND: /* "&&" */
  9875. case TOR: /* "||" */
  9876. if (!double_brackets_flag) {
  9877. tokpushback = 1;
  9878. goto out;
  9879. }
  9880. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9881. #endif
  9882. case TWORD:
  9883. n = stzalloc(sizeof(struct narg));
  9884. n->type = NARG;
  9885. /*n->narg.next = NULL; - stzalloc did it */
  9886. n->narg.text = wordtext;
  9887. #if ENABLE_ASH_BASH_COMPAT
  9888. if (strcmp("[[", wordtext) == 0)
  9889. double_brackets_flag = 1;
  9890. else if (strcmp("]]", wordtext) == 0)
  9891. double_brackets_flag = 0;
  9892. #endif
  9893. n->narg.backquote = backquotelist;
  9894. if (savecheckkwd && isassignment(wordtext)) {
  9895. *vpp = n;
  9896. vpp = &n->narg.next;
  9897. } else {
  9898. *app = n;
  9899. app = &n->narg.next;
  9900. savecheckkwd = 0;
  9901. }
  9902. #if ENABLE_ASH_BASH_COMPAT
  9903. if (function_flag) {
  9904. checkkwd = CHKNL | CHKKWD;
  9905. switch (peektoken()) {
  9906. case TBEGIN:
  9907. case TIF:
  9908. case TCASE:
  9909. case TUNTIL:
  9910. case TWHILE:
  9911. case TFOR:
  9912. goto do_func;
  9913. case TLP:
  9914. function_flag = 0;
  9915. break;
  9916. case TWORD:
  9917. if (strcmp("[[", wordtext) == 0)
  9918. goto do_func;
  9919. /* fall through */
  9920. default:
  9921. raise_error_unexpected_syntax(-1);
  9922. }
  9923. }
  9924. #endif
  9925. break;
  9926. case TREDIR:
  9927. *rpp = n = redirnode;
  9928. rpp = &n->nfile.next;
  9929. parsefname(); /* read name of redirection file */
  9930. break;
  9931. case TLP:
  9932. IF_ASH_BASH_COMPAT(do_func:)
  9933. if (args && app == &args->narg.next
  9934. && !vars && !redir
  9935. ) {
  9936. struct builtincmd *bcmd;
  9937. const char *name;
  9938. /* We have a function */
  9939. if (IF_ASH_BASH_COMPAT(!function_flag &&) readtoken() != TRP)
  9940. raise_error_unexpected_syntax(TRP);
  9941. name = n->narg.text;
  9942. if (!goodname(name)
  9943. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9944. ) {
  9945. raise_error_syntax("bad function name");
  9946. }
  9947. n->type = NDEFUN;
  9948. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9949. n->narg.next = parse_command();
  9950. return n;
  9951. }
  9952. IF_ASH_BASH_COMPAT(function_flag = 0;)
  9953. /* fall through */
  9954. default:
  9955. tokpushback = 1;
  9956. goto out;
  9957. }
  9958. }
  9959. out:
  9960. *app = NULL;
  9961. *vpp = NULL;
  9962. *rpp = NULL;
  9963. n = stzalloc(sizeof(struct ncmd));
  9964. n->type = NCMD;
  9965. n->ncmd.args = args;
  9966. n->ncmd.assign = vars;
  9967. n->ncmd.redirect = redir;
  9968. return n;
  9969. }
  9970. static union node *
  9971. parse_command(void)
  9972. {
  9973. union node *n1, *n2;
  9974. union node *ap, **app;
  9975. union node *cp, **cpp;
  9976. union node *redir, **rpp;
  9977. union node **rpp2;
  9978. int t;
  9979. redir = NULL;
  9980. rpp2 = &redir;
  9981. switch (readtoken()) {
  9982. default:
  9983. raise_error_unexpected_syntax(-1);
  9984. /* NOTREACHED */
  9985. case TIF:
  9986. n1 = stzalloc(sizeof(struct nif));
  9987. n1->type = NIF;
  9988. n1->nif.test = list(0);
  9989. if (readtoken() != TTHEN)
  9990. raise_error_unexpected_syntax(TTHEN);
  9991. n1->nif.ifpart = list(0);
  9992. n2 = n1;
  9993. while (readtoken() == TELIF) {
  9994. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9995. n2 = n2->nif.elsepart;
  9996. n2->type = NIF;
  9997. n2->nif.test = list(0);
  9998. if (readtoken() != TTHEN)
  9999. raise_error_unexpected_syntax(TTHEN);
  10000. n2->nif.ifpart = list(0);
  10001. }
  10002. if (lasttoken == TELSE)
  10003. n2->nif.elsepart = list(0);
  10004. else {
  10005. n2->nif.elsepart = NULL;
  10006. tokpushback = 1;
  10007. }
  10008. t = TFI;
  10009. break;
  10010. case TWHILE:
  10011. case TUNTIL: {
  10012. int got;
  10013. n1 = stzalloc(sizeof(struct nbinary));
  10014. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10015. n1->nbinary.ch1 = list(0);
  10016. got = readtoken();
  10017. if (got != TDO) {
  10018. TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
  10019. got == TWORD ? wordtext : ""));
  10020. raise_error_unexpected_syntax(TDO);
  10021. }
  10022. n1->nbinary.ch2 = list(0);
  10023. t = TDONE;
  10024. break;
  10025. }
  10026. case TFOR:
  10027. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10028. raise_error_syntax("bad for loop variable");
  10029. n1 = stzalloc(sizeof(struct nfor));
  10030. n1->type = NFOR;
  10031. n1->nfor.var = wordtext;
  10032. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10033. if (readtoken() == TIN) {
  10034. app = &ap;
  10035. while (readtoken() == TWORD) {
  10036. n2 = stzalloc(sizeof(struct narg));
  10037. n2->type = NARG;
  10038. /*n2->narg.next = NULL; - stzalloc did it */
  10039. n2->narg.text = wordtext;
  10040. n2->narg.backquote = backquotelist;
  10041. *app = n2;
  10042. app = &n2->narg.next;
  10043. }
  10044. *app = NULL;
  10045. n1->nfor.args = ap;
  10046. if (lasttoken != TNL && lasttoken != TSEMI)
  10047. raise_error_unexpected_syntax(-1);
  10048. } else {
  10049. n2 = stzalloc(sizeof(struct narg));
  10050. n2->type = NARG;
  10051. /*n2->narg.next = NULL; - stzalloc did it */
  10052. n2->narg.text = (char *)dolatstr;
  10053. /*n2->narg.backquote = NULL;*/
  10054. n1->nfor.args = n2;
  10055. /*
  10056. * Newline or semicolon here is optional (but note
  10057. * that the original Bourne shell only allowed NL).
  10058. */
  10059. if (lasttoken != TSEMI)
  10060. tokpushback = 1;
  10061. }
  10062. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10063. if (readtoken() != TDO)
  10064. raise_error_unexpected_syntax(TDO);
  10065. n1->nfor.body = list(0);
  10066. t = TDONE;
  10067. break;
  10068. case TCASE:
  10069. n1 = stzalloc(sizeof(struct ncase));
  10070. n1->type = NCASE;
  10071. if (readtoken() != TWORD)
  10072. raise_error_unexpected_syntax(TWORD);
  10073. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10074. n2->type = NARG;
  10075. /*n2->narg.next = NULL; - stzalloc did it */
  10076. n2->narg.text = wordtext;
  10077. n2->narg.backquote = backquotelist;
  10078. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10079. if (readtoken() != TIN)
  10080. raise_error_unexpected_syntax(TIN);
  10081. cpp = &n1->ncase.cases;
  10082. next_case:
  10083. checkkwd = CHKNL | CHKKWD;
  10084. t = readtoken();
  10085. while (t != TESAC) {
  10086. if (lasttoken == TLP)
  10087. readtoken();
  10088. *cpp = cp = stzalloc(sizeof(struct nclist));
  10089. cp->type = NCLIST;
  10090. app = &cp->nclist.pattern;
  10091. for (;;) {
  10092. *app = ap = stzalloc(sizeof(struct narg));
  10093. ap->type = NARG;
  10094. /*ap->narg.next = NULL; - stzalloc did it */
  10095. ap->narg.text = wordtext;
  10096. ap->narg.backquote = backquotelist;
  10097. if (readtoken() != TPIPE)
  10098. break;
  10099. app = &ap->narg.next;
  10100. readtoken();
  10101. }
  10102. //ap->narg.next = NULL;
  10103. if (lasttoken != TRP)
  10104. raise_error_unexpected_syntax(TRP);
  10105. cp->nclist.body = list(2);
  10106. cpp = &cp->nclist.next;
  10107. checkkwd = CHKNL | CHKKWD;
  10108. t = readtoken();
  10109. if (t != TESAC) {
  10110. if (t != TENDCASE)
  10111. raise_error_unexpected_syntax(TENDCASE);
  10112. goto next_case;
  10113. }
  10114. }
  10115. *cpp = NULL;
  10116. goto redir;
  10117. case TLP:
  10118. n1 = stzalloc(sizeof(struct nredir));
  10119. n1->type = NSUBSHELL;
  10120. n1->nredir.n = list(0);
  10121. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10122. t = TRP;
  10123. break;
  10124. case TBEGIN:
  10125. n1 = list(0);
  10126. t = TEND;
  10127. break;
  10128. IF_ASH_BASH_COMPAT(case TFUNCTION:)
  10129. case TWORD:
  10130. case TREDIR:
  10131. tokpushback = 1;
  10132. return simplecmd();
  10133. }
  10134. if (readtoken() != t)
  10135. raise_error_unexpected_syntax(t);
  10136. redir:
  10137. /* Now check for redirection which may follow command */
  10138. checkkwd = CHKKWD | CHKALIAS;
  10139. rpp = rpp2;
  10140. while (readtoken() == TREDIR) {
  10141. *rpp = n2 = redirnode;
  10142. rpp = &n2->nfile.next;
  10143. parsefname();
  10144. }
  10145. tokpushback = 1;
  10146. *rpp = NULL;
  10147. if (redir) {
  10148. if (n1->type != NSUBSHELL) {
  10149. n2 = stzalloc(sizeof(struct nredir));
  10150. n2->type = NREDIR;
  10151. n2->nredir.n = n1;
  10152. n1 = n2;
  10153. }
  10154. n1->nredir.redirect = redir;
  10155. }
  10156. return n1;
  10157. }
  10158. #if ENABLE_ASH_BASH_COMPAT
  10159. static int decode_dollar_squote(void)
  10160. {
  10161. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10162. int c, cnt;
  10163. char *p;
  10164. char buf[4];
  10165. c = pgetc();
  10166. p = strchr(C_escapes, c);
  10167. if (p) {
  10168. buf[0] = c;
  10169. p = buf;
  10170. cnt = 3;
  10171. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10172. do {
  10173. c = pgetc();
  10174. *++p = c;
  10175. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10176. pungetc();
  10177. } else if (c == 'x') { /* \xHH */
  10178. do {
  10179. c = pgetc();
  10180. *++p = c;
  10181. } while (isxdigit(c) && --cnt);
  10182. pungetc();
  10183. if (cnt == 3) { /* \x but next char is "bad" */
  10184. c = 'x';
  10185. goto unrecognized;
  10186. }
  10187. } else { /* simple seq like \\ or \t */
  10188. p++;
  10189. }
  10190. *p = '\0';
  10191. p = buf;
  10192. c = bb_process_escape_sequence((void*)&p);
  10193. } else { /* unrecognized "\z": print both chars unless ' or " */
  10194. if (c != '\'' && c != '"') {
  10195. unrecognized:
  10196. c |= 0x100; /* "please encode \, then me" */
  10197. }
  10198. }
  10199. return c;
  10200. }
  10201. #endif
  10202. /*
  10203. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10204. * is not NULL, read a here document. In the latter case, eofmark is the
  10205. * word which marks the end of the document and striptabs is true if
  10206. * leading tabs should be stripped from the document. The argument c
  10207. * is the first character of the input token or document.
  10208. *
  10209. * Because C does not have internal subroutines, I have simulated them
  10210. * using goto's to implement the subroutine linkage. The following macros
  10211. * will run code that appears at the end of readtoken1.
  10212. */
  10213. #define CHECKEND() {goto checkend; checkend_return:;}
  10214. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10215. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10216. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10217. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10218. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10219. static int
  10220. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10221. {
  10222. /* NB: syntax parameter fits into smallint */
  10223. /* c parameter is an unsigned char or PEOF or PEOA */
  10224. char *out;
  10225. int len;
  10226. char line[EOFMARKLEN + 1];
  10227. struct nodelist *bqlist;
  10228. smallint quotef;
  10229. smallint dblquote;
  10230. smallint oldstyle;
  10231. smallint prevsyntax; /* syntax before arithmetic */
  10232. #if ENABLE_ASH_EXPAND_PRMT
  10233. smallint pssyntax; /* we are expanding a prompt string */
  10234. #endif
  10235. int varnest; /* levels of variables expansion */
  10236. int arinest; /* levels of arithmetic expansion */
  10237. int parenlevel; /* levels of parens in arithmetic */
  10238. int dqvarnest; /* levels of variables expansion within double quotes */
  10239. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  10240. startlinno = g_parsefile->linno;
  10241. bqlist = NULL;
  10242. quotef = 0;
  10243. prevsyntax = 0;
  10244. #if ENABLE_ASH_EXPAND_PRMT
  10245. pssyntax = (syntax == PSSYNTAX);
  10246. if (pssyntax)
  10247. syntax = DQSYNTAX;
  10248. #endif
  10249. dblquote = (syntax == DQSYNTAX);
  10250. varnest = 0;
  10251. arinest = 0;
  10252. parenlevel = 0;
  10253. dqvarnest = 0;
  10254. STARTSTACKSTR(out);
  10255. loop:
  10256. /* For each line, until end of word */
  10257. CHECKEND(); /* set c to PEOF if at end of here document */
  10258. for (;;) { /* until end of line or end of word */
  10259. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10260. switch (SIT(c, syntax)) {
  10261. case CNL: /* '\n' */
  10262. if (syntax == BASESYNTAX)
  10263. goto endword; /* exit outer loop */
  10264. USTPUTC(c, out);
  10265. g_parsefile->linno++;
  10266. setprompt_if(doprompt, 2);
  10267. c = pgetc();
  10268. goto loop; /* continue outer loop */
  10269. case CWORD:
  10270. USTPUTC(c, out);
  10271. break;
  10272. case CCTL:
  10273. if (eofmark == NULL || dblquote)
  10274. USTPUTC(CTLESC, out);
  10275. #if ENABLE_ASH_BASH_COMPAT
  10276. if (c == '\\' && bash_dollar_squote) {
  10277. c = decode_dollar_squote();
  10278. if (c & 0x100) {
  10279. USTPUTC('\\', out);
  10280. c = (unsigned char)c;
  10281. }
  10282. }
  10283. #endif
  10284. USTPUTC(c, out);
  10285. break;
  10286. case CBACK: /* backslash */
  10287. c = pgetc_without_PEOA();
  10288. if (c == PEOF) {
  10289. USTPUTC(CTLESC, out);
  10290. USTPUTC('\\', out);
  10291. pungetc();
  10292. } else if (c == '\n') {
  10293. setprompt_if(doprompt, 2);
  10294. } else {
  10295. #if ENABLE_ASH_EXPAND_PRMT
  10296. if (c == '$' && pssyntax) {
  10297. USTPUTC(CTLESC, out);
  10298. USTPUTC('\\', out);
  10299. }
  10300. #endif
  10301. /* Backslash is retained if we are in "str" and next char isn't special */
  10302. if (dblquote
  10303. && c != '\\'
  10304. && c != '`'
  10305. && c != '$'
  10306. && (c != '"' || eofmark != NULL)
  10307. ) {
  10308. USTPUTC('\\', out);
  10309. }
  10310. USTPUTC(CTLESC, out);
  10311. USTPUTC(c, out);
  10312. quotef = 1;
  10313. }
  10314. break;
  10315. case CSQUOTE:
  10316. syntax = SQSYNTAX;
  10317. quotemark:
  10318. if (eofmark == NULL) {
  10319. USTPUTC(CTLQUOTEMARK, out);
  10320. }
  10321. break;
  10322. case CDQUOTE:
  10323. syntax = DQSYNTAX;
  10324. dblquote = 1;
  10325. goto quotemark;
  10326. case CENDQUOTE:
  10327. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10328. if (eofmark != NULL && varnest == 0) {
  10329. USTPUTC(c, out);
  10330. } else {
  10331. if (dqvarnest == 0) {
  10332. syntax = BASESYNTAX;
  10333. dblquote = 0;
  10334. }
  10335. quotef = 1;
  10336. goto quotemark;
  10337. }
  10338. break;
  10339. case CVAR: /* '$' */
  10340. PARSESUB(); /* parse substitution */
  10341. break;
  10342. case CENDVAR: /* '}' */
  10343. if (varnest > 0) {
  10344. varnest--;
  10345. if (dqvarnest > 0) {
  10346. dqvarnest--;
  10347. }
  10348. c = CTLENDVAR;
  10349. }
  10350. USTPUTC(c, out);
  10351. break;
  10352. #if ENABLE_SH_MATH_SUPPORT
  10353. case CLP: /* '(' in arithmetic */
  10354. parenlevel++;
  10355. USTPUTC(c, out);
  10356. break;
  10357. case CRP: /* ')' in arithmetic */
  10358. if (parenlevel > 0) {
  10359. parenlevel--;
  10360. } else {
  10361. if (pgetc() == ')') {
  10362. c = CTLENDARI;
  10363. if (--arinest == 0) {
  10364. syntax = prevsyntax;
  10365. }
  10366. } else {
  10367. /*
  10368. * unbalanced parens
  10369. * (don't 2nd guess - no error)
  10370. */
  10371. pungetc();
  10372. }
  10373. }
  10374. USTPUTC(c, out);
  10375. break;
  10376. #endif
  10377. case CBQUOTE: /* '`' */
  10378. PARSEBACKQOLD();
  10379. break;
  10380. case CENDFILE:
  10381. goto endword; /* exit outer loop */
  10382. case CIGN:
  10383. break;
  10384. default:
  10385. if (varnest == 0) {
  10386. #if ENABLE_ASH_BASH_COMPAT
  10387. if (c == '&') {
  10388. if (pgetc() == '>')
  10389. c = 0x100 + '>'; /* flag &> */
  10390. pungetc();
  10391. }
  10392. #endif
  10393. goto endword; /* exit outer loop */
  10394. }
  10395. IF_ASH_ALIAS(if (c != PEOA))
  10396. USTPUTC(c, out);
  10397. }
  10398. c = pgetc_fast();
  10399. } /* for (;;) */
  10400. endword:
  10401. #if ENABLE_SH_MATH_SUPPORT
  10402. if (syntax == ARISYNTAX)
  10403. raise_error_syntax("missing '))'");
  10404. #endif
  10405. if (syntax != BASESYNTAX && eofmark == NULL)
  10406. raise_error_syntax("unterminated quoted string");
  10407. if (varnest != 0) {
  10408. startlinno = g_parsefile->linno;
  10409. /* { */
  10410. raise_error_syntax("missing '}'");
  10411. }
  10412. USTPUTC('\0', out);
  10413. len = out - (char *)stackblock();
  10414. out = stackblock();
  10415. if (eofmark == NULL) {
  10416. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10417. && quotef == 0
  10418. ) {
  10419. if (isdigit_str9(out)) {
  10420. PARSEREDIR(); /* passed as params: out, c */
  10421. lasttoken = TREDIR;
  10422. return lasttoken;
  10423. }
  10424. /* else: non-number X seen, interpret it
  10425. * as "NNNX>file" = "NNNX >file" */
  10426. }
  10427. pungetc();
  10428. }
  10429. quoteflag = quotef;
  10430. backquotelist = bqlist;
  10431. grabstackblock(len);
  10432. wordtext = out;
  10433. lasttoken = TWORD;
  10434. return lasttoken;
  10435. /* end of readtoken routine */
  10436. /*
  10437. * Check to see whether we are at the end of the here document. When this
  10438. * is called, c is set to the first character of the next input line. If
  10439. * we are at the end of the here document, this routine sets the c to PEOF.
  10440. */
  10441. checkend: {
  10442. if (eofmark) {
  10443. #if ENABLE_ASH_ALIAS
  10444. if (c == PEOA)
  10445. c = pgetc_without_PEOA();
  10446. #endif
  10447. if (striptabs) {
  10448. while (c == '\t') {
  10449. c = pgetc_without_PEOA();
  10450. }
  10451. }
  10452. if (c == *eofmark) {
  10453. if (pfgets(line, sizeof(line)) != NULL) {
  10454. char *p, *q;
  10455. p = line;
  10456. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10457. continue;
  10458. if (*p == '\n' && *q == '\0') {
  10459. c = PEOF;
  10460. g_parsefile->linno++;
  10461. needprompt = doprompt;
  10462. } else {
  10463. pushstring(line, NULL);
  10464. }
  10465. }
  10466. }
  10467. }
  10468. goto checkend_return;
  10469. }
  10470. /*
  10471. * Parse a redirection operator. The variable "out" points to a string
  10472. * specifying the fd to be redirected. The variable "c" contains the
  10473. * first character of the redirection operator.
  10474. */
  10475. parseredir: {
  10476. /* out is already checked to be a valid number or "" */
  10477. int fd = (*out == '\0' ? -1 : atoi(out));
  10478. union node *np;
  10479. np = stzalloc(sizeof(struct nfile));
  10480. if (c == '>') {
  10481. np->nfile.fd = 1;
  10482. c = pgetc();
  10483. if (c == '>')
  10484. np->type = NAPPEND;
  10485. else if (c == '|')
  10486. np->type = NCLOBBER;
  10487. else if (c == '&')
  10488. np->type = NTOFD;
  10489. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10490. else {
  10491. np->type = NTO;
  10492. pungetc();
  10493. }
  10494. }
  10495. #if ENABLE_ASH_BASH_COMPAT
  10496. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10497. np->nfile.fd = 1;
  10498. pgetc(); /* this is '>', no need to check */
  10499. np->type = NTO2;
  10500. }
  10501. #endif
  10502. else { /* c == '<' */
  10503. /*np->nfile.fd = 0; - stzalloc did it */
  10504. c = pgetc();
  10505. switch (c) {
  10506. case '<':
  10507. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10508. np = stzalloc(sizeof(struct nhere));
  10509. /*np->nfile.fd = 0; - stzalloc did it */
  10510. }
  10511. np->type = NHERE;
  10512. heredoc = stzalloc(sizeof(struct heredoc));
  10513. heredoc->here = np;
  10514. c = pgetc();
  10515. if (c == '-') {
  10516. heredoc->striptabs = 1;
  10517. } else {
  10518. /*heredoc->striptabs = 0; - stzalloc did it */
  10519. pungetc();
  10520. }
  10521. break;
  10522. case '&':
  10523. np->type = NFROMFD;
  10524. break;
  10525. case '>':
  10526. np->type = NFROMTO;
  10527. break;
  10528. default:
  10529. np->type = NFROM;
  10530. pungetc();
  10531. break;
  10532. }
  10533. }
  10534. if (fd >= 0)
  10535. np->nfile.fd = fd;
  10536. redirnode = np;
  10537. goto parseredir_return;
  10538. }
  10539. /*
  10540. * Parse a substitution. At this point, we have read the dollar sign
  10541. * and nothing else.
  10542. */
  10543. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10544. * (assuming ascii char codes, as the original implementation did) */
  10545. #define is_special(c) \
  10546. (((unsigned)(c) - 33 < 32) \
  10547. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10548. parsesub: {
  10549. unsigned char subtype;
  10550. int typeloc;
  10551. int flags;
  10552. c = pgetc();
  10553. if (c > 255 /* PEOA or PEOF */
  10554. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10555. ) {
  10556. #if ENABLE_ASH_BASH_COMPAT
  10557. if (syntax != DQSYNTAX && c == '\'')
  10558. bash_dollar_squote = 1;
  10559. else
  10560. #endif
  10561. USTPUTC('$', out);
  10562. pungetc();
  10563. } else if (c == '(') {
  10564. /* $(command) or $((arith)) */
  10565. if (pgetc() == '(') {
  10566. #if ENABLE_SH_MATH_SUPPORT
  10567. PARSEARITH();
  10568. #else
  10569. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10570. #endif
  10571. } else {
  10572. pungetc();
  10573. PARSEBACKQNEW();
  10574. }
  10575. } else {
  10576. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  10577. USTPUTC(CTLVAR, out);
  10578. typeloc = out - (char *)stackblock();
  10579. USTPUTC(VSNORMAL, out);
  10580. subtype = VSNORMAL;
  10581. if (c == '{') {
  10582. c = pgetc();
  10583. if (c == '#') {
  10584. c = pgetc();
  10585. if (c == '}')
  10586. c = '#'; /* ${#} - same as $# */
  10587. else
  10588. subtype = VSLENGTH; /* ${#VAR} */
  10589. } else {
  10590. subtype = 0;
  10591. }
  10592. }
  10593. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10594. /* $[{[#]]NAME[}] */
  10595. do {
  10596. STPUTC(c, out);
  10597. c = pgetc();
  10598. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10599. } else if (isdigit(c)) {
  10600. /* $[{[#]]NUM[}] */
  10601. do {
  10602. STPUTC(c, out);
  10603. c = pgetc();
  10604. } while (isdigit(c));
  10605. } else if (is_special(c)) {
  10606. /* $[{[#]]<specialchar>[}] */
  10607. USTPUTC(c, out);
  10608. c = pgetc();
  10609. } else {
  10610. badsub:
  10611. raise_error_syntax("bad substitution");
  10612. }
  10613. if (c != '}' && subtype == VSLENGTH) {
  10614. /* ${#VAR didn't end with } */
  10615. goto badsub;
  10616. }
  10617. STPUTC('=', out);
  10618. flags = 0;
  10619. if (subtype == 0) {
  10620. /* ${VAR...} but not $VAR or ${#VAR} */
  10621. /* c == first char after VAR */
  10622. switch (c) {
  10623. case ':':
  10624. c = pgetc();
  10625. #if ENABLE_ASH_BASH_COMPAT
  10626. if (c == ':' || c == '$' || isdigit(c)) {
  10627. //TODO: support more general format ${v:EXPR:EXPR},
  10628. // where EXPR follows $(()) rules
  10629. subtype = VSSUBSTR;
  10630. pungetc();
  10631. break; /* "goto do_pungetc" is bigger (!) */
  10632. }
  10633. #endif
  10634. flags = VSNUL;
  10635. /*FALLTHROUGH*/
  10636. default: {
  10637. static const char types[] ALIGN1 = "}-+?=";
  10638. const char *p = strchr(types, c);
  10639. if (p == NULL)
  10640. goto badsub;
  10641. subtype = p - types + VSNORMAL;
  10642. break;
  10643. }
  10644. case '%':
  10645. case '#': {
  10646. int cc = c;
  10647. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  10648. c = pgetc();
  10649. if (c != cc)
  10650. goto do_pungetc;
  10651. subtype++;
  10652. break;
  10653. }
  10654. #if ENABLE_ASH_BASH_COMPAT
  10655. case '/':
  10656. /* ${v/[/]pattern/repl} */
  10657. //TODO: encode pattern and repl separately.
  10658. // Currently ${v/$var_with_slash/repl} is horribly broken
  10659. subtype = VSREPLACE;
  10660. c = pgetc();
  10661. if (c != '/')
  10662. goto do_pungetc;
  10663. subtype++; /* VSREPLACEALL */
  10664. break;
  10665. #endif
  10666. }
  10667. } else {
  10668. do_pungetc:
  10669. pungetc();
  10670. }
  10671. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10672. if (subtype != VSNORMAL) {
  10673. varnest++;
  10674. if (dblquote) {
  10675. dqvarnest++;
  10676. }
  10677. }
  10678. }
  10679. goto parsesub_return;
  10680. }
  10681. /*
  10682. * Called to parse command substitutions. Newstyle is set if the command
  10683. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10684. * list of commands (passed by reference), and savelen is the number of
  10685. * characters on the top of the stack which must be preserved.
  10686. */
  10687. parsebackq: {
  10688. struct nodelist **nlpp;
  10689. union node *n;
  10690. char *str;
  10691. size_t savelen;
  10692. smallint saveprompt = 0;
  10693. str = NULL;
  10694. savelen = out - (char *)stackblock();
  10695. if (savelen > 0) {
  10696. str = alloca(savelen);
  10697. memcpy(str, stackblock(), savelen);
  10698. }
  10699. if (oldstyle) {
  10700. /* We must read until the closing backquote, giving special
  10701. * treatment to some slashes, and then push the string and
  10702. * reread it as input, interpreting it normally.
  10703. */
  10704. char *pout;
  10705. size_t psavelen;
  10706. char *pstr;
  10707. STARTSTACKSTR(pout);
  10708. for (;;) {
  10709. int pc;
  10710. setprompt_if(needprompt, 2);
  10711. pc = pgetc();
  10712. switch (pc) {
  10713. case '`':
  10714. goto done;
  10715. case '\\':
  10716. pc = pgetc();
  10717. if (pc == '\n') {
  10718. g_parsefile->linno++;
  10719. setprompt_if(doprompt, 2);
  10720. /*
  10721. * If eating a newline, avoid putting
  10722. * the newline into the new character
  10723. * stream (via the STPUTC after the
  10724. * switch).
  10725. */
  10726. continue;
  10727. }
  10728. if (pc != '\\' && pc != '`' && pc != '$'
  10729. && (!dblquote || pc != '"')
  10730. ) {
  10731. STPUTC('\\', pout);
  10732. }
  10733. if (pc <= 255 /* not PEOA or PEOF */) {
  10734. break;
  10735. }
  10736. /* fall through */
  10737. case PEOF:
  10738. IF_ASH_ALIAS(case PEOA:)
  10739. startlinno = g_parsefile->linno;
  10740. raise_error_syntax("EOF in backquote substitution");
  10741. case '\n':
  10742. g_parsefile->linno++;
  10743. needprompt = doprompt;
  10744. break;
  10745. default:
  10746. break;
  10747. }
  10748. STPUTC(pc, pout);
  10749. }
  10750. done:
  10751. STPUTC('\0', pout);
  10752. psavelen = pout - (char *)stackblock();
  10753. if (psavelen > 0) {
  10754. pstr = grabstackstr(pout);
  10755. setinputstring(pstr);
  10756. }
  10757. }
  10758. nlpp = &bqlist;
  10759. while (*nlpp)
  10760. nlpp = &(*nlpp)->next;
  10761. *nlpp = stzalloc(sizeof(**nlpp));
  10762. /* (*nlpp)->next = NULL; - stzalloc did it */
  10763. if (oldstyle) {
  10764. saveprompt = doprompt;
  10765. doprompt = 0;
  10766. }
  10767. n = list(2);
  10768. if (oldstyle)
  10769. doprompt = saveprompt;
  10770. else if (readtoken() != TRP)
  10771. raise_error_unexpected_syntax(TRP);
  10772. (*nlpp)->n = n;
  10773. if (oldstyle) {
  10774. /*
  10775. * Start reading from old file again, ignoring any pushed back
  10776. * tokens left from the backquote parsing
  10777. */
  10778. popfile();
  10779. tokpushback = 0;
  10780. }
  10781. while (stackblocksize() <= savelen)
  10782. growstackblock();
  10783. STARTSTACKSTR(out);
  10784. if (str) {
  10785. memcpy(out, str, savelen);
  10786. STADJUST(savelen, out);
  10787. }
  10788. USTPUTC(CTLBACKQ, out);
  10789. if (oldstyle)
  10790. goto parsebackq_oldreturn;
  10791. goto parsebackq_newreturn;
  10792. }
  10793. #if ENABLE_SH_MATH_SUPPORT
  10794. /*
  10795. * Parse an arithmetic expansion (indicate start of one and set state)
  10796. */
  10797. parsearith: {
  10798. if (++arinest == 1) {
  10799. prevsyntax = syntax;
  10800. syntax = ARISYNTAX;
  10801. }
  10802. USTPUTC(CTLARI, out);
  10803. goto parsearith_return;
  10804. }
  10805. #endif
  10806. } /* end of readtoken */
  10807. /*
  10808. * Read the next input token.
  10809. * If the token is a word, we set backquotelist to the list of cmds in
  10810. * backquotes. We set quoteflag to true if any part of the word was
  10811. * quoted.
  10812. * If the token is TREDIR, then we set redirnode to a structure containing
  10813. * the redirection.
  10814. * In all cases, the variable startlinno is set to the number of the line
  10815. * on which the token starts.
  10816. *
  10817. * [Change comment: here documents and internal procedures]
  10818. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10819. * word parsing code into a separate routine. In this case, readtoken
  10820. * doesn't need to have any internal procedures, but parseword does.
  10821. * We could also make parseoperator in essence the main routine, and
  10822. * have parseword (readtoken1?) handle both words and redirection.]
  10823. */
  10824. #define NEW_xxreadtoken
  10825. #ifdef NEW_xxreadtoken
  10826. /* singles must be first! */
  10827. static const char xxreadtoken_chars[7] ALIGN1 = {
  10828. '\n', '(', ')', /* singles */
  10829. '&', '|', ';', /* doubles */
  10830. 0
  10831. };
  10832. #define xxreadtoken_singles 3
  10833. #define xxreadtoken_doubles 3
  10834. static const char xxreadtoken_tokens[] ALIGN1 = {
  10835. TNL, TLP, TRP, /* only single occurrence allowed */
  10836. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10837. TEOF, /* corresponds to trailing nul */
  10838. TAND, TOR, TENDCASE /* if double occurrence */
  10839. };
  10840. static int
  10841. xxreadtoken(void)
  10842. {
  10843. int c;
  10844. if (tokpushback) {
  10845. tokpushback = 0;
  10846. return lasttoken;
  10847. }
  10848. setprompt_if(needprompt, 2);
  10849. startlinno = g_parsefile->linno;
  10850. for (;;) { /* until token or start of word found */
  10851. c = pgetc_fast();
  10852. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10853. continue;
  10854. if (c == '#') {
  10855. while ((c = pgetc()) != '\n' && c != PEOF)
  10856. continue;
  10857. pungetc();
  10858. } else if (c == '\\') {
  10859. if (pgetc() != '\n') {
  10860. pungetc();
  10861. break; /* return readtoken1(...) */
  10862. }
  10863. startlinno = ++g_parsefile->linno;
  10864. setprompt_if(doprompt, 2);
  10865. } else {
  10866. const char *p;
  10867. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10868. if (c != PEOF) {
  10869. if (c == '\n') {
  10870. g_parsefile->linno++;
  10871. needprompt = doprompt;
  10872. }
  10873. p = strchr(xxreadtoken_chars, c);
  10874. if (p == NULL)
  10875. break; /* return readtoken1(...) */
  10876. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10877. int cc = pgetc();
  10878. if (cc == c) { /* double occurrence? */
  10879. p += xxreadtoken_doubles + 1;
  10880. } else {
  10881. pungetc();
  10882. #if ENABLE_ASH_BASH_COMPAT
  10883. if (c == '&' && cc == '>') /* &> */
  10884. break; /* return readtoken1(...) */
  10885. #endif
  10886. }
  10887. }
  10888. }
  10889. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10890. return lasttoken;
  10891. }
  10892. } /* for (;;) */
  10893. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10894. }
  10895. #else /* old xxreadtoken */
  10896. #define RETURN(token) return lasttoken = token
  10897. static int
  10898. xxreadtoken(void)
  10899. {
  10900. int c;
  10901. if (tokpushback) {
  10902. tokpushback = 0;
  10903. return lasttoken;
  10904. }
  10905. setprompt_if(needprompt, 2);
  10906. startlinno = g_parsefile->linno;
  10907. for (;;) { /* until token or start of word found */
  10908. c = pgetc_fast();
  10909. switch (c) {
  10910. case ' ': case '\t':
  10911. IF_ASH_ALIAS(case PEOA:)
  10912. continue;
  10913. case '#':
  10914. while ((c = pgetc()) != '\n' && c != PEOF)
  10915. continue;
  10916. pungetc();
  10917. continue;
  10918. case '\\':
  10919. if (pgetc() == '\n') {
  10920. startlinno = ++g_parsefile->linno;
  10921. setprompt_if(doprompt, 2);
  10922. continue;
  10923. }
  10924. pungetc();
  10925. goto breakloop;
  10926. case '\n':
  10927. g_parsefile->linno++;
  10928. needprompt = doprompt;
  10929. RETURN(TNL);
  10930. case PEOF:
  10931. RETURN(TEOF);
  10932. case '&':
  10933. if (pgetc() == '&')
  10934. RETURN(TAND);
  10935. pungetc();
  10936. RETURN(TBACKGND);
  10937. case '|':
  10938. if (pgetc() == '|')
  10939. RETURN(TOR);
  10940. pungetc();
  10941. RETURN(TPIPE);
  10942. case ';':
  10943. if (pgetc() == ';')
  10944. RETURN(TENDCASE);
  10945. pungetc();
  10946. RETURN(TSEMI);
  10947. case '(':
  10948. RETURN(TLP);
  10949. case ')':
  10950. RETURN(TRP);
  10951. default:
  10952. goto breakloop;
  10953. }
  10954. }
  10955. breakloop:
  10956. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10957. #undef RETURN
  10958. }
  10959. #endif /* old xxreadtoken */
  10960. static int
  10961. readtoken(void)
  10962. {
  10963. int t;
  10964. int kwd = checkkwd;
  10965. #if DEBUG
  10966. smallint alreadyseen = tokpushback;
  10967. #endif
  10968. #if ENABLE_ASH_ALIAS
  10969. top:
  10970. #endif
  10971. t = xxreadtoken();
  10972. /*
  10973. * eat newlines
  10974. */
  10975. if (kwd & CHKNL) {
  10976. while (t == TNL) {
  10977. parseheredoc();
  10978. t = xxreadtoken();
  10979. }
  10980. }
  10981. if (t != TWORD || quoteflag) {
  10982. goto out;
  10983. }
  10984. /*
  10985. * check for keywords
  10986. */
  10987. if (kwd & CHKKWD) {
  10988. const char *const *pp;
  10989. pp = findkwd(wordtext);
  10990. if (pp) {
  10991. lasttoken = t = pp - tokname_array;
  10992. TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
  10993. goto out;
  10994. }
  10995. }
  10996. if (checkkwd & CHKALIAS) {
  10997. #if ENABLE_ASH_ALIAS
  10998. struct alias *ap;
  10999. ap = lookupalias(wordtext, 1);
  11000. if (ap != NULL) {
  11001. if (*ap->val) {
  11002. pushstring(ap->val, ap);
  11003. }
  11004. goto top;
  11005. }
  11006. #endif
  11007. }
  11008. out:
  11009. checkkwd = 0;
  11010. #if DEBUG
  11011. if (!alreadyseen)
  11012. TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11013. else
  11014. TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  11015. #endif
  11016. return t;
  11017. }
  11018. static int
  11019. peektoken(void)
  11020. {
  11021. int t;
  11022. t = readtoken();
  11023. tokpushback = 1;
  11024. return t;
  11025. }
  11026. /*
  11027. * Read and parse a command. Returns NODE_EOF on end of file.
  11028. * (NULL is a valid parse tree indicating a blank line.)
  11029. */
  11030. static union node *
  11031. parsecmd(int interact)
  11032. {
  11033. tokpushback = 0;
  11034. checkkwd = 0;
  11035. heredoclist = 0;
  11036. doprompt = interact;
  11037. setprompt_if(doprompt, doprompt);
  11038. needprompt = 0;
  11039. return list(1);
  11040. }
  11041. /*
  11042. * Input any here documents.
  11043. */
  11044. static void
  11045. parseheredoc(void)
  11046. {
  11047. struct heredoc *here;
  11048. union node *n;
  11049. here = heredoclist;
  11050. heredoclist = NULL;
  11051. while (here) {
  11052. setprompt_if(needprompt, 2);
  11053. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11054. here->eofmark, here->striptabs);
  11055. n = stzalloc(sizeof(struct narg));
  11056. n->narg.type = NARG;
  11057. /*n->narg.next = NULL; - stzalloc did it */
  11058. n->narg.text = wordtext;
  11059. n->narg.backquote = backquotelist;
  11060. here->here->nhere.doc = n;
  11061. here = here->next;
  11062. }
  11063. }
  11064. /*
  11065. * called by editline -- any expansions to the prompt should be added here.
  11066. */
  11067. #if ENABLE_ASH_EXPAND_PRMT
  11068. static const char *
  11069. expandstr(const char *ps)
  11070. {
  11071. union node n;
  11072. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  11073. * and token processing _can_ alter it (delete NULs etc). */
  11074. setinputstring((char *)ps);
  11075. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  11076. popfile();
  11077. n.narg.type = NARG;
  11078. n.narg.next = NULL;
  11079. n.narg.text = wordtext;
  11080. n.narg.backquote = backquotelist;
  11081. expandarg(&n, NULL, EXP_QUOTED);
  11082. return stackblock();
  11083. }
  11084. #endif
  11085. /*
  11086. * Execute a command or commands contained in a string.
  11087. */
  11088. static int
  11089. evalstring(char *s, int mask)
  11090. {
  11091. union node *n;
  11092. struct stackmark smark;
  11093. int skip;
  11094. setinputstring(s);
  11095. setstackmark(&smark);
  11096. skip = 0;
  11097. while ((n = parsecmd(0)) != NODE_EOF) {
  11098. evaltree(n, 0);
  11099. popstackmark(&smark);
  11100. skip = evalskip;
  11101. if (skip)
  11102. break;
  11103. }
  11104. popfile();
  11105. skip &= mask;
  11106. evalskip = skip;
  11107. return skip;
  11108. }
  11109. /*
  11110. * The eval command.
  11111. */
  11112. static int FAST_FUNC
  11113. evalcmd(int argc UNUSED_PARAM, char **argv)
  11114. {
  11115. char *p;
  11116. char *concat;
  11117. if (argv[1]) {
  11118. p = argv[1];
  11119. argv += 2;
  11120. if (argv[0]) {
  11121. STARTSTACKSTR(concat);
  11122. for (;;) {
  11123. concat = stack_putstr(p, concat);
  11124. p = *argv++;
  11125. if (p == NULL)
  11126. break;
  11127. STPUTC(' ', concat);
  11128. }
  11129. STPUTC('\0', concat);
  11130. p = grabstackstr(concat);
  11131. }
  11132. evalstring(p, ~SKIPEVAL);
  11133. }
  11134. return exitstatus;
  11135. }
  11136. /*
  11137. * Read and execute commands.
  11138. * "Top" is nonzero for the top level command loop;
  11139. * it turns on prompting if the shell is interactive.
  11140. */
  11141. static int
  11142. cmdloop(int top)
  11143. {
  11144. union node *n;
  11145. struct stackmark smark;
  11146. int inter;
  11147. int numeof = 0;
  11148. TRACE(("cmdloop(%d) called\n", top));
  11149. for (;;) {
  11150. int skip;
  11151. setstackmark(&smark);
  11152. #if JOBS
  11153. if (doing_jobctl)
  11154. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11155. #endif
  11156. inter = 0;
  11157. if (iflag && top) {
  11158. inter++;
  11159. chkmail();
  11160. }
  11161. n = parsecmd(inter);
  11162. #if DEBUG
  11163. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11164. showtree(n);
  11165. #endif
  11166. if (n == NODE_EOF) {
  11167. if (!top || numeof >= 50)
  11168. break;
  11169. if (!stoppedjobs()) {
  11170. if (!Iflag)
  11171. break;
  11172. out2str("\nUse \"exit\" to leave shell.\n");
  11173. }
  11174. numeof++;
  11175. } else if (nflag == 0) {
  11176. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11177. job_warning >>= 1;
  11178. numeof = 0;
  11179. evaltree(n, 0);
  11180. }
  11181. popstackmark(&smark);
  11182. skip = evalskip;
  11183. if (skip) {
  11184. evalskip = 0;
  11185. return skip & SKIPEVAL;
  11186. }
  11187. }
  11188. return 0;
  11189. }
  11190. /*
  11191. * Take commands from a file. To be compatible we should do a path
  11192. * search for the file, which is necessary to find sub-commands.
  11193. */
  11194. static char *
  11195. find_dot_file(char *name)
  11196. {
  11197. char *fullname;
  11198. const char *path = pathval();
  11199. struct stat statb;
  11200. /* don't try this for absolute or relative paths */
  11201. if (strchr(name, '/'))
  11202. return name;
  11203. /* IIRC standards do not say whether . is to be searched.
  11204. * And it is even smaller this way, making it unconditional for now:
  11205. */
  11206. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  11207. fullname = name;
  11208. goto try_cur_dir;
  11209. }
  11210. while ((fullname = path_advance(&path, name)) != NULL) {
  11211. try_cur_dir:
  11212. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11213. /*
  11214. * Don't bother freeing here, since it will
  11215. * be freed by the caller.
  11216. */
  11217. return fullname;
  11218. }
  11219. if (fullname != name)
  11220. stunalloc(fullname);
  11221. }
  11222. /* not found in the PATH */
  11223. ash_msg_and_raise_error("%s: not found", name);
  11224. /* NOTREACHED */
  11225. }
  11226. static int FAST_FUNC
  11227. dotcmd(int argc, char **argv)
  11228. {
  11229. char *fullname;
  11230. struct strlist *sp;
  11231. volatile struct shparam saveparam;
  11232. for (sp = cmdenviron; sp; sp = sp->next)
  11233. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11234. if (!argv[1]) {
  11235. /* bash says: "bash: .: filename argument required" */
  11236. return 2; /* bash compat */
  11237. }
  11238. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11239. exitstatus = 0;
  11240. /* This aborts if file isn't found, which is POSIXly correct.
  11241. * bash returns exitcode 1 instead.
  11242. */
  11243. fullname = find_dot_file(argv[1]);
  11244. argv += 2;
  11245. argc -= 2;
  11246. if (argc) { /* argc > 0, argv[0] != NULL */
  11247. saveparam = shellparam;
  11248. shellparam.malloced = 0;
  11249. shellparam.nparam = argc;
  11250. shellparam.p = argv;
  11251. };
  11252. /* This aborts if file can't be opened, which is POSIXly correct.
  11253. * bash returns exitcode 1 instead.
  11254. */
  11255. setinputfile(fullname, INPUT_PUSH_FILE);
  11256. commandname = fullname;
  11257. cmdloop(0);
  11258. popfile();
  11259. if (argc) {
  11260. freeparam(&shellparam);
  11261. shellparam = saveparam;
  11262. };
  11263. return exitstatus;
  11264. }
  11265. static int FAST_FUNC
  11266. exitcmd(int argc UNUSED_PARAM, char **argv)
  11267. {
  11268. if (stoppedjobs())
  11269. return 0;
  11270. if (argv[1])
  11271. exitstatus = number(argv[1]);
  11272. raise_exception(EXEXIT);
  11273. /* NOTREACHED */
  11274. }
  11275. /*
  11276. * Read a file containing shell functions.
  11277. */
  11278. static void
  11279. readcmdfile(char *name)
  11280. {
  11281. setinputfile(name, INPUT_PUSH_FILE);
  11282. cmdloop(0);
  11283. popfile();
  11284. }
  11285. /* ============ find_command inplementation */
  11286. /*
  11287. * Resolve a command name. If you change this routine, you may have to
  11288. * change the shellexec routine as well.
  11289. */
  11290. static void
  11291. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11292. {
  11293. struct tblentry *cmdp;
  11294. int idx;
  11295. int prev;
  11296. char *fullname;
  11297. struct stat statb;
  11298. int e;
  11299. int updatetbl;
  11300. struct builtincmd *bcmd;
  11301. /* If name contains a slash, don't use PATH or hash table */
  11302. if (strchr(name, '/') != NULL) {
  11303. entry->u.index = -1;
  11304. if (act & DO_ABS) {
  11305. while (stat(name, &statb) < 0) {
  11306. #ifdef SYSV
  11307. if (errno == EINTR)
  11308. continue;
  11309. #endif
  11310. entry->cmdtype = CMDUNKNOWN;
  11311. return;
  11312. }
  11313. }
  11314. entry->cmdtype = CMDNORMAL;
  11315. return;
  11316. }
  11317. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11318. updatetbl = (path == pathval());
  11319. if (!updatetbl) {
  11320. act |= DO_ALTPATH;
  11321. if (strstr(path, "%builtin") != NULL)
  11322. act |= DO_ALTBLTIN;
  11323. }
  11324. /* If name is in the table, check answer will be ok */
  11325. cmdp = cmdlookup(name, 0);
  11326. if (cmdp != NULL) {
  11327. int bit;
  11328. switch (cmdp->cmdtype) {
  11329. default:
  11330. #if DEBUG
  11331. abort();
  11332. #endif
  11333. case CMDNORMAL:
  11334. bit = DO_ALTPATH;
  11335. break;
  11336. case CMDFUNCTION:
  11337. bit = DO_NOFUNC;
  11338. break;
  11339. case CMDBUILTIN:
  11340. bit = DO_ALTBLTIN;
  11341. break;
  11342. }
  11343. if (act & bit) {
  11344. updatetbl = 0;
  11345. cmdp = NULL;
  11346. } else if (cmdp->rehash == 0)
  11347. /* if not invalidated by cd, we're done */
  11348. goto success;
  11349. }
  11350. /* If %builtin not in path, check for builtin next */
  11351. bcmd = find_builtin(name);
  11352. if (bcmd) {
  11353. if (IS_BUILTIN_REGULAR(bcmd))
  11354. goto builtin_success;
  11355. if (act & DO_ALTPATH) {
  11356. if (!(act & DO_ALTBLTIN))
  11357. goto builtin_success;
  11358. } else if (builtinloc <= 0) {
  11359. goto builtin_success;
  11360. }
  11361. }
  11362. #if ENABLE_FEATURE_SH_STANDALONE
  11363. {
  11364. int applet_no = find_applet_by_name(name);
  11365. if (applet_no >= 0) {
  11366. entry->cmdtype = CMDNORMAL;
  11367. entry->u.index = -2 - applet_no;
  11368. return;
  11369. }
  11370. }
  11371. #endif
  11372. /* We have to search path. */
  11373. prev = -1; /* where to start */
  11374. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11375. if (cmdp->cmdtype == CMDBUILTIN)
  11376. prev = builtinloc;
  11377. else
  11378. prev = cmdp->param.index;
  11379. }
  11380. e = ENOENT;
  11381. idx = -1;
  11382. loop:
  11383. while ((fullname = path_advance(&path, name)) != NULL) {
  11384. stunalloc(fullname);
  11385. /* NB: code below will still use fullname
  11386. * despite it being "unallocated" */
  11387. idx++;
  11388. if (pathopt) {
  11389. if (prefix(pathopt, "builtin")) {
  11390. if (bcmd)
  11391. goto builtin_success;
  11392. continue;
  11393. }
  11394. if ((act & DO_NOFUNC)
  11395. || !prefix(pathopt, "func")
  11396. ) { /* ignore unimplemented options */
  11397. continue;
  11398. }
  11399. }
  11400. /* if rehash, don't redo absolute path names */
  11401. if (fullname[0] == '/' && idx <= prev) {
  11402. if (idx < prev)
  11403. continue;
  11404. TRACE(("searchexec \"%s\": no change\n", name));
  11405. goto success;
  11406. }
  11407. while (stat(fullname, &statb) < 0) {
  11408. #ifdef SYSV
  11409. if (errno == EINTR)
  11410. continue;
  11411. #endif
  11412. if (errno != ENOENT && errno != ENOTDIR)
  11413. e = errno;
  11414. goto loop;
  11415. }
  11416. e = EACCES; /* if we fail, this will be the error */
  11417. if (!S_ISREG(statb.st_mode))
  11418. continue;
  11419. if (pathopt) { /* this is a %func directory */
  11420. stalloc(strlen(fullname) + 1);
  11421. /* NB: stalloc will return space pointed by fullname
  11422. * (because we don't have any intervening allocations
  11423. * between stunalloc above and this stalloc) */
  11424. readcmdfile(fullname);
  11425. cmdp = cmdlookup(name, 0);
  11426. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11427. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11428. stunalloc(fullname);
  11429. goto success;
  11430. }
  11431. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11432. if (!updatetbl) {
  11433. entry->cmdtype = CMDNORMAL;
  11434. entry->u.index = idx;
  11435. return;
  11436. }
  11437. INT_OFF;
  11438. cmdp = cmdlookup(name, 1);
  11439. cmdp->cmdtype = CMDNORMAL;
  11440. cmdp->param.index = idx;
  11441. INT_ON;
  11442. goto success;
  11443. }
  11444. /* We failed. If there was an entry for this command, delete it */
  11445. if (cmdp && updatetbl)
  11446. delete_cmd_entry();
  11447. if (act & DO_ERR)
  11448. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11449. entry->cmdtype = CMDUNKNOWN;
  11450. return;
  11451. builtin_success:
  11452. if (!updatetbl) {
  11453. entry->cmdtype = CMDBUILTIN;
  11454. entry->u.cmd = bcmd;
  11455. return;
  11456. }
  11457. INT_OFF;
  11458. cmdp = cmdlookup(name, 1);
  11459. cmdp->cmdtype = CMDBUILTIN;
  11460. cmdp->param.cmd = bcmd;
  11461. INT_ON;
  11462. success:
  11463. cmdp->rehash = 0;
  11464. entry->cmdtype = cmdp->cmdtype;
  11465. entry->u = cmdp->param;
  11466. }
  11467. /* ============ trap.c */
  11468. /*
  11469. * The trap builtin.
  11470. */
  11471. static int FAST_FUNC
  11472. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11473. {
  11474. char *action;
  11475. char **ap;
  11476. int signo, exitcode;
  11477. nextopt(nullstr);
  11478. ap = argptr;
  11479. if (!*ap) {
  11480. for (signo = 0; signo < NSIG; signo++) {
  11481. char *tr = trap_ptr[signo];
  11482. if (tr) {
  11483. /* note: bash adds "SIG", but only if invoked
  11484. * as "bash". If called as "sh", or if set -o posix,
  11485. * then it prints short signal names.
  11486. * We are printing short names: */
  11487. out1fmt("trap -- %s %s\n",
  11488. single_quote(tr),
  11489. get_signame(signo));
  11490. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11491. * In this case, we will exit very soon, no need to free(). */
  11492. /* if (trap_ptr != trap && tp[0]) */
  11493. /* free(tr); */
  11494. }
  11495. }
  11496. /*
  11497. if (trap_ptr != trap) {
  11498. free(trap_ptr);
  11499. trap_ptr = trap;
  11500. }
  11501. */
  11502. return 0;
  11503. }
  11504. action = NULL;
  11505. if (ap[1])
  11506. action = *ap++;
  11507. exitcode = 0;
  11508. while (*ap) {
  11509. signo = get_signum(*ap);
  11510. if (signo < 0) {
  11511. /* Mimic bash message exactly */
  11512. ash_msg("%s: invalid signal specification", *ap);
  11513. exitcode = 1;
  11514. goto next;
  11515. }
  11516. INT_OFF;
  11517. if (action) {
  11518. if (LONE_DASH(action))
  11519. action = NULL;
  11520. else
  11521. action = ckstrdup(action);
  11522. }
  11523. free(trap[signo]);
  11524. if (action)
  11525. may_have_traps = 1;
  11526. trap[signo] = action;
  11527. if (signo != 0)
  11528. setsignal(signo);
  11529. INT_ON;
  11530. next:
  11531. ap++;
  11532. }
  11533. return exitcode;
  11534. }
  11535. /* ============ Builtins */
  11536. #if ENABLE_ASH_HELP
  11537. static int FAST_FUNC
  11538. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11539. {
  11540. unsigned col;
  11541. unsigned i;
  11542. out1fmt(
  11543. "Built-in commands:\n"
  11544. "------------------\n");
  11545. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11546. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11547. builtintab[i].name + 1);
  11548. if (col > 60) {
  11549. out1fmt("\n");
  11550. col = 0;
  11551. }
  11552. }
  11553. # if ENABLE_FEATURE_SH_STANDALONE
  11554. {
  11555. const char *a = applet_names;
  11556. while (*a) {
  11557. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11558. if (col > 60) {
  11559. out1fmt("\n");
  11560. col = 0;
  11561. }
  11562. while (*a++ != '\0')
  11563. continue;
  11564. }
  11565. }
  11566. # endif
  11567. out1fmt("\n\n");
  11568. return EXIT_SUCCESS;
  11569. }
  11570. #endif
  11571. #if MAX_HISTORY
  11572. static int FAST_FUNC
  11573. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11574. {
  11575. show_history(line_input_state);
  11576. return EXIT_SUCCESS;
  11577. }
  11578. #endif
  11579. /*
  11580. * The export and readonly commands.
  11581. */
  11582. static int FAST_FUNC
  11583. exportcmd(int argc UNUSED_PARAM, char **argv)
  11584. {
  11585. struct var *vp;
  11586. char *name;
  11587. const char *p;
  11588. char **aptr;
  11589. char opt;
  11590. int flag;
  11591. int flag_off;
  11592. /* "readonly" in bash accepts, but ignores -n.
  11593. * We do the same: it saves a conditional in nextopt's param.
  11594. */
  11595. flag_off = 0;
  11596. while ((opt = nextopt("np")) != '\0') {
  11597. if (opt == 'n')
  11598. flag_off = VEXPORT;
  11599. }
  11600. flag = VEXPORT;
  11601. if (argv[0][0] == 'r') {
  11602. flag = VREADONLY;
  11603. flag_off = 0; /* readonly ignores -n */
  11604. }
  11605. flag_off = ~flag_off;
  11606. /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
  11607. {
  11608. aptr = argptr;
  11609. name = *aptr;
  11610. if (name) {
  11611. do {
  11612. p = strchr(name, '=');
  11613. if (p != NULL) {
  11614. p++;
  11615. } else {
  11616. vp = *findvar(hashvar(name), name);
  11617. if (vp) {
  11618. vp->flags = ((vp->flags | flag) & flag_off);
  11619. continue;
  11620. }
  11621. }
  11622. setvar(name, p, (flag & flag_off));
  11623. } while ((name = *++aptr) != NULL);
  11624. return 0;
  11625. }
  11626. }
  11627. /* No arguments. Show the list of exported or readonly vars.
  11628. * -n is ignored.
  11629. */
  11630. showvars(argv[0], flag, 0);
  11631. return 0;
  11632. }
  11633. /*
  11634. * Delete a function if it exists.
  11635. */
  11636. static void
  11637. unsetfunc(const char *name)
  11638. {
  11639. struct tblentry *cmdp;
  11640. cmdp = cmdlookup(name, 0);
  11641. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  11642. delete_cmd_entry();
  11643. }
  11644. /*
  11645. * The unset builtin command. We unset the function before we unset the
  11646. * variable to allow a function to be unset when there is a readonly variable
  11647. * with the same name.
  11648. */
  11649. static int FAST_FUNC
  11650. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11651. {
  11652. char **ap;
  11653. int i;
  11654. int flag = 0;
  11655. int ret = 0;
  11656. while ((i = nextopt("vf")) != 0) {
  11657. flag = i;
  11658. }
  11659. for (ap = argptr; *ap; ap++) {
  11660. if (flag != 'f') {
  11661. i = unsetvar(*ap);
  11662. ret |= i;
  11663. if (!(i & 2))
  11664. continue;
  11665. }
  11666. if (flag != 'v')
  11667. unsetfunc(*ap);
  11668. }
  11669. return ret & 1;
  11670. }
  11671. static const unsigned char timescmd_str[] ALIGN1 = {
  11672. ' ', offsetof(struct tms, tms_utime),
  11673. '\n', offsetof(struct tms, tms_stime),
  11674. ' ', offsetof(struct tms, tms_cutime),
  11675. '\n', offsetof(struct tms, tms_cstime),
  11676. 0
  11677. };
  11678. static int FAST_FUNC
  11679. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11680. {
  11681. unsigned long clk_tck, s, t;
  11682. const unsigned char *p;
  11683. struct tms buf;
  11684. clk_tck = bb_clk_tck();
  11685. times(&buf);
  11686. p = timescmd_str;
  11687. do {
  11688. t = *(clock_t *)(((char *) &buf) + p[1]);
  11689. s = t / clk_tck;
  11690. t = t % clk_tck;
  11691. out1fmt("%lum%lu.%03lus%c",
  11692. s / 60, s % 60,
  11693. (t * 1000) / clk_tck,
  11694. p[0]);
  11695. p += 2;
  11696. } while (*p);
  11697. return 0;
  11698. }
  11699. #if ENABLE_SH_MATH_SUPPORT
  11700. /*
  11701. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  11702. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11703. *
  11704. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11705. */
  11706. static int FAST_FUNC
  11707. letcmd(int argc UNUSED_PARAM, char **argv)
  11708. {
  11709. arith_t i;
  11710. argv++;
  11711. if (!*argv)
  11712. ash_msg_and_raise_error("expression expected");
  11713. do {
  11714. i = ash_arith(*argv);
  11715. } while (*++argv);
  11716. return !i;
  11717. }
  11718. #endif
  11719. /*
  11720. * The read builtin. Options:
  11721. * -r Do not interpret '\' specially
  11722. * -s Turn off echo (tty only)
  11723. * -n NCHARS Read NCHARS max
  11724. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11725. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11726. * -u FD Read from given FD instead of fd 0
  11727. * This uses unbuffered input, which may be avoidable in some cases.
  11728. * TODO: bash also has:
  11729. * -a ARRAY Read into array[0],[1],etc
  11730. * -d DELIM End on DELIM char, not newline
  11731. * -e Use line editing (tty only)
  11732. */
  11733. static int FAST_FUNC
  11734. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11735. {
  11736. char *opt_n = NULL;
  11737. char *opt_p = NULL;
  11738. char *opt_t = NULL;
  11739. char *opt_u = NULL;
  11740. int read_flags = 0;
  11741. const char *r;
  11742. int i;
  11743. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11744. switch (i) {
  11745. case 'p':
  11746. opt_p = optionarg;
  11747. break;
  11748. case 'n':
  11749. opt_n = optionarg;
  11750. break;
  11751. case 's':
  11752. read_flags |= BUILTIN_READ_SILENT;
  11753. break;
  11754. case 't':
  11755. opt_t = optionarg;
  11756. break;
  11757. case 'r':
  11758. read_flags |= BUILTIN_READ_RAW;
  11759. break;
  11760. case 'u':
  11761. opt_u = optionarg;
  11762. break;
  11763. default:
  11764. break;
  11765. }
  11766. }
  11767. /* "read -s" needs to save/restore termios, can't allow ^C
  11768. * to jump out of it.
  11769. */
  11770. INT_OFF;
  11771. r = shell_builtin_read(setvar0,
  11772. argptr,
  11773. bltinlookup("IFS"), /* can be NULL */
  11774. read_flags,
  11775. opt_n,
  11776. opt_p,
  11777. opt_t,
  11778. opt_u
  11779. );
  11780. INT_ON;
  11781. if ((uintptr_t)r > 1)
  11782. ash_msg_and_raise_error(r);
  11783. return (uintptr_t)r;
  11784. }
  11785. static int FAST_FUNC
  11786. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11787. {
  11788. static const char permuser[3] ALIGN1 = "ogu";
  11789. mode_t mask;
  11790. int symbolic_mode = 0;
  11791. while (nextopt("S") != '\0') {
  11792. symbolic_mode = 1;
  11793. }
  11794. INT_OFF;
  11795. mask = umask(0);
  11796. umask(mask);
  11797. INT_ON;
  11798. if (*argptr == NULL) {
  11799. if (symbolic_mode) {
  11800. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  11801. char *p = buf;
  11802. int i;
  11803. i = 2;
  11804. for (;;) {
  11805. *p++ = ',';
  11806. *p++ = permuser[i];
  11807. *p++ = '=';
  11808. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  11809. if (!(mask & 0400)) *p++ = 'r';
  11810. if (!(mask & 0200)) *p++ = 'w';
  11811. if (!(mask & 0100)) *p++ = 'x';
  11812. mask <<= 3;
  11813. if (--i < 0)
  11814. break;
  11815. }
  11816. *p = '\0';
  11817. puts(buf + 1);
  11818. } else {
  11819. out1fmt("%04o\n", mask);
  11820. }
  11821. } else {
  11822. char *modestr = *argptr;
  11823. /* numeric umasks are taken as-is */
  11824. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  11825. if (!isdigit(modestr[0]))
  11826. mask ^= 0777;
  11827. mask = bb_parse_mode(modestr, mask);
  11828. if ((unsigned)mask > 0777) {
  11829. ash_msg_and_raise_error("illegal mode: %s", modestr);
  11830. }
  11831. if (!isdigit(modestr[0]))
  11832. mask ^= 0777;
  11833. umask(mask);
  11834. }
  11835. return 0;
  11836. }
  11837. static int FAST_FUNC
  11838. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  11839. {
  11840. return shell_builtin_ulimit(argv);
  11841. }
  11842. /* ============ main() and helpers */
  11843. /*
  11844. * Called to exit the shell.
  11845. */
  11846. static void
  11847. exitshell(void)
  11848. {
  11849. struct jmploc loc;
  11850. char *p;
  11851. int status;
  11852. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  11853. save_history(line_input_state);
  11854. #endif
  11855. status = exitstatus;
  11856. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11857. if (setjmp(loc.loc)) {
  11858. if (exception_type == EXEXIT)
  11859. /* dash bug: it just does _exit(exitstatus) here
  11860. * but we have to do setjobctl(0) first!
  11861. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11862. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11863. status = exitstatus;
  11864. goto out;
  11865. }
  11866. exception_handler = &loc;
  11867. p = trap[0];
  11868. if (p) {
  11869. trap[0] = NULL;
  11870. evalstring(p, 0);
  11871. free(p);
  11872. }
  11873. flush_stdout_stderr();
  11874. out:
  11875. setjobctl(0);
  11876. _exit(status);
  11877. /* NOTREACHED */
  11878. }
  11879. static void
  11880. init(void)
  11881. {
  11882. /* from input.c: */
  11883. /* we will never free this */
  11884. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  11885. /* from trap.c: */
  11886. signal(SIGCHLD, SIG_DFL);
  11887. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11888. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11889. */
  11890. signal(SIGHUP, SIG_DFL);
  11891. /* from var.c: */
  11892. {
  11893. char **envp;
  11894. const char *p;
  11895. struct stat st1, st2;
  11896. initvar();
  11897. for (envp = environ; envp && *envp; envp++) {
  11898. if (strchr(*envp, '=')) {
  11899. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11900. }
  11901. }
  11902. setvar0("PPID", utoa(getppid()));
  11903. #if ENABLE_ASH_BASH_COMPAT
  11904. p = lookupvar("SHLVL");
  11905. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  11906. if (!lookupvar("HOSTNAME")) {
  11907. struct utsname uts;
  11908. uname(&uts);
  11909. setvar0("HOSTNAME", uts.nodename);
  11910. }
  11911. #endif
  11912. p = lookupvar("PWD");
  11913. if (p) {
  11914. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11915. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  11916. ) {
  11917. p = '\0';
  11918. }
  11919. }
  11920. setpwd(p, 0);
  11921. }
  11922. }
  11923. //usage:#define ash_trivial_usage
  11924. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  11925. //usage:#define ash_full_usage "\n\n"
  11926. //usage: "Unix shell interpreter"
  11927. //usage:#if ENABLE_FEATURE_SH_IS_ASH
  11928. //usage:# define sh_trivial_usage ash_trivial_usage
  11929. //usage:# define sh_full_usage ash_full_usage
  11930. //usage:#endif
  11931. //usage:#if ENABLE_FEATURE_BASH_IS_ASH
  11932. //usage:# define bash_trivial_usage ash_trivial_usage
  11933. //usage:# define bash_full_usage ash_full_usage
  11934. //usage:#endif
  11935. /*
  11936. * Process the shell command line arguments.
  11937. */
  11938. static void
  11939. procargs(char **argv)
  11940. {
  11941. int i;
  11942. const char *xminusc;
  11943. char **xargv;
  11944. xargv = argv;
  11945. arg0 = xargv[0];
  11946. /* if (xargv[0]) - mmm, this is always true! */
  11947. xargv++;
  11948. for (i = 0; i < NOPTS; i++)
  11949. optlist[i] = 2;
  11950. argptr = xargv;
  11951. if (options(/*cmdline:*/ 1)) {
  11952. /* it already printed err message */
  11953. raise_exception(EXERROR);
  11954. }
  11955. xargv = argptr;
  11956. xminusc = minusc;
  11957. if (*xargv == NULL) {
  11958. if (xminusc)
  11959. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11960. sflag = 1;
  11961. }
  11962. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11963. iflag = 1;
  11964. if (mflag == 2)
  11965. mflag = iflag;
  11966. for (i = 0; i < NOPTS; i++)
  11967. if (optlist[i] == 2)
  11968. optlist[i] = 0;
  11969. #if DEBUG == 2
  11970. debug = 1;
  11971. #endif
  11972. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11973. if (xminusc) {
  11974. minusc = *xargv++;
  11975. if (*xargv)
  11976. goto setarg0;
  11977. } else if (!sflag) {
  11978. setinputfile(*xargv, 0);
  11979. setarg0:
  11980. arg0 = *xargv++;
  11981. commandname = arg0;
  11982. }
  11983. shellparam.p = xargv;
  11984. #if ENABLE_ASH_GETOPTS
  11985. shellparam.optind = 1;
  11986. shellparam.optoff = -1;
  11987. #endif
  11988. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11989. while (*xargv) {
  11990. shellparam.nparam++;
  11991. xargv++;
  11992. }
  11993. optschanged();
  11994. }
  11995. /*
  11996. * Read /etc/profile or .profile.
  11997. */
  11998. static void
  11999. read_profile(const char *name)
  12000. {
  12001. int skip;
  12002. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12003. return;
  12004. skip = cmdloop(0);
  12005. popfile();
  12006. if (skip)
  12007. exitshell();
  12008. }
  12009. /*
  12010. * This routine is called when an error or an interrupt occurs in an
  12011. * interactive shell and control is returned to the main command loop.
  12012. */
  12013. static void
  12014. reset(void)
  12015. {
  12016. /* from eval.c: */
  12017. evalskip = 0;
  12018. loopnest = 0;
  12019. /* from input.c: */
  12020. g_parsefile->left_in_buffer = 0;
  12021. g_parsefile->left_in_line = 0; /* clear input buffer */
  12022. popallfiles();
  12023. /* from parser.c: */
  12024. tokpushback = 0;
  12025. checkkwd = 0;
  12026. /* from redir.c: */
  12027. clearredir(/*drop:*/ 0);
  12028. }
  12029. #if PROFILE
  12030. static short profile_buf[16384];
  12031. extern int etext();
  12032. #endif
  12033. /*
  12034. * Main routine. We initialize things, parse the arguments, execute
  12035. * profiles if we're a login shell, and then call cmdloop to execute
  12036. * commands. The setjmp call sets up the location to jump to when an
  12037. * exception occurs. When an exception occurs the variable "state"
  12038. * is used to figure out how far we had gotten.
  12039. */
  12040. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12041. int ash_main(int argc UNUSED_PARAM, char **argv)
  12042. {
  12043. const char *shinit;
  12044. volatile smallint state;
  12045. struct jmploc jmploc;
  12046. struct stackmark smark;
  12047. /* Initialize global data */
  12048. INIT_G_misc();
  12049. INIT_G_memstack();
  12050. INIT_G_var();
  12051. #if ENABLE_ASH_ALIAS
  12052. INIT_G_alias();
  12053. #endif
  12054. INIT_G_cmdtable();
  12055. #if PROFILE
  12056. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12057. #endif
  12058. #if ENABLE_FEATURE_EDITING
  12059. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12060. #endif
  12061. state = 0;
  12062. if (setjmp(jmploc.loc)) {
  12063. smallint e;
  12064. smallint s;
  12065. reset();
  12066. e = exception_type;
  12067. if (e == EXERROR)
  12068. exitstatus = 2;
  12069. s = state;
  12070. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12071. exitshell();
  12072. }
  12073. if (e == EXINT) {
  12074. newline_and_flush(stderr);
  12075. }
  12076. popstackmark(&smark);
  12077. FORCE_INT_ON; /* enable interrupts */
  12078. if (s == 1)
  12079. goto state1;
  12080. if (s == 2)
  12081. goto state2;
  12082. if (s == 3)
  12083. goto state3;
  12084. goto state4;
  12085. }
  12086. exception_handler = &jmploc;
  12087. #if DEBUG
  12088. opentrace();
  12089. TRACE(("Shell args: "));
  12090. trace_puts_args(argv);
  12091. #endif
  12092. rootpid = getpid();
  12093. init();
  12094. setstackmark(&smark);
  12095. procargs(argv);
  12096. if (argv[0] && argv[0][0] == '-')
  12097. isloginsh = 1;
  12098. if (isloginsh) {
  12099. const char *hp;
  12100. state = 1;
  12101. read_profile("/etc/profile");
  12102. state1:
  12103. state = 2;
  12104. hp = lookupvar("HOME");
  12105. if (hp) {
  12106. hp = concat_path_file(hp, ".profile");
  12107. read_profile(hp);
  12108. free((char*)hp);
  12109. }
  12110. }
  12111. state2:
  12112. state = 3;
  12113. if (
  12114. #ifndef linux
  12115. getuid() == geteuid() && getgid() == getegid() &&
  12116. #endif
  12117. iflag
  12118. ) {
  12119. shinit = lookupvar("ENV");
  12120. if (shinit != NULL && *shinit != '\0') {
  12121. read_profile(shinit);
  12122. }
  12123. }
  12124. state3:
  12125. state = 4;
  12126. if (minusc) {
  12127. /* evalstring pushes parsefile stack.
  12128. * Ensure we don't falsely claim that 0 (stdin)
  12129. * is one of stacked source fds.
  12130. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12131. // if (!sflag) g_parsefile->pf_fd = -1;
  12132. // ^^ not necessary since now we special-case fd 0
  12133. // in is_hidden_fd() to not be considered "hidden fd"
  12134. evalstring(minusc, 0);
  12135. }
  12136. if (sflag || minusc == NULL) {
  12137. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12138. if (iflag) {
  12139. const char *hp = lookupvar("HISTFILE");
  12140. if (!hp) {
  12141. hp = lookupvar("HOME");
  12142. if (hp) {
  12143. hp = concat_path_file(hp, ".ash_history");
  12144. setvar0("HISTFILE", hp);
  12145. free((char*)hp);
  12146. hp = lookupvar("HISTFILE");
  12147. }
  12148. }
  12149. if (hp)
  12150. line_input_state->hist_file = hp;
  12151. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12152. hp = lookupvar("HISTFILESIZE");
  12153. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12154. # endif
  12155. }
  12156. #endif
  12157. state4: /* XXX ??? - why isn't this before the "if" statement */
  12158. cmdloop(1);
  12159. }
  12160. #if PROFILE
  12161. monitor(0);
  12162. #endif
  12163. #ifdef GPROF
  12164. {
  12165. extern void _mcleanup(void);
  12166. _mcleanup();
  12167. }
  12168. #endif
  12169. TRACE(("End of main reached\n"));
  12170. exitshell();
  12171. /* NOTREACHED */
  12172. }
  12173. /*-
  12174. * Copyright (c) 1989, 1991, 1993, 1994
  12175. * The Regents of the University of California. All rights reserved.
  12176. *
  12177. * This code is derived from software contributed to Berkeley by
  12178. * Kenneth Almquist.
  12179. *
  12180. * Redistribution and use in source and binary forms, with or without
  12181. * modification, are permitted provided that the following conditions
  12182. * are met:
  12183. * 1. Redistributions of source code must retain the above copyright
  12184. * notice, this list of conditions and the following disclaimer.
  12185. * 2. Redistributions in binary form must reproduce the above copyright
  12186. * notice, this list of conditions and the following disclaimer in the
  12187. * documentation and/or other materials provided with the distribution.
  12188. * 3. Neither the name of the University nor the names of its contributors
  12189. * may be used to endorse or promote products derived from this software
  12190. * without specific prior written permission.
  12191. *
  12192. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12193. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12194. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12195. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12196. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12197. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12198. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12199. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12200. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12201. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12202. * SUCH DAMAGE.
  12203. */