ash.c 292 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. /*
  19. * The following should be set to reflect the type of system you have:
  20. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  21. * define SYSV if you are running under System V.
  22. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  23. * define DEBUG=2 to compile in and turn on debugging.
  24. *
  25. * When debugging is on (DEBUG is 1 and "set -o debug" was executed),
  26. * debugging info will be written to ./trace and a quit signal
  27. * will generate a core dump.
  28. */
  29. #define DEBUG 0
  30. /* Tweak debug output verbosity here */
  31. #define DEBUG_TIME 0
  32. #define DEBUG_PID 1
  33. #define DEBUG_SIG 1
  34. #define PROFILE 0
  35. #define JOBS ENABLE_ASH_JOB_CONTROL
  36. #include <paths.h>
  37. #include <setjmp.h>
  38. #include <fnmatch.h>
  39. #include <sys/times.h>
  40. #include <sys/utsname.h> /* for setting $HOSTNAME */
  41. #include "busybox.h" /* for applet_names */
  42. #include "unicode.h"
  43. #include "shell_common.h"
  44. #if ENABLE_SH_MATH_SUPPORT
  45. # include "math.h"
  46. #endif
  47. #if ENABLE_ASH_RANDOM_SUPPORT
  48. # include "random.h"
  49. #else
  50. # define CLEAR_RANDOM_T(rnd) ((void)0)
  51. #endif
  52. #include "NUM_APPLETS.h"
  53. #if NUM_APPLETS == 1
  54. /* STANDALONE does not make sense, and won't compile */
  55. # undef CONFIG_FEATURE_SH_STANDALONE
  56. # undef ENABLE_FEATURE_SH_STANDALONE
  57. # undef IF_FEATURE_SH_STANDALONE
  58. # undef IF_NOT_FEATURE_SH_STANDALONE
  59. # define ENABLE_FEATURE_SH_STANDALONE 0
  60. # define IF_FEATURE_SH_STANDALONE(...)
  61. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  62. #endif
  63. #ifndef PIPE_BUF
  64. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  65. #endif
  66. #if !BB_MMU
  67. # error "Do not even bother, ash will not run on NOMMU machine"
  68. #endif
  69. //config:config ASH
  70. //config: bool "ash"
  71. //config: default y
  72. //config: depends on !NOMMU
  73. //config: help
  74. //config: Tha 'ash' shell adds about 60k in the default configuration and is
  75. //config: the most complete and most pedantically correct shell included with
  76. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  77. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  78. //config: (written by Kenneth Almquist) from NetBSD.
  79. //config:
  80. //config:config ASH_BASH_COMPAT
  81. //config: bool "bash-compatible extensions"
  82. //config: default y
  83. //config: depends on ASH
  84. //config: help
  85. //config: Enable bash-compatible extensions.
  86. //config:
  87. //config:config ASH_IDLE_TIMEOUT
  88. //config: bool "Idle timeout variable"
  89. //config: default n
  90. //config: depends on ASH
  91. //config: help
  92. //config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
  93. //config:
  94. //config:config ASH_JOB_CONTROL
  95. //config: bool "Job control"
  96. //config: default y
  97. //config: depends on ASH
  98. //config: help
  99. //config: Enable job control in the ash shell.
  100. //config:
  101. //config:config ASH_ALIAS
  102. //config: bool "Alias support"
  103. //config: default y
  104. //config: depends on ASH
  105. //config: help
  106. //config: Enable alias support in the ash shell.
  107. //config:
  108. //config:config ASH_GETOPTS
  109. //config: bool "Builtin getopt to parse positional parameters"
  110. //config: default y
  111. //config: depends on ASH
  112. //config: help
  113. //config: Enable support for getopts builtin in ash.
  114. //config:
  115. //config:config ASH_BUILTIN_ECHO
  116. //config: bool "Builtin version of 'echo'"
  117. //config: default y
  118. //config: depends on ASH
  119. //config: help
  120. //config: Enable support for echo builtin in ash.
  121. //config:
  122. //config:config ASH_BUILTIN_PRINTF
  123. //config: bool "Builtin version of 'printf'"
  124. //config: default y
  125. //config: depends on ASH
  126. //config: help
  127. //config: Enable support for printf builtin in ash.
  128. //config:
  129. //config:config ASH_BUILTIN_TEST
  130. //config: bool "Builtin version of 'test'"
  131. //config: default y
  132. //config: depends on ASH
  133. //config: help
  134. //config: Enable support for test builtin in ash.
  135. //config:
  136. //config:config ASH_HELP
  137. //config: bool "help builtin"
  138. //config: default y
  139. //config: depends on ASH
  140. //config: help
  141. //config: Enable help builtin in ash.
  142. //config:
  143. //config:config ASH_CMDCMD
  144. //config: bool "'command' command to override shell builtins"
  145. //config: default y
  146. //config: depends on ASH
  147. //config: help
  148. //config: Enable support for the ash 'command' builtin, which allows
  149. //config: you to run the specified command with the specified arguments,
  150. //config: even when there is an ash builtin command with the same name.
  151. //config:
  152. //config:config ASH_MAIL
  153. //config: bool "Check for new mail on interactive shells"
  154. //config: default n
  155. //config: depends on ASH
  156. //config: help
  157. //config: Enable "check for new mail" function in the ash shell.
  158. //config:
  159. //config:config ASH_OPTIMIZE_FOR_SIZE
  160. //config: bool "Optimize for size instead of speed"
  161. //config: default y
  162. //config: depends on ASH
  163. //config: help
  164. //config: Compile ash for reduced size at the price of speed.
  165. //config:
  166. //config:config ASH_RANDOM_SUPPORT
  167. //config: bool "Pseudorandom generator and $RANDOM variable"
  168. //config: default y
  169. //config: depends on ASH
  170. //config: help
  171. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  172. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  173. //config: You can reset the generator by using a specified start value.
  174. //config: After "unset RANDOM" the generator will switch off and this
  175. //config: variable will no longer have special treatment.
  176. //config:
  177. //config:config ASH_EXPAND_PRMT
  178. //config: bool "Expand prompt string"
  179. //config: default y
  180. //config: depends on ASH
  181. //config: help
  182. //config: "PS#" may contain volatile content, such as backquote commands.
  183. //config: This option recreates the prompt string from the environment
  184. //config: variable each time it is displayed.
  185. //config:
  186. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  187. //applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
  188. //applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
  189. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  190. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  191. /* ============ Hash table sizes. Configurable. */
  192. #define VTABSIZE 39
  193. #define ATABSIZE 39
  194. #define CMDTABLESIZE 31 /* should be prime */
  195. /* ============ Shell options */
  196. static const char *const optletters_optnames[] = {
  197. "e" "errexit",
  198. "f" "noglob",
  199. "I" "ignoreeof",
  200. "i" "interactive",
  201. "m" "monitor",
  202. "n" "noexec",
  203. "s" "stdin",
  204. "x" "xtrace",
  205. "v" "verbose",
  206. "C" "noclobber",
  207. "a" "allexport",
  208. "b" "notify",
  209. "u" "nounset",
  210. "\0" "vi"
  211. #if ENABLE_ASH_BASH_COMPAT
  212. ,"\0" "pipefail"
  213. #endif
  214. #if DEBUG
  215. ,"\0" "nolog"
  216. ,"\0" "debug"
  217. #endif
  218. };
  219. #define optletters(n) optletters_optnames[n][0]
  220. #define optnames(n) (optletters_optnames[n] + 1)
  221. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  222. /* ============ Misc data */
  223. #define msg_illnum "Illegal number: %s"
  224. /*
  225. * We enclose jmp_buf in a structure so that we can declare pointers to
  226. * jump locations. The global variable handler contains the location to
  227. * jump to when an exception occurs, and the global variable exception_type
  228. * contains a code identifying the exception. To implement nested
  229. * exception handlers, the user should save the value of handler on entry
  230. * to an inner scope, set handler to point to a jmploc structure for the
  231. * inner scope, and restore handler on exit from the scope.
  232. */
  233. struct jmploc {
  234. jmp_buf loc;
  235. };
  236. struct globals_misc {
  237. /* pid of main shell */
  238. int rootpid;
  239. /* shell level: 0 for the main shell, 1 for its children, and so on */
  240. int shlvl;
  241. #define rootshell (!shlvl)
  242. char *minusc; /* argument to -c option */
  243. char *curdir; // = nullstr; /* current working directory */
  244. char *physdir; // = nullstr; /* physical working directory */
  245. char *arg0; /* value of $0 */
  246. struct jmploc *exception_handler;
  247. volatile int suppress_int; /* counter */
  248. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  249. /* last pending signal */
  250. volatile /*sig_atomic_t*/ smallint pending_sig;
  251. smallint exception_type; /* kind of exception (0..5) */
  252. /* exceptions */
  253. #define EXINT 0 /* SIGINT received */
  254. #define EXERROR 1 /* a generic error */
  255. #define EXSHELLPROC 2 /* execute a shell procedure */
  256. #define EXEXEC 3 /* command execution failed */
  257. #define EXEXIT 4 /* exit the shell */
  258. #define EXSIG 5 /* trapped signal in wait(1) */
  259. smallint isloginsh;
  260. char nullstr[1]; /* zero length string */
  261. char optlist[NOPTS];
  262. #define eflag optlist[0]
  263. #define fflag optlist[1]
  264. #define Iflag optlist[2]
  265. #define iflag optlist[3]
  266. #define mflag optlist[4]
  267. #define nflag optlist[5]
  268. #define sflag optlist[6]
  269. #define xflag optlist[7]
  270. #define vflag optlist[8]
  271. #define Cflag optlist[9]
  272. #define aflag optlist[10]
  273. #define bflag optlist[11]
  274. #define uflag optlist[12]
  275. #define viflag optlist[13]
  276. #if ENABLE_ASH_BASH_COMPAT
  277. # define pipefail optlist[14]
  278. #else
  279. # define pipefail 0
  280. #endif
  281. #if DEBUG
  282. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  283. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  284. #endif
  285. /* trap handler commands */
  286. /*
  287. * Sigmode records the current value of the signal handlers for the various
  288. * modes. A value of zero means that the current handler is not known.
  289. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  290. */
  291. char sigmode[NSIG - 1];
  292. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  293. #define S_CATCH 2 /* signal is caught */
  294. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  295. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  296. /* indicates specified signal received */
  297. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  298. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  299. char *trap[NSIG];
  300. char **trap_ptr; /* used only by "trap hack" */
  301. /* Rarely referenced stuff */
  302. #if ENABLE_ASH_RANDOM_SUPPORT
  303. random_t random_gen;
  304. #endif
  305. pid_t backgndpid; /* pid of last background process */
  306. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  307. };
  308. extern struct globals_misc *const ash_ptr_to_globals_misc;
  309. #define G_misc (*ash_ptr_to_globals_misc)
  310. #define rootpid (G_misc.rootpid )
  311. #define shlvl (G_misc.shlvl )
  312. #define minusc (G_misc.minusc )
  313. #define curdir (G_misc.curdir )
  314. #define physdir (G_misc.physdir )
  315. #define arg0 (G_misc.arg0 )
  316. #define exception_handler (G_misc.exception_handler)
  317. #define exception_type (G_misc.exception_type )
  318. #define suppress_int (G_misc.suppress_int )
  319. #define pending_int (G_misc.pending_int )
  320. #define pending_sig (G_misc.pending_sig )
  321. #define isloginsh (G_misc.isloginsh )
  322. #define nullstr (G_misc.nullstr )
  323. #define optlist (G_misc.optlist )
  324. #define sigmode (G_misc.sigmode )
  325. #define gotsig (G_misc.gotsig )
  326. #define may_have_traps (G_misc.may_have_traps )
  327. #define trap (G_misc.trap )
  328. #define trap_ptr (G_misc.trap_ptr )
  329. #define random_gen (G_misc.random_gen )
  330. #define backgndpid (G_misc.backgndpid )
  331. #define job_warning (G_misc.job_warning)
  332. #define INIT_G_misc() do { \
  333. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  334. barrier(); \
  335. curdir = nullstr; \
  336. physdir = nullstr; \
  337. trap_ptr = trap; \
  338. } while (0)
  339. /* ============ DEBUG */
  340. #if DEBUG
  341. static void trace_printf(const char *fmt, ...);
  342. static void trace_vprintf(const char *fmt, va_list va);
  343. # define TRACE(param) trace_printf param
  344. # define TRACEV(param) trace_vprintf param
  345. # define close(fd) do { \
  346. int dfd = (fd); \
  347. if (close(dfd) < 0) \
  348. bb_error_msg("bug on %d: closing %d(0x%x)", \
  349. __LINE__, dfd, dfd); \
  350. } while (0)
  351. #else
  352. # define TRACE(param)
  353. # define TRACEV(param)
  354. #endif
  355. /* ============ Utility functions */
  356. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  357. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  358. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  359. static int isdigit_str9(const char *str)
  360. {
  361. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  362. while (--maxlen && isdigit(*str))
  363. str++;
  364. return (*str == '\0');
  365. }
  366. static const char *var_end(const char *var)
  367. {
  368. while (*var)
  369. if (*var++ == '=')
  370. break;
  371. return var;
  372. }
  373. /* ============ Interrupts / exceptions */
  374. static void exitshell(void) NORETURN;
  375. /*
  376. * These macros allow the user to suspend the handling of interrupt signals
  377. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  378. * much more efficient and portable. (But hacking the kernel is so much
  379. * more fun than worrying about efficiency and portability. :-))
  380. */
  381. #define INT_OFF do { \
  382. suppress_int++; \
  383. xbarrier(); \
  384. } while (0)
  385. /*
  386. * Called to raise an exception. Since C doesn't include exceptions, we
  387. * just do a longjmp to the exception handler. The type of exception is
  388. * stored in the global variable "exception_type".
  389. */
  390. static void raise_exception(int) NORETURN;
  391. static void
  392. raise_exception(int e)
  393. {
  394. #if DEBUG
  395. if (exception_handler == NULL)
  396. abort();
  397. #endif
  398. INT_OFF;
  399. exception_type = e;
  400. longjmp(exception_handler->loc, 1);
  401. }
  402. #if DEBUG
  403. #define raise_exception(e) do { \
  404. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  405. raise_exception(e); \
  406. } while (0)
  407. #endif
  408. /*
  409. * Called from trap.c when a SIGINT is received. (If the user specifies
  410. * that SIGINT is to be trapped or ignored using the trap builtin, then
  411. * this routine is not called.) Suppressint is nonzero when interrupts
  412. * are held using the INT_OFF macro. (The test for iflag is just
  413. * defensive programming.)
  414. */
  415. static void raise_interrupt(void) NORETURN;
  416. static void
  417. raise_interrupt(void)
  418. {
  419. int ex_type;
  420. pending_int = 0;
  421. /* Signal is not automatically unmasked after it is raised,
  422. * do it ourself - unmask all signals */
  423. sigprocmask_allsigs(SIG_UNBLOCK);
  424. /* pending_sig = 0; - now done in signal_handler() */
  425. ex_type = EXSIG;
  426. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  427. if (!(rootshell && iflag)) {
  428. /* Kill ourself with SIGINT */
  429. signal(SIGINT, SIG_DFL);
  430. raise(SIGINT);
  431. }
  432. ex_type = EXINT;
  433. }
  434. raise_exception(ex_type);
  435. /* NOTREACHED */
  436. }
  437. #if DEBUG
  438. #define raise_interrupt() do { \
  439. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  440. raise_interrupt(); \
  441. } while (0)
  442. #endif
  443. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  444. int_on(void)
  445. {
  446. xbarrier();
  447. if (--suppress_int == 0 && pending_int) {
  448. raise_interrupt();
  449. }
  450. }
  451. #define INT_ON int_on()
  452. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  453. force_int_on(void)
  454. {
  455. xbarrier();
  456. suppress_int = 0;
  457. if (pending_int)
  458. raise_interrupt();
  459. }
  460. #define FORCE_INT_ON force_int_on()
  461. #define SAVE_INT(v) ((v) = suppress_int)
  462. #define RESTORE_INT(v) do { \
  463. xbarrier(); \
  464. suppress_int = (v); \
  465. if (suppress_int == 0 && pending_int) \
  466. raise_interrupt(); \
  467. } while (0)
  468. /* ============ Stdout/stderr output */
  469. static void
  470. outstr(const char *p, FILE *file)
  471. {
  472. INT_OFF;
  473. fputs(p, file);
  474. INT_ON;
  475. }
  476. static void
  477. flush_stdout_stderr(void)
  478. {
  479. INT_OFF;
  480. fflush_all();
  481. INT_ON;
  482. }
  483. /* Was called outcslow(c,FILE*), but c was always '\n' */
  484. static void
  485. newline_and_flush(FILE *dest)
  486. {
  487. INT_OFF;
  488. putc('\n', dest);
  489. fflush(dest);
  490. INT_ON;
  491. }
  492. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  493. static int
  494. out1fmt(const char *fmt, ...)
  495. {
  496. va_list ap;
  497. int r;
  498. INT_OFF;
  499. va_start(ap, fmt);
  500. r = vprintf(fmt, ap);
  501. va_end(ap);
  502. INT_ON;
  503. return r;
  504. }
  505. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  506. static int
  507. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  508. {
  509. va_list ap;
  510. int ret;
  511. va_start(ap, fmt);
  512. INT_OFF;
  513. ret = vsnprintf(outbuf, length, fmt, ap);
  514. va_end(ap);
  515. INT_ON;
  516. return ret;
  517. }
  518. static void
  519. out1str(const char *p)
  520. {
  521. outstr(p, stdout);
  522. }
  523. static void
  524. out2str(const char *p)
  525. {
  526. outstr(p, stderr);
  527. flush_stdout_stderr();
  528. }
  529. /* ============ Parser structures */
  530. /* control characters in argument strings */
  531. #define CTL_FIRST CTLESC
  532. #define CTLESC ((unsigned char)'\201') /* escape next character */
  533. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  534. #define CTLENDVAR ((unsigned char)'\203')
  535. #define CTLBACKQ ((unsigned char)'\204')
  536. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  537. #define CTLENDARI ((unsigned char)'\207')
  538. #define CTLQUOTEMARK ((unsigned char)'\210')
  539. #define CTL_LAST CTLQUOTEMARK
  540. /* variable substitution byte (follows CTLVAR) */
  541. #define VSTYPE 0x0f /* type of variable substitution */
  542. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  543. /* values of VSTYPE field */
  544. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  545. #define VSMINUS 0x2 /* ${var-text} */
  546. #define VSPLUS 0x3 /* ${var+text} */
  547. #define VSQUESTION 0x4 /* ${var?message} */
  548. #define VSASSIGN 0x5 /* ${var=text} */
  549. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  550. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  551. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  552. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  553. #define VSLENGTH 0xa /* ${#var} */
  554. #if ENABLE_ASH_BASH_COMPAT
  555. #define VSSUBSTR 0xc /* ${var:position:length} */
  556. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  557. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  558. #endif
  559. static const char dolatstr[] ALIGN1 = {
  560. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  561. };
  562. #define DOLATSTRLEN 6
  563. #define NCMD 0
  564. #define NPIPE 1
  565. #define NREDIR 2
  566. #define NBACKGND 3
  567. #define NSUBSHELL 4
  568. #define NAND 5
  569. #define NOR 6
  570. #define NSEMI 7
  571. #define NIF 8
  572. #define NWHILE 9
  573. #define NUNTIL 10
  574. #define NFOR 11
  575. #define NCASE 12
  576. #define NCLIST 13
  577. #define NDEFUN 14
  578. #define NARG 15
  579. #define NTO 16
  580. #if ENABLE_ASH_BASH_COMPAT
  581. #define NTO2 17
  582. #endif
  583. #define NCLOBBER 18
  584. #define NFROM 19
  585. #define NFROMTO 20
  586. #define NAPPEND 21
  587. #define NTOFD 22
  588. #define NFROMFD 23
  589. #define NHERE 24
  590. #define NXHERE 25
  591. #define NNOT 26
  592. #define N_NUMBER 27
  593. union node;
  594. struct ncmd {
  595. smallint type; /* Nxxxx */
  596. union node *assign;
  597. union node *args;
  598. union node *redirect;
  599. };
  600. struct npipe {
  601. smallint type;
  602. smallint pipe_backgnd;
  603. struct nodelist *cmdlist;
  604. };
  605. struct nredir {
  606. smallint type;
  607. union node *n;
  608. union node *redirect;
  609. };
  610. struct nbinary {
  611. smallint type;
  612. union node *ch1;
  613. union node *ch2;
  614. };
  615. struct nif {
  616. smallint type;
  617. union node *test;
  618. union node *ifpart;
  619. union node *elsepart;
  620. };
  621. struct nfor {
  622. smallint type;
  623. union node *args;
  624. union node *body;
  625. char *var;
  626. };
  627. struct ncase {
  628. smallint type;
  629. union node *expr;
  630. union node *cases;
  631. };
  632. struct nclist {
  633. smallint type;
  634. union node *next;
  635. union node *pattern;
  636. union node *body;
  637. };
  638. struct narg {
  639. smallint type;
  640. union node *next;
  641. char *text;
  642. struct nodelist *backquote;
  643. };
  644. /* nfile and ndup layout must match!
  645. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  646. * that it is actually NTO2 (>&file), and change its type.
  647. */
  648. struct nfile {
  649. smallint type;
  650. union node *next;
  651. int fd;
  652. int _unused_dupfd;
  653. union node *fname;
  654. char *expfname;
  655. };
  656. struct ndup {
  657. smallint type;
  658. union node *next;
  659. int fd;
  660. int dupfd;
  661. union node *vname;
  662. char *_unused_expfname;
  663. };
  664. struct nhere {
  665. smallint type;
  666. union node *next;
  667. int fd;
  668. union node *doc;
  669. };
  670. struct nnot {
  671. smallint type;
  672. union node *com;
  673. };
  674. union node {
  675. smallint type;
  676. struct ncmd ncmd;
  677. struct npipe npipe;
  678. struct nredir nredir;
  679. struct nbinary nbinary;
  680. struct nif nif;
  681. struct nfor nfor;
  682. struct ncase ncase;
  683. struct nclist nclist;
  684. struct narg narg;
  685. struct nfile nfile;
  686. struct ndup ndup;
  687. struct nhere nhere;
  688. struct nnot nnot;
  689. };
  690. /*
  691. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  692. * It must be distinct from NULL.
  693. */
  694. #define NODE_EOF ((union node *) -1L)
  695. struct nodelist {
  696. struct nodelist *next;
  697. union node *n;
  698. };
  699. struct funcnode {
  700. int count;
  701. union node n;
  702. };
  703. /*
  704. * Free a parse tree.
  705. */
  706. static void
  707. freefunc(struct funcnode *f)
  708. {
  709. if (f && --f->count < 0)
  710. free(f);
  711. }
  712. /* ============ Debugging output */
  713. #if DEBUG
  714. static FILE *tracefile;
  715. static void
  716. trace_printf(const char *fmt, ...)
  717. {
  718. va_list va;
  719. if (debug != 1)
  720. return;
  721. if (DEBUG_TIME)
  722. fprintf(tracefile, "%u ", (int) time(NULL));
  723. if (DEBUG_PID)
  724. fprintf(tracefile, "[%u] ", (int) getpid());
  725. if (DEBUG_SIG)
  726. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  727. va_start(va, fmt);
  728. vfprintf(tracefile, fmt, va);
  729. va_end(va);
  730. }
  731. static void
  732. trace_vprintf(const char *fmt, va_list va)
  733. {
  734. if (debug != 1)
  735. return;
  736. if (DEBUG_TIME)
  737. fprintf(tracefile, "%u ", (int) time(NULL));
  738. if (DEBUG_PID)
  739. fprintf(tracefile, "[%u] ", (int) getpid());
  740. if (DEBUG_SIG)
  741. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  742. vfprintf(tracefile, fmt, va);
  743. }
  744. static void
  745. trace_puts(const char *s)
  746. {
  747. if (debug != 1)
  748. return;
  749. fputs(s, tracefile);
  750. }
  751. static void
  752. trace_puts_quoted(char *s)
  753. {
  754. char *p;
  755. char c;
  756. if (debug != 1)
  757. return;
  758. putc('"', tracefile);
  759. for (p = s; *p; p++) {
  760. switch ((unsigned char)*p) {
  761. case '\n': c = 'n'; goto backslash;
  762. case '\t': c = 't'; goto backslash;
  763. case '\r': c = 'r'; goto backslash;
  764. case '\"': c = '\"'; goto backslash;
  765. case '\\': c = '\\'; goto backslash;
  766. case CTLESC: c = 'e'; goto backslash;
  767. case CTLVAR: c = 'v'; goto backslash;
  768. case CTLBACKQ: c = 'q'; goto backslash;
  769. backslash:
  770. putc('\\', tracefile);
  771. putc(c, tracefile);
  772. break;
  773. default:
  774. if (*p >= ' ' && *p <= '~')
  775. putc(*p, tracefile);
  776. else {
  777. putc('\\', tracefile);
  778. putc((*p >> 6) & 03, tracefile);
  779. putc((*p >> 3) & 07, tracefile);
  780. putc(*p & 07, tracefile);
  781. }
  782. break;
  783. }
  784. }
  785. putc('"', tracefile);
  786. }
  787. static void
  788. trace_puts_args(char **ap)
  789. {
  790. if (debug != 1)
  791. return;
  792. if (!*ap)
  793. return;
  794. while (1) {
  795. trace_puts_quoted(*ap);
  796. if (!*++ap) {
  797. putc('\n', tracefile);
  798. break;
  799. }
  800. putc(' ', tracefile);
  801. }
  802. }
  803. static void
  804. opentrace(void)
  805. {
  806. char s[100];
  807. #ifdef O_APPEND
  808. int flags;
  809. #endif
  810. if (debug != 1) {
  811. if (tracefile)
  812. fflush(tracefile);
  813. /* leave open because libedit might be using it */
  814. return;
  815. }
  816. strcpy(s, "./trace");
  817. if (tracefile) {
  818. if (!freopen(s, "a", tracefile)) {
  819. fprintf(stderr, "Can't re-open %s\n", s);
  820. debug = 0;
  821. return;
  822. }
  823. } else {
  824. tracefile = fopen(s, "a");
  825. if (tracefile == NULL) {
  826. fprintf(stderr, "Can't open %s\n", s);
  827. debug = 0;
  828. return;
  829. }
  830. }
  831. #ifdef O_APPEND
  832. flags = fcntl(fileno(tracefile), F_GETFL);
  833. if (flags >= 0)
  834. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  835. #endif
  836. setlinebuf(tracefile);
  837. fputs("\nTracing started.\n", tracefile);
  838. }
  839. static void
  840. indent(int amount, char *pfx, FILE *fp)
  841. {
  842. int i;
  843. for (i = 0; i < amount; i++) {
  844. if (pfx && i == amount - 1)
  845. fputs(pfx, fp);
  846. putc('\t', fp);
  847. }
  848. }
  849. /* little circular references here... */
  850. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  851. static void
  852. sharg(union node *arg, FILE *fp)
  853. {
  854. char *p;
  855. struct nodelist *bqlist;
  856. unsigned char subtype;
  857. if (arg->type != NARG) {
  858. out1fmt("<node type %d>\n", arg->type);
  859. abort();
  860. }
  861. bqlist = arg->narg.backquote;
  862. for (p = arg->narg.text; *p; p++) {
  863. switch ((unsigned char)*p) {
  864. case CTLESC:
  865. p++;
  866. putc(*p, fp);
  867. break;
  868. case CTLVAR:
  869. putc('$', fp);
  870. putc('{', fp);
  871. subtype = *++p;
  872. if (subtype == VSLENGTH)
  873. putc('#', fp);
  874. while (*p != '=') {
  875. putc(*p, fp);
  876. p++;
  877. }
  878. if (subtype & VSNUL)
  879. putc(':', fp);
  880. switch (subtype & VSTYPE) {
  881. case VSNORMAL:
  882. putc('}', fp);
  883. break;
  884. case VSMINUS:
  885. putc('-', fp);
  886. break;
  887. case VSPLUS:
  888. putc('+', fp);
  889. break;
  890. case VSQUESTION:
  891. putc('?', fp);
  892. break;
  893. case VSASSIGN:
  894. putc('=', fp);
  895. break;
  896. case VSTRIMLEFT:
  897. putc('#', fp);
  898. break;
  899. case VSTRIMLEFTMAX:
  900. putc('#', fp);
  901. putc('#', fp);
  902. break;
  903. case VSTRIMRIGHT:
  904. putc('%', fp);
  905. break;
  906. case VSTRIMRIGHTMAX:
  907. putc('%', fp);
  908. putc('%', fp);
  909. break;
  910. case VSLENGTH:
  911. break;
  912. default:
  913. out1fmt("<subtype %d>", subtype);
  914. }
  915. break;
  916. case CTLENDVAR:
  917. putc('}', fp);
  918. break;
  919. case CTLBACKQ:
  920. putc('$', fp);
  921. putc('(', fp);
  922. shtree(bqlist->n, -1, NULL, fp);
  923. putc(')', fp);
  924. break;
  925. default:
  926. putc(*p, fp);
  927. break;
  928. }
  929. }
  930. }
  931. static void
  932. shcmd(union node *cmd, FILE *fp)
  933. {
  934. union node *np;
  935. int first;
  936. const char *s;
  937. int dftfd;
  938. first = 1;
  939. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  940. if (!first)
  941. putc(' ', fp);
  942. sharg(np, fp);
  943. first = 0;
  944. }
  945. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  946. if (!first)
  947. putc(' ', fp);
  948. dftfd = 0;
  949. switch (np->nfile.type) {
  950. case NTO: s = ">>"+1; dftfd = 1; break;
  951. case NCLOBBER: s = ">|"; dftfd = 1; break;
  952. case NAPPEND: s = ">>"; dftfd = 1; break;
  953. #if ENABLE_ASH_BASH_COMPAT
  954. case NTO2:
  955. #endif
  956. case NTOFD: s = ">&"; dftfd = 1; break;
  957. case NFROM: s = "<"; break;
  958. case NFROMFD: s = "<&"; break;
  959. case NFROMTO: s = "<>"; break;
  960. default: s = "*error*"; break;
  961. }
  962. if (np->nfile.fd != dftfd)
  963. fprintf(fp, "%d", np->nfile.fd);
  964. fputs(s, fp);
  965. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  966. fprintf(fp, "%d", np->ndup.dupfd);
  967. } else {
  968. sharg(np->nfile.fname, fp);
  969. }
  970. first = 0;
  971. }
  972. }
  973. static void
  974. shtree(union node *n, int ind, char *pfx, FILE *fp)
  975. {
  976. struct nodelist *lp;
  977. const char *s;
  978. if (n == NULL)
  979. return;
  980. indent(ind, pfx, fp);
  981. if (n == NODE_EOF) {
  982. fputs("<EOF>", fp);
  983. return;
  984. }
  985. switch (n->type) {
  986. case NSEMI:
  987. s = "; ";
  988. goto binop;
  989. case NAND:
  990. s = " && ";
  991. goto binop;
  992. case NOR:
  993. s = " || ";
  994. binop:
  995. shtree(n->nbinary.ch1, ind, NULL, fp);
  996. /* if (ind < 0) */
  997. fputs(s, fp);
  998. shtree(n->nbinary.ch2, ind, NULL, fp);
  999. break;
  1000. case NCMD:
  1001. shcmd(n, fp);
  1002. if (ind >= 0)
  1003. putc('\n', fp);
  1004. break;
  1005. case NPIPE:
  1006. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1007. shtree(lp->n, 0, NULL, fp);
  1008. if (lp->next)
  1009. fputs(" | ", fp);
  1010. }
  1011. if (n->npipe.pipe_backgnd)
  1012. fputs(" &", fp);
  1013. if (ind >= 0)
  1014. putc('\n', fp);
  1015. break;
  1016. default:
  1017. fprintf(fp, "<node type %d>", n->type);
  1018. if (ind >= 0)
  1019. putc('\n', fp);
  1020. break;
  1021. }
  1022. }
  1023. static void
  1024. showtree(union node *n)
  1025. {
  1026. trace_puts("showtree called\n");
  1027. shtree(n, 1, NULL, stderr);
  1028. }
  1029. #endif /* DEBUG */
  1030. /* ============ Parser data */
  1031. /*
  1032. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1033. */
  1034. struct strlist {
  1035. struct strlist *next;
  1036. char *text;
  1037. };
  1038. struct alias;
  1039. struct strpush {
  1040. struct strpush *prev; /* preceding string on stack */
  1041. char *prev_string;
  1042. int prev_left_in_line;
  1043. #if ENABLE_ASH_ALIAS
  1044. struct alias *ap; /* if push was associated with an alias */
  1045. #endif
  1046. char *string; /* remember the string since it may change */
  1047. };
  1048. struct parsefile {
  1049. struct parsefile *prev; /* preceding file on stack */
  1050. int linno; /* current line */
  1051. int pf_fd; /* file descriptor (or -1 if string) */
  1052. int left_in_line; /* number of chars left in this line */
  1053. int left_in_buffer; /* number of chars left in this buffer past the line */
  1054. char *next_to_pgetc; /* next char in buffer */
  1055. char *buf; /* input buffer */
  1056. struct strpush *strpush; /* for pushing strings at this level */
  1057. struct strpush basestrpush; /* so pushing one is fast */
  1058. };
  1059. static struct parsefile basepf; /* top level input file */
  1060. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1061. static int startlinno; /* line # where last token started */
  1062. static char *commandname; /* currently executing command */
  1063. static struct strlist *cmdenviron; /* environment for builtin command */
  1064. static uint8_t exitstatus; /* exit status of last command */
  1065. /* ============ Message printing */
  1066. static void
  1067. ash_vmsg(const char *msg, va_list ap)
  1068. {
  1069. fprintf(stderr, "%s: ", arg0);
  1070. if (commandname) {
  1071. if (strcmp(arg0, commandname))
  1072. fprintf(stderr, "%s: ", commandname);
  1073. if (!iflag || g_parsefile->pf_fd > 0)
  1074. fprintf(stderr, "line %d: ", startlinno);
  1075. }
  1076. vfprintf(stderr, msg, ap);
  1077. newline_and_flush(stderr);
  1078. }
  1079. /*
  1080. * Exverror is called to raise the error exception. If the second argument
  1081. * is not NULL then error prints an error message using printf style
  1082. * formatting. It then raises the error exception.
  1083. */
  1084. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1085. static void
  1086. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1087. {
  1088. #if DEBUG
  1089. if (msg) {
  1090. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  1091. TRACEV((msg, ap));
  1092. TRACE(("\") pid=%d\n", getpid()));
  1093. } else
  1094. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  1095. if (msg)
  1096. #endif
  1097. ash_vmsg(msg, ap);
  1098. flush_stdout_stderr();
  1099. raise_exception(cond);
  1100. /* NOTREACHED */
  1101. }
  1102. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1103. static void
  1104. ash_msg_and_raise_error(const char *msg, ...)
  1105. {
  1106. va_list ap;
  1107. va_start(ap, msg);
  1108. ash_vmsg_and_raise(EXERROR, msg, ap);
  1109. /* NOTREACHED */
  1110. va_end(ap);
  1111. }
  1112. static void raise_error_syntax(const char *) NORETURN;
  1113. static void
  1114. raise_error_syntax(const char *msg)
  1115. {
  1116. ash_msg_and_raise_error("syntax error: %s", msg);
  1117. /* NOTREACHED */
  1118. }
  1119. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1120. static void
  1121. ash_msg_and_raise(int cond, const char *msg, ...)
  1122. {
  1123. va_list ap;
  1124. va_start(ap, msg);
  1125. ash_vmsg_and_raise(cond, msg, ap);
  1126. /* NOTREACHED */
  1127. va_end(ap);
  1128. }
  1129. /*
  1130. * error/warning routines for external builtins
  1131. */
  1132. static void
  1133. ash_msg(const char *fmt, ...)
  1134. {
  1135. va_list ap;
  1136. va_start(ap, fmt);
  1137. ash_vmsg(fmt, ap);
  1138. va_end(ap);
  1139. }
  1140. /*
  1141. * Return a string describing an error. The returned string may be a
  1142. * pointer to a static buffer that will be overwritten on the next call.
  1143. * Action describes the operation that got the error.
  1144. */
  1145. static const char *
  1146. errmsg(int e, const char *em)
  1147. {
  1148. if (e == ENOENT || e == ENOTDIR) {
  1149. return em;
  1150. }
  1151. return strerror(e);
  1152. }
  1153. /* ============ Memory allocation */
  1154. #if 0
  1155. /* I consider these wrappers nearly useless:
  1156. * ok, they return you to nearest exception handler, but
  1157. * how much memory do you leak in the process, making
  1158. * memory starvation worse?
  1159. */
  1160. static void *
  1161. ckrealloc(void * p, size_t nbytes)
  1162. {
  1163. p = realloc(p, nbytes);
  1164. if (!p)
  1165. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1166. return p;
  1167. }
  1168. static void *
  1169. ckmalloc(size_t nbytes)
  1170. {
  1171. return ckrealloc(NULL, nbytes);
  1172. }
  1173. static void *
  1174. ckzalloc(size_t nbytes)
  1175. {
  1176. return memset(ckmalloc(nbytes), 0, nbytes);
  1177. }
  1178. static char *
  1179. ckstrdup(const char *s)
  1180. {
  1181. char *p = strdup(s);
  1182. if (!p)
  1183. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1184. return p;
  1185. }
  1186. #else
  1187. /* Using bbox equivalents. They exit if out of memory */
  1188. # define ckrealloc xrealloc
  1189. # define ckmalloc xmalloc
  1190. # define ckzalloc xzalloc
  1191. # define ckstrdup xstrdup
  1192. #endif
  1193. /*
  1194. * It appears that grabstackstr() will barf with such alignments
  1195. * because stalloc() will return a string allocated in a new stackblock.
  1196. */
  1197. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1198. enum {
  1199. /* Most machines require the value returned from malloc to be aligned
  1200. * in some way. The following macro will get this right
  1201. * on many machines. */
  1202. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1203. /* Minimum size of a block */
  1204. MINSIZE = SHELL_ALIGN(504),
  1205. };
  1206. struct stack_block {
  1207. struct stack_block *prev;
  1208. char space[MINSIZE];
  1209. };
  1210. struct stackmark {
  1211. struct stack_block *stackp;
  1212. char *stacknxt;
  1213. size_t stacknleft;
  1214. struct stackmark *marknext;
  1215. };
  1216. struct globals_memstack {
  1217. struct stack_block *g_stackp; // = &stackbase;
  1218. struct stackmark *markp;
  1219. char *g_stacknxt; // = stackbase.space;
  1220. char *sstrend; // = stackbase.space + MINSIZE;
  1221. size_t g_stacknleft; // = MINSIZE;
  1222. int herefd; // = -1;
  1223. struct stack_block stackbase;
  1224. };
  1225. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1226. #define G_memstack (*ash_ptr_to_globals_memstack)
  1227. #define g_stackp (G_memstack.g_stackp )
  1228. #define markp (G_memstack.markp )
  1229. #define g_stacknxt (G_memstack.g_stacknxt )
  1230. #define sstrend (G_memstack.sstrend )
  1231. #define g_stacknleft (G_memstack.g_stacknleft)
  1232. #define herefd (G_memstack.herefd )
  1233. #define stackbase (G_memstack.stackbase )
  1234. #define INIT_G_memstack() do { \
  1235. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1236. barrier(); \
  1237. g_stackp = &stackbase; \
  1238. g_stacknxt = stackbase.space; \
  1239. g_stacknleft = MINSIZE; \
  1240. sstrend = stackbase.space + MINSIZE; \
  1241. herefd = -1; \
  1242. } while (0)
  1243. #define stackblock() ((void *)g_stacknxt)
  1244. #define stackblocksize() g_stacknleft
  1245. /*
  1246. * Parse trees for commands are allocated in lifo order, so we use a stack
  1247. * to make this more efficient, and also to avoid all sorts of exception
  1248. * handling code to handle interrupts in the middle of a parse.
  1249. *
  1250. * The size 504 was chosen because the Ultrix malloc handles that size
  1251. * well.
  1252. */
  1253. static void *
  1254. stalloc(size_t nbytes)
  1255. {
  1256. char *p;
  1257. size_t aligned;
  1258. aligned = SHELL_ALIGN(nbytes);
  1259. if (aligned > g_stacknleft) {
  1260. size_t len;
  1261. size_t blocksize;
  1262. struct stack_block *sp;
  1263. blocksize = aligned;
  1264. if (blocksize < MINSIZE)
  1265. blocksize = MINSIZE;
  1266. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1267. if (len < blocksize)
  1268. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1269. INT_OFF;
  1270. sp = ckmalloc(len);
  1271. sp->prev = g_stackp;
  1272. g_stacknxt = sp->space;
  1273. g_stacknleft = blocksize;
  1274. sstrend = g_stacknxt + blocksize;
  1275. g_stackp = sp;
  1276. INT_ON;
  1277. }
  1278. p = g_stacknxt;
  1279. g_stacknxt += aligned;
  1280. g_stacknleft -= aligned;
  1281. return p;
  1282. }
  1283. static void *
  1284. stzalloc(size_t nbytes)
  1285. {
  1286. return memset(stalloc(nbytes), 0, nbytes);
  1287. }
  1288. static void
  1289. stunalloc(void *p)
  1290. {
  1291. #if DEBUG
  1292. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1293. write(STDERR_FILENO, "stunalloc\n", 10);
  1294. abort();
  1295. }
  1296. #endif
  1297. g_stacknleft += g_stacknxt - (char *)p;
  1298. g_stacknxt = p;
  1299. }
  1300. /*
  1301. * Like strdup but works with the ash stack.
  1302. */
  1303. static char *
  1304. ststrdup(const char *p)
  1305. {
  1306. size_t len = strlen(p) + 1;
  1307. return memcpy(stalloc(len), p, len);
  1308. }
  1309. static void
  1310. setstackmark(struct stackmark *mark)
  1311. {
  1312. mark->stackp = g_stackp;
  1313. mark->stacknxt = g_stacknxt;
  1314. mark->stacknleft = g_stacknleft;
  1315. mark->marknext = markp;
  1316. markp = mark;
  1317. }
  1318. static void
  1319. popstackmark(struct stackmark *mark)
  1320. {
  1321. struct stack_block *sp;
  1322. if (!mark->stackp)
  1323. return;
  1324. INT_OFF;
  1325. markp = mark->marknext;
  1326. while (g_stackp != mark->stackp) {
  1327. sp = g_stackp;
  1328. g_stackp = sp->prev;
  1329. free(sp);
  1330. }
  1331. g_stacknxt = mark->stacknxt;
  1332. g_stacknleft = mark->stacknleft;
  1333. sstrend = mark->stacknxt + mark->stacknleft;
  1334. INT_ON;
  1335. }
  1336. /*
  1337. * When the parser reads in a string, it wants to stick the string on the
  1338. * stack and only adjust the stack pointer when it knows how big the
  1339. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1340. * of space on top of the stack and stackblocklen returns the length of
  1341. * this block. Growstackblock will grow this space by at least one byte,
  1342. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1343. * part of the block that has been used.
  1344. */
  1345. static void
  1346. growstackblock(void)
  1347. {
  1348. size_t newlen;
  1349. newlen = g_stacknleft * 2;
  1350. if (newlen < g_stacknleft)
  1351. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1352. if (newlen < 128)
  1353. newlen += 128;
  1354. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1355. struct stack_block *oldstackp;
  1356. struct stackmark *xmark;
  1357. struct stack_block *sp;
  1358. struct stack_block *prevstackp;
  1359. size_t grosslen;
  1360. INT_OFF;
  1361. oldstackp = g_stackp;
  1362. sp = g_stackp;
  1363. prevstackp = sp->prev;
  1364. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1365. sp = ckrealloc(sp, grosslen);
  1366. sp->prev = prevstackp;
  1367. g_stackp = sp;
  1368. g_stacknxt = sp->space;
  1369. g_stacknleft = newlen;
  1370. sstrend = sp->space + newlen;
  1371. /*
  1372. * Stack marks pointing to the start of the old block
  1373. * must be relocated to point to the new block
  1374. */
  1375. xmark = markp;
  1376. while (xmark != NULL && xmark->stackp == oldstackp) {
  1377. xmark->stackp = g_stackp;
  1378. xmark->stacknxt = g_stacknxt;
  1379. xmark->stacknleft = g_stacknleft;
  1380. xmark = xmark->marknext;
  1381. }
  1382. INT_ON;
  1383. } else {
  1384. char *oldspace = g_stacknxt;
  1385. size_t oldlen = g_stacknleft;
  1386. char *p = stalloc(newlen);
  1387. /* free the space we just allocated */
  1388. g_stacknxt = memcpy(p, oldspace, oldlen);
  1389. g_stacknleft += newlen;
  1390. }
  1391. }
  1392. static void
  1393. grabstackblock(size_t len)
  1394. {
  1395. len = SHELL_ALIGN(len);
  1396. g_stacknxt += len;
  1397. g_stacknleft -= len;
  1398. }
  1399. /*
  1400. * The following routines are somewhat easier to use than the above.
  1401. * The user declares a variable of type STACKSTR, which may be declared
  1402. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1403. * the user uses the macro STPUTC to add characters to the string. In
  1404. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1405. * grown as necessary. When the user is done, she can just leave the
  1406. * string there and refer to it using stackblock(). Or she can allocate
  1407. * the space for it using grabstackstr(). If it is necessary to allow
  1408. * someone else to use the stack temporarily and then continue to grow
  1409. * the string, the user should use grabstack to allocate the space, and
  1410. * then call ungrabstr(p) to return to the previous mode of operation.
  1411. *
  1412. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1413. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1414. * is space for at least one character.
  1415. */
  1416. static void *
  1417. growstackstr(void)
  1418. {
  1419. size_t len = stackblocksize();
  1420. if (herefd >= 0 && len >= 1024) {
  1421. full_write(herefd, stackblock(), len);
  1422. return stackblock();
  1423. }
  1424. growstackblock();
  1425. return (char *)stackblock() + len;
  1426. }
  1427. /*
  1428. * Called from CHECKSTRSPACE.
  1429. */
  1430. static char *
  1431. makestrspace(size_t newlen, char *p)
  1432. {
  1433. size_t len = p - g_stacknxt;
  1434. size_t size = stackblocksize();
  1435. for (;;) {
  1436. size_t nleft;
  1437. size = stackblocksize();
  1438. nleft = size - len;
  1439. if (nleft >= newlen)
  1440. break;
  1441. growstackblock();
  1442. }
  1443. return (char *)stackblock() + len;
  1444. }
  1445. static char *
  1446. stack_nputstr(const char *s, size_t n, char *p)
  1447. {
  1448. p = makestrspace(n, p);
  1449. p = (char *)memcpy(p, s, n) + n;
  1450. return p;
  1451. }
  1452. static char *
  1453. stack_putstr(const char *s, char *p)
  1454. {
  1455. return stack_nputstr(s, strlen(s), p);
  1456. }
  1457. static char *
  1458. _STPUTC(int c, char *p)
  1459. {
  1460. if (p == sstrend)
  1461. p = growstackstr();
  1462. *p++ = c;
  1463. return p;
  1464. }
  1465. #define STARTSTACKSTR(p) ((p) = stackblock())
  1466. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1467. #define CHECKSTRSPACE(n, p) do { \
  1468. char *q = (p); \
  1469. size_t l = (n); \
  1470. size_t m = sstrend - q; \
  1471. if (l > m) \
  1472. (p) = makestrspace(l, q); \
  1473. } while (0)
  1474. #define USTPUTC(c, p) (*(p)++ = (c))
  1475. #define STACKSTRNUL(p) do { \
  1476. if ((p) == sstrend) \
  1477. (p) = growstackstr(); \
  1478. *(p) = '\0'; \
  1479. } while (0)
  1480. #define STUNPUTC(p) (--(p))
  1481. #define STTOPC(p) ((p)[-1])
  1482. #define STADJUST(amount, p) ((p) += (amount))
  1483. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1484. #define ungrabstackstr(s, p) stunalloc(s)
  1485. #define stackstrend() ((void *)sstrend)
  1486. /* ============ String helpers */
  1487. /*
  1488. * prefix -- see if pfx is a prefix of string.
  1489. */
  1490. static char *
  1491. prefix(const char *string, const char *pfx)
  1492. {
  1493. while (*pfx) {
  1494. if (*pfx++ != *string++)
  1495. return NULL;
  1496. }
  1497. return (char *) string;
  1498. }
  1499. /*
  1500. * Check for a valid number. This should be elsewhere.
  1501. */
  1502. static int
  1503. is_number(const char *p)
  1504. {
  1505. do {
  1506. if (!isdigit(*p))
  1507. return 0;
  1508. } while (*++p != '\0');
  1509. return 1;
  1510. }
  1511. /*
  1512. * Convert a string of digits to an integer, printing an error message on
  1513. * failure.
  1514. */
  1515. static int
  1516. number(const char *s)
  1517. {
  1518. if (!is_number(s))
  1519. ash_msg_and_raise_error(msg_illnum, s);
  1520. return atoi(s);
  1521. }
  1522. /*
  1523. * Produce a possibly single quoted string suitable as input to the shell.
  1524. * The return string is allocated on the stack.
  1525. */
  1526. static char *
  1527. single_quote(const char *s)
  1528. {
  1529. char *p;
  1530. STARTSTACKSTR(p);
  1531. do {
  1532. char *q;
  1533. size_t len;
  1534. len = strchrnul(s, '\'') - s;
  1535. q = p = makestrspace(len + 3, p);
  1536. *q++ = '\'';
  1537. q = (char *)memcpy(q, s, len) + len;
  1538. *q++ = '\'';
  1539. s += len;
  1540. STADJUST(q - p, p);
  1541. if (*s != '\'')
  1542. break;
  1543. len = 0;
  1544. do len++; while (*++s == '\'');
  1545. q = p = makestrspace(len + 3, p);
  1546. *q++ = '"';
  1547. q = (char *)memcpy(q, s - len, len) + len;
  1548. *q++ = '"';
  1549. STADJUST(q - p, p);
  1550. } while (*s);
  1551. USTPUTC('\0', p);
  1552. return stackblock();
  1553. }
  1554. /* ============ nextopt */
  1555. static char **argptr; /* argument list for builtin commands */
  1556. static char *optionarg; /* set by nextopt (like getopt) */
  1557. static char *optptr; /* used by nextopt */
  1558. /*
  1559. * XXX - should get rid of. Have all builtins use getopt(3).
  1560. * The library getopt must have the BSD extension static variable
  1561. * "optreset", otherwise it can't be used within the shell safely.
  1562. *
  1563. * Standard option processing (a la getopt) for builtin routines.
  1564. * The only argument that is passed to nextopt is the option string;
  1565. * the other arguments are unnecessary. It returns the character,
  1566. * or '\0' on end of input.
  1567. */
  1568. static int
  1569. nextopt(const char *optstring)
  1570. {
  1571. char *p;
  1572. const char *q;
  1573. char c;
  1574. p = optptr;
  1575. if (p == NULL || *p == '\0') {
  1576. /* We ate entire "-param", take next one */
  1577. p = *argptr;
  1578. if (p == NULL)
  1579. return '\0';
  1580. if (*p != '-')
  1581. return '\0';
  1582. if (*++p == '\0') /* just "-" ? */
  1583. return '\0';
  1584. argptr++;
  1585. if (LONE_DASH(p)) /* "--" ? */
  1586. return '\0';
  1587. /* p => next "-param" */
  1588. }
  1589. /* p => some option char in the middle of a "-param" */
  1590. c = *p++;
  1591. for (q = optstring; *q != c;) {
  1592. if (*q == '\0')
  1593. ash_msg_and_raise_error("illegal option -%c", c);
  1594. if (*++q == ':')
  1595. q++;
  1596. }
  1597. if (*++q == ':') {
  1598. if (*p == '\0') {
  1599. p = *argptr++;
  1600. if (p == NULL)
  1601. ash_msg_and_raise_error("no arg for -%c option", c);
  1602. }
  1603. optionarg = p;
  1604. p = NULL;
  1605. }
  1606. optptr = p;
  1607. return c;
  1608. }
  1609. /* ============ Shell variables */
  1610. /*
  1611. * The parsefile structure pointed to by the global variable parsefile
  1612. * contains information about the current file being read.
  1613. */
  1614. struct shparam {
  1615. int nparam; /* # of positional parameters (without $0) */
  1616. #if ENABLE_ASH_GETOPTS
  1617. int optind; /* next parameter to be processed by getopts */
  1618. int optoff; /* used by getopts */
  1619. #endif
  1620. unsigned char malloced; /* if parameter list dynamically allocated */
  1621. char **p; /* parameter list */
  1622. };
  1623. /*
  1624. * Free the list of positional parameters.
  1625. */
  1626. static void
  1627. freeparam(volatile struct shparam *param)
  1628. {
  1629. if (param->malloced) {
  1630. char **ap, **ap1;
  1631. ap = ap1 = param->p;
  1632. while (*ap)
  1633. free(*ap++);
  1634. free(ap1);
  1635. }
  1636. }
  1637. #if ENABLE_ASH_GETOPTS
  1638. static void FAST_FUNC getoptsreset(const char *value);
  1639. #endif
  1640. struct var {
  1641. struct var *next; /* next entry in hash list */
  1642. int flags; /* flags are defined above */
  1643. const char *var_text; /* name=value */
  1644. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1645. /* the variable gets set/unset */
  1646. };
  1647. struct localvar {
  1648. struct localvar *next; /* next local variable in list */
  1649. struct var *vp; /* the variable that was made local */
  1650. int flags; /* saved flags */
  1651. const char *text; /* saved text */
  1652. };
  1653. /* flags */
  1654. #define VEXPORT 0x01 /* variable is exported */
  1655. #define VREADONLY 0x02 /* variable cannot be modified */
  1656. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1657. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1658. #define VSTACK 0x10 /* text is allocated on the stack */
  1659. #define VUNSET 0x20 /* the variable is not set */
  1660. #define VNOFUNC 0x40 /* don't call the callback function */
  1661. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1662. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1663. #if ENABLE_ASH_RANDOM_SUPPORT
  1664. # define VDYNAMIC 0x200 /* dynamic variable */
  1665. #else
  1666. # define VDYNAMIC 0
  1667. #endif
  1668. /* Need to be before varinit_data[] */
  1669. #if ENABLE_LOCALE_SUPPORT
  1670. static void FAST_FUNC
  1671. change_lc_all(const char *value)
  1672. {
  1673. if (value && *value != '\0')
  1674. setlocale(LC_ALL, value);
  1675. }
  1676. static void FAST_FUNC
  1677. change_lc_ctype(const char *value)
  1678. {
  1679. if (value && *value != '\0')
  1680. setlocale(LC_CTYPE, value);
  1681. }
  1682. #endif
  1683. #if ENABLE_ASH_MAIL
  1684. static void chkmail(void);
  1685. static void changemail(const char *var_value) FAST_FUNC;
  1686. #else
  1687. # define chkmail() ((void)0)
  1688. #endif
  1689. static void changepath(const char *) FAST_FUNC;
  1690. #if ENABLE_ASH_RANDOM_SUPPORT
  1691. static void change_random(const char *) FAST_FUNC;
  1692. #endif
  1693. static const struct {
  1694. int flags;
  1695. const char *var_text;
  1696. void (*var_func)(const char *) FAST_FUNC;
  1697. } varinit_data[] = {
  1698. /*
  1699. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1700. * some environment strings may be constant.
  1701. */
  1702. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1703. #if ENABLE_ASH_MAIL
  1704. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1705. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1706. #endif
  1707. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1708. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1709. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1710. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1711. #if ENABLE_ASH_GETOPTS
  1712. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1713. #endif
  1714. #if ENABLE_ASH_RANDOM_SUPPORT
  1715. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1716. #endif
  1717. #if ENABLE_LOCALE_SUPPORT
  1718. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1719. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1720. #endif
  1721. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1722. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1723. #endif
  1724. };
  1725. struct redirtab;
  1726. struct globals_var {
  1727. struct shparam shellparam; /* $@ current positional parameters */
  1728. struct redirtab *redirlist;
  1729. int g_nullredirs;
  1730. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1731. struct var *vartab[VTABSIZE];
  1732. struct var varinit[ARRAY_SIZE(varinit_data)];
  1733. };
  1734. extern struct globals_var *const ash_ptr_to_globals_var;
  1735. #define G_var (*ash_ptr_to_globals_var)
  1736. #define shellparam (G_var.shellparam )
  1737. //#define redirlist (G_var.redirlist )
  1738. #define g_nullredirs (G_var.g_nullredirs )
  1739. #define preverrout_fd (G_var.preverrout_fd)
  1740. #define vartab (G_var.vartab )
  1741. #define varinit (G_var.varinit )
  1742. #define INIT_G_var() do { \
  1743. unsigned i; \
  1744. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1745. barrier(); \
  1746. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1747. varinit[i].flags = varinit_data[i].flags; \
  1748. varinit[i].var_text = varinit_data[i].var_text; \
  1749. varinit[i].var_func = varinit_data[i].var_func; \
  1750. } \
  1751. } while (0)
  1752. #define vifs varinit[0]
  1753. #if ENABLE_ASH_MAIL
  1754. # define vmail (&vifs)[1]
  1755. # define vmpath (&vmail)[1]
  1756. # define vpath (&vmpath)[1]
  1757. #else
  1758. # define vpath (&vifs)[1]
  1759. #endif
  1760. #define vps1 (&vpath)[1]
  1761. #define vps2 (&vps1)[1]
  1762. #define vps4 (&vps2)[1]
  1763. #if ENABLE_ASH_GETOPTS
  1764. # define voptind (&vps4)[1]
  1765. # if ENABLE_ASH_RANDOM_SUPPORT
  1766. # define vrandom (&voptind)[1]
  1767. # endif
  1768. #else
  1769. # if ENABLE_ASH_RANDOM_SUPPORT
  1770. # define vrandom (&vps4)[1]
  1771. # endif
  1772. #endif
  1773. /*
  1774. * The following macros access the values of the above variables.
  1775. * They have to skip over the name. They return the null string
  1776. * for unset variables.
  1777. */
  1778. #define ifsval() (vifs.var_text + 4)
  1779. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1780. #if ENABLE_ASH_MAIL
  1781. # define mailval() (vmail.var_text + 5)
  1782. # define mpathval() (vmpath.var_text + 9)
  1783. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1784. #endif
  1785. #define pathval() (vpath.var_text + 5)
  1786. #define ps1val() (vps1.var_text + 4)
  1787. #define ps2val() (vps2.var_text + 4)
  1788. #define ps4val() (vps4.var_text + 4)
  1789. #if ENABLE_ASH_GETOPTS
  1790. # define optindval() (voptind.var_text + 7)
  1791. #endif
  1792. #if ENABLE_ASH_GETOPTS
  1793. static void FAST_FUNC
  1794. getoptsreset(const char *value)
  1795. {
  1796. shellparam.optind = number(value);
  1797. shellparam.optoff = -1;
  1798. }
  1799. #endif
  1800. /*
  1801. * Compares two strings up to the first = or '\0'. The first
  1802. * string must be terminated by '='; the second may be terminated by
  1803. * either '=' or '\0'.
  1804. */
  1805. static int
  1806. varcmp(const char *p, const char *q)
  1807. {
  1808. int c, d;
  1809. while ((c = *p) == (d = *q)) {
  1810. if (c == '\0' || c == '=')
  1811. goto out;
  1812. p++;
  1813. q++;
  1814. }
  1815. if (c == '=')
  1816. c = '\0';
  1817. if (d == '=')
  1818. d = '\0';
  1819. out:
  1820. return c - d;
  1821. }
  1822. /*
  1823. * Find the appropriate entry in the hash table from the name.
  1824. */
  1825. static struct var **
  1826. hashvar(const char *p)
  1827. {
  1828. unsigned hashval;
  1829. hashval = ((unsigned char) *p) << 4;
  1830. while (*p && *p != '=')
  1831. hashval += (unsigned char) *p++;
  1832. return &vartab[hashval % VTABSIZE];
  1833. }
  1834. static int
  1835. vpcmp(const void *a, const void *b)
  1836. {
  1837. return varcmp(*(const char **)a, *(const char **)b);
  1838. }
  1839. /*
  1840. * This routine initializes the builtin variables.
  1841. */
  1842. static void
  1843. initvar(void)
  1844. {
  1845. struct var *vp;
  1846. struct var *end;
  1847. struct var **vpp;
  1848. /*
  1849. * PS1 depends on uid
  1850. */
  1851. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1852. vps1.var_text = "PS1=\\w \\$ ";
  1853. #else
  1854. if (!geteuid())
  1855. vps1.var_text = "PS1=# ";
  1856. #endif
  1857. vp = varinit;
  1858. end = vp + ARRAY_SIZE(varinit);
  1859. do {
  1860. vpp = hashvar(vp->var_text);
  1861. vp->next = *vpp;
  1862. *vpp = vp;
  1863. } while (++vp < end);
  1864. }
  1865. static struct var **
  1866. findvar(struct var **vpp, const char *name)
  1867. {
  1868. for (; *vpp; vpp = &(*vpp)->next) {
  1869. if (varcmp((*vpp)->var_text, name) == 0) {
  1870. break;
  1871. }
  1872. }
  1873. return vpp;
  1874. }
  1875. /*
  1876. * Find the value of a variable. Returns NULL if not set.
  1877. */
  1878. static const char* FAST_FUNC
  1879. lookupvar(const char *name)
  1880. {
  1881. struct var *v;
  1882. v = *findvar(hashvar(name), name);
  1883. if (v) {
  1884. #if ENABLE_ASH_RANDOM_SUPPORT
  1885. /*
  1886. * Dynamic variables are implemented roughly the same way they are
  1887. * in bash. Namely, they're "special" so long as they aren't unset.
  1888. * As soon as they're unset, they're no longer dynamic, and dynamic
  1889. * lookup will no longer happen at that point. -- PFM.
  1890. */
  1891. if (v->flags & VDYNAMIC)
  1892. v->var_func(NULL);
  1893. #endif
  1894. if (!(v->flags & VUNSET))
  1895. return var_end(v->var_text);
  1896. }
  1897. return NULL;
  1898. }
  1899. static void reinit_unicode_for_ash(void)
  1900. {
  1901. /* Unicode support should be activated even if LANG is set
  1902. * _during_ shell execution, not only if it was set when
  1903. * shell was started. Therefore, re-check LANG every time:
  1904. */
  1905. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1906. || ENABLE_UNICODE_USING_LOCALE
  1907. ) {
  1908. const char *s = lookupvar("LC_ALL");
  1909. if (!s) s = lookupvar("LC_CTYPE");
  1910. if (!s) s = lookupvar("LANG");
  1911. reinit_unicode(s);
  1912. }
  1913. }
  1914. /*
  1915. * Search the environment of a builtin command.
  1916. */
  1917. static const char *
  1918. bltinlookup(const char *name)
  1919. {
  1920. struct strlist *sp;
  1921. for (sp = cmdenviron; sp; sp = sp->next) {
  1922. if (varcmp(sp->text, name) == 0)
  1923. return var_end(sp->text);
  1924. }
  1925. return lookupvar(name);
  1926. }
  1927. /*
  1928. * Same as setvar except that the variable and value are passed in
  1929. * the first argument as name=value. Since the first argument will
  1930. * be actually stored in the table, it should not be a string that
  1931. * will go away.
  1932. * Called with interrupts off.
  1933. */
  1934. static void
  1935. setvareq(char *s, int flags)
  1936. {
  1937. struct var *vp, **vpp;
  1938. vpp = hashvar(s);
  1939. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1940. vp = *findvar(vpp, s);
  1941. if (vp) {
  1942. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1943. const char *n;
  1944. if (flags & VNOSAVE)
  1945. free(s);
  1946. n = vp->var_text;
  1947. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1948. }
  1949. if (flags & VNOSET)
  1950. return;
  1951. if (vp->var_func && !(flags & VNOFUNC))
  1952. vp->var_func(var_end(s));
  1953. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  1954. free((char*)vp->var_text);
  1955. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1956. } else {
  1957. /* variable s is not found */
  1958. if (flags & VNOSET)
  1959. return;
  1960. vp = ckzalloc(sizeof(*vp));
  1961. vp->next = *vpp;
  1962. /*vp->func = NULL; - ckzalloc did it */
  1963. *vpp = vp;
  1964. }
  1965. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1966. s = ckstrdup(s);
  1967. vp->var_text = s;
  1968. vp->flags = flags;
  1969. }
  1970. /*
  1971. * Set the value of a variable. The flags argument is ored with the
  1972. * flags of the variable. If val is NULL, the variable is unset.
  1973. */
  1974. static void
  1975. setvar(const char *name, const char *val, int flags)
  1976. {
  1977. const char *q;
  1978. char *p;
  1979. char *nameeq;
  1980. size_t namelen;
  1981. size_t vallen;
  1982. q = endofname(name);
  1983. p = strchrnul(q, '=');
  1984. namelen = p - name;
  1985. if (!namelen || p != q)
  1986. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1987. vallen = 0;
  1988. if (val == NULL) {
  1989. flags |= VUNSET;
  1990. } else {
  1991. vallen = strlen(val);
  1992. }
  1993. INT_OFF;
  1994. nameeq = ckmalloc(namelen + vallen + 2);
  1995. p = memcpy(nameeq, name, namelen) + namelen;
  1996. if (val) {
  1997. *p++ = '=';
  1998. p = memcpy(p, val, vallen) + vallen;
  1999. }
  2000. *p = '\0';
  2001. setvareq(nameeq, flags | VNOSAVE);
  2002. INT_ON;
  2003. }
  2004. static void FAST_FUNC
  2005. setvar0(const char *name, const char *val)
  2006. {
  2007. setvar(name, val, 0);
  2008. }
  2009. #if ENABLE_ASH_GETOPTS
  2010. /*
  2011. * Safe version of setvar, returns 1 on success 0 on failure.
  2012. */
  2013. static int
  2014. setvarsafe(const char *name, const char *val, int flags)
  2015. {
  2016. int err;
  2017. volatile int saveint;
  2018. struct jmploc *volatile savehandler = exception_handler;
  2019. struct jmploc jmploc;
  2020. SAVE_INT(saveint);
  2021. if (setjmp(jmploc.loc))
  2022. err = 1;
  2023. else {
  2024. exception_handler = &jmploc;
  2025. setvar(name, val, flags);
  2026. err = 0;
  2027. }
  2028. exception_handler = savehandler;
  2029. RESTORE_INT(saveint);
  2030. return err;
  2031. }
  2032. #endif
  2033. /*
  2034. * Unset the specified variable.
  2035. */
  2036. static int
  2037. unsetvar(const char *s)
  2038. {
  2039. struct var **vpp;
  2040. struct var *vp;
  2041. int retval;
  2042. vpp = findvar(hashvar(s), s);
  2043. vp = *vpp;
  2044. retval = 2;
  2045. if (vp) {
  2046. int flags = vp->flags;
  2047. retval = 1;
  2048. if (flags & VREADONLY)
  2049. goto out;
  2050. #if ENABLE_ASH_RANDOM_SUPPORT
  2051. vp->flags &= ~VDYNAMIC;
  2052. #endif
  2053. if (flags & VUNSET)
  2054. goto ok;
  2055. if ((flags & VSTRFIXED) == 0) {
  2056. INT_OFF;
  2057. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  2058. free((char*)vp->var_text);
  2059. *vpp = vp->next;
  2060. free(vp);
  2061. INT_ON;
  2062. } else {
  2063. setvar0(s, NULL);
  2064. vp->flags &= ~VEXPORT;
  2065. }
  2066. ok:
  2067. retval = 0;
  2068. }
  2069. out:
  2070. return retval;
  2071. }
  2072. /*
  2073. * Process a linked list of variable assignments.
  2074. */
  2075. static void
  2076. listsetvar(struct strlist *list_set_var, int flags)
  2077. {
  2078. struct strlist *lp = list_set_var;
  2079. if (!lp)
  2080. return;
  2081. INT_OFF;
  2082. do {
  2083. setvareq(lp->text, flags);
  2084. lp = lp->next;
  2085. } while (lp);
  2086. INT_ON;
  2087. }
  2088. /*
  2089. * Generate a list of variables satisfying the given conditions.
  2090. */
  2091. static char **
  2092. listvars(int on, int off, char ***end)
  2093. {
  2094. struct var **vpp;
  2095. struct var *vp;
  2096. char **ep;
  2097. int mask;
  2098. STARTSTACKSTR(ep);
  2099. vpp = vartab;
  2100. mask = on | off;
  2101. do {
  2102. for (vp = *vpp; vp; vp = vp->next) {
  2103. if ((vp->flags & mask) == on) {
  2104. if (ep == stackstrend())
  2105. ep = growstackstr();
  2106. *ep++ = (char*)vp->var_text;
  2107. }
  2108. }
  2109. } while (++vpp < vartab + VTABSIZE);
  2110. if (ep == stackstrend())
  2111. ep = growstackstr();
  2112. if (end)
  2113. *end = ep;
  2114. *ep++ = NULL;
  2115. return grabstackstr(ep);
  2116. }
  2117. /* ============ Path search helper
  2118. *
  2119. * The variable path (passed by reference) should be set to the start
  2120. * of the path before the first call; path_advance will update
  2121. * this value as it proceeds. Successive calls to path_advance will return
  2122. * the possible path expansions in sequence. If an option (indicated by
  2123. * a percent sign) appears in the path entry then the global variable
  2124. * pathopt will be set to point to it; otherwise pathopt will be set to
  2125. * NULL.
  2126. */
  2127. static const char *pathopt; /* set by path_advance */
  2128. static char *
  2129. path_advance(const char **path, const char *name)
  2130. {
  2131. const char *p;
  2132. char *q;
  2133. const char *start;
  2134. size_t len;
  2135. if (*path == NULL)
  2136. return NULL;
  2137. start = *path;
  2138. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2139. continue;
  2140. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2141. while (stackblocksize() < len)
  2142. growstackblock();
  2143. q = stackblock();
  2144. if (p != start) {
  2145. memcpy(q, start, p - start);
  2146. q += p - start;
  2147. *q++ = '/';
  2148. }
  2149. strcpy(q, name);
  2150. pathopt = NULL;
  2151. if (*p == '%') {
  2152. pathopt = ++p;
  2153. while (*p && *p != ':')
  2154. p++;
  2155. }
  2156. if (*p == ':')
  2157. *path = p + 1;
  2158. else
  2159. *path = NULL;
  2160. return stalloc(len);
  2161. }
  2162. /* ============ Prompt */
  2163. static smallint doprompt; /* if set, prompt the user */
  2164. static smallint needprompt; /* true if interactive and at start of line */
  2165. #if ENABLE_FEATURE_EDITING
  2166. static line_input_t *line_input_state;
  2167. static const char *cmdedit_prompt;
  2168. static void
  2169. putprompt(const char *s)
  2170. {
  2171. if (ENABLE_ASH_EXPAND_PRMT) {
  2172. free((char*)cmdedit_prompt);
  2173. cmdedit_prompt = ckstrdup(s);
  2174. return;
  2175. }
  2176. cmdedit_prompt = s;
  2177. }
  2178. #else
  2179. static void
  2180. putprompt(const char *s)
  2181. {
  2182. out2str(s);
  2183. }
  2184. #endif
  2185. #if ENABLE_ASH_EXPAND_PRMT
  2186. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2187. static const char *expandstr(const char *ps);
  2188. #else
  2189. #define expandstr(s) s
  2190. #endif
  2191. static void
  2192. setprompt_if(smallint do_set, int whichprompt)
  2193. {
  2194. const char *prompt;
  2195. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2196. if (!do_set)
  2197. return;
  2198. needprompt = 0;
  2199. switch (whichprompt) {
  2200. case 1:
  2201. prompt = ps1val();
  2202. break;
  2203. case 2:
  2204. prompt = ps2val();
  2205. break;
  2206. default: /* 0 */
  2207. prompt = nullstr;
  2208. }
  2209. #if ENABLE_ASH_EXPAND_PRMT
  2210. setstackmark(&smark);
  2211. stalloc(stackblocksize());
  2212. #endif
  2213. putprompt(expandstr(prompt));
  2214. #if ENABLE_ASH_EXPAND_PRMT
  2215. popstackmark(&smark);
  2216. #endif
  2217. }
  2218. /* ============ The cd and pwd commands */
  2219. #define CD_PHYSICAL 1
  2220. #define CD_PRINT 2
  2221. static int
  2222. cdopt(void)
  2223. {
  2224. int flags = 0;
  2225. int i, j;
  2226. j = 'L';
  2227. while ((i = nextopt("LP")) != '\0') {
  2228. if (i != j) {
  2229. flags ^= CD_PHYSICAL;
  2230. j = i;
  2231. }
  2232. }
  2233. return flags;
  2234. }
  2235. /*
  2236. * Update curdir (the name of the current directory) in response to a
  2237. * cd command.
  2238. */
  2239. static const char *
  2240. updatepwd(const char *dir)
  2241. {
  2242. char *new;
  2243. char *p;
  2244. char *cdcomppath;
  2245. const char *lim;
  2246. cdcomppath = ststrdup(dir);
  2247. STARTSTACKSTR(new);
  2248. if (*dir != '/') {
  2249. if (curdir == nullstr)
  2250. return 0;
  2251. new = stack_putstr(curdir, new);
  2252. }
  2253. new = makestrspace(strlen(dir) + 2, new);
  2254. lim = (char *)stackblock() + 1;
  2255. if (*dir != '/') {
  2256. if (new[-1] != '/')
  2257. USTPUTC('/', new);
  2258. if (new > lim && *lim == '/')
  2259. lim++;
  2260. } else {
  2261. USTPUTC('/', new);
  2262. cdcomppath++;
  2263. if (dir[1] == '/' && dir[2] != '/') {
  2264. USTPUTC('/', new);
  2265. cdcomppath++;
  2266. lim++;
  2267. }
  2268. }
  2269. p = strtok(cdcomppath, "/");
  2270. while (p) {
  2271. switch (*p) {
  2272. case '.':
  2273. if (p[1] == '.' && p[2] == '\0') {
  2274. while (new > lim) {
  2275. STUNPUTC(new);
  2276. if (new[-1] == '/')
  2277. break;
  2278. }
  2279. break;
  2280. }
  2281. if (p[1] == '\0')
  2282. break;
  2283. /* fall through */
  2284. default:
  2285. new = stack_putstr(p, new);
  2286. USTPUTC('/', new);
  2287. }
  2288. p = strtok(0, "/");
  2289. }
  2290. if (new > lim)
  2291. STUNPUTC(new);
  2292. *new = 0;
  2293. return stackblock();
  2294. }
  2295. /*
  2296. * Find out what the current directory is. If we already know the current
  2297. * directory, this routine returns immediately.
  2298. */
  2299. static char *
  2300. getpwd(void)
  2301. {
  2302. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2303. return dir ? dir : nullstr;
  2304. }
  2305. static void
  2306. setpwd(const char *val, int setold)
  2307. {
  2308. char *oldcur, *dir;
  2309. oldcur = dir = curdir;
  2310. if (setold) {
  2311. setvar("OLDPWD", oldcur, VEXPORT);
  2312. }
  2313. INT_OFF;
  2314. if (physdir != nullstr) {
  2315. if (physdir != oldcur)
  2316. free(physdir);
  2317. physdir = nullstr;
  2318. }
  2319. if (oldcur == val || !val) {
  2320. char *s = getpwd();
  2321. physdir = s;
  2322. if (!val)
  2323. dir = s;
  2324. } else
  2325. dir = ckstrdup(val);
  2326. if (oldcur != dir && oldcur != nullstr) {
  2327. free(oldcur);
  2328. }
  2329. curdir = dir;
  2330. INT_ON;
  2331. setvar("PWD", dir, VEXPORT);
  2332. }
  2333. static void hashcd(void);
  2334. /*
  2335. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2336. * know that the current directory has changed.
  2337. */
  2338. static int
  2339. docd(const char *dest, int flags)
  2340. {
  2341. const char *dir = NULL;
  2342. int err;
  2343. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2344. INT_OFF;
  2345. if (!(flags & CD_PHYSICAL)) {
  2346. dir = updatepwd(dest);
  2347. if (dir)
  2348. dest = dir;
  2349. }
  2350. err = chdir(dest);
  2351. if (err)
  2352. goto out;
  2353. setpwd(dir, 1);
  2354. hashcd();
  2355. out:
  2356. INT_ON;
  2357. return err;
  2358. }
  2359. static int FAST_FUNC
  2360. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2361. {
  2362. const char *dest;
  2363. const char *path;
  2364. const char *p;
  2365. char c;
  2366. struct stat statb;
  2367. int flags;
  2368. flags = cdopt();
  2369. dest = *argptr;
  2370. if (!dest)
  2371. dest = bltinlookup("HOME");
  2372. else if (LONE_DASH(dest)) {
  2373. dest = bltinlookup("OLDPWD");
  2374. flags |= CD_PRINT;
  2375. }
  2376. if (!dest)
  2377. dest = nullstr;
  2378. if (*dest == '/')
  2379. goto step7;
  2380. if (*dest == '.') {
  2381. c = dest[1];
  2382. dotdot:
  2383. switch (c) {
  2384. case '\0':
  2385. case '/':
  2386. goto step6;
  2387. case '.':
  2388. c = dest[2];
  2389. if (c != '.')
  2390. goto dotdot;
  2391. }
  2392. }
  2393. if (!*dest)
  2394. dest = ".";
  2395. path = bltinlookup("CDPATH");
  2396. if (!path) {
  2397. step6:
  2398. step7:
  2399. p = dest;
  2400. goto docd;
  2401. }
  2402. do {
  2403. c = *path;
  2404. p = path_advance(&path, dest);
  2405. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2406. if (c && c != ':')
  2407. flags |= CD_PRINT;
  2408. docd:
  2409. if (!docd(p, flags))
  2410. goto out;
  2411. break;
  2412. }
  2413. } while (path);
  2414. ash_msg_and_raise_error("can't cd to %s", dest);
  2415. /* NOTREACHED */
  2416. out:
  2417. if (flags & CD_PRINT)
  2418. out1fmt("%s\n", curdir);
  2419. return 0;
  2420. }
  2421. static int FAST_FUNC
  2422. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2423. {
  2424. int flags;
  2425. const char *dir = curdir;
  2426. flags = cdopt();
  2427. if (flags) {
  2428. if (physdir == nullstr)
  2429. setpwd(dir, 0);
  2430. dir = physdir;
  2431. }
  2432. out1fmt("%s\n", dir);
  2433. return 0;
  2434. }
  2435. /* ============ ... */
  2436. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2437. /* Syntax classes */
  2438. #define CWORD 0 /* character is nothing special */
  2439. #define CNL 1 /* newline character */
  2440. #define CBACK 2 /* a backslash character */
  2441. #define CSQUOTE 3 /* single quote */
  2442. #define CDQUOTE 4 /* double quote */
  2443. #define CENDQUOTE 5 /* a terminating quote */
  2444. #define CBQUOTE 6 /* backwards single quote */
  2445. #define CVAR 7 /* a dollar sign */
  2446. #define CENDVAR 8 /* a '}' character */
  2447. #define CLP 9 /* a left paren in arithmetic */
  2448. #define CRP 10 /* a right paren in arithmetic */
  2449. #define CENDFILE 11 /* end of file */
  2450. #define CCTL 12 /* like CWORD, except it must be escaped */
  2451. #define CSPCL 13 /* these terminate a word */
  2452. #define CIGN 14 /* character should be ignored */
  2453. #define PEOF 256
  2454. #if ENABLE_ASH_ALIAS
  2455. # define PEOA 257
  2456. #endif
  2457. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2458. #if ENABLE_SH_MATH_SUPPORT
  2459. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2460. #else
  2461. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2462. #endif
  2463. static const uint16_t S_I_T[] = {
  2464. #if ENABLE_ASH_ALIAS
  2465. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2466. #endif
  2467. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2468. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2469. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2470. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2471. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2472. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2473. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2474. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2475. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2476. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2477. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2478. #if !USE_SIT_FUNCTION
  2479. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2480. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2481. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2482. #endif
  2483. #undef SIT_ITEM
  2484. };
  2485. /* Constants below must match table above */
  2486. enum {
  2487. #if ENABLE_ASH_ALIAS
  2488. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2489. #endif
  2490. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2491. CNL_CNL_CNL_CNL , /* 2 */
  2492. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2493. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2494. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2495. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2496. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2497. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2498. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2499. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2500. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2501. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2502. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2503. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2504. };
  2505. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2506. * caller must ensure proper cast on it if c is *char_ptr!
  2507. */
  2508. /* Values for syntax param */
  2509. #define BASESYNTAX 0 /* not in quotes */
  2510. #define DQSYNTAX 1 /* in double quotes */
  2511. #define SQSYNTAX 2 /* in single quotes */
  2512. #define ARISYNTAX 3 /* in arithmetic */
  2513. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2514. #if USE_SIT_FUNCTION
  2515. static int
  2516. SIT(int c, int syntax)
  2517. {
  2518. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2519. # if ENABLE_ASH_ALIAS
  2520. static const uint8_t syntax_index_table[] ALIGN1 = {
  2521. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2522. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2523. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2524. 11, 3 /* "}~" */
  2525. };
  2526. # else
  2527. static const uint8_t syntax_index_table[] ALIGN1 = {
  2528. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2529. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2530. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2531. 10, 2 /* "}~" */
  2532. };
  2533. # endif
  2534. const char *s;
  2535. int indx;
  2536. if (c == PEOF)
  2537. return CENDFILE;
  2538. # if ENABLE_ASH_ALIAS
  2539. if (c == PEOA)
  2540. indx = 0;
  2541. else
  2542. # endif
  2543. {
  2544. /* Cast is purely for paranoia here,
  2545. * just in case someone passed signed char to us */
  2546. if ((unsigned char)c >= CTL_FIRST
  2547. && (unsigned char)c <= CTL_LAST
  2548. ) {
  2549. return CCTL;
  2550. }
  2551. s = strchrnul(spec_symbls, c);
  2552. if (*s == '\0')
  2553. return CWORD;
  2554. indx = syntax_index_table[s - spec_symbls];
  2555. }
  2556. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2557. }
  2558. #else /* !USE_SIT_FUNCTION */
  2559. static const uint8_t syntax_index_table[] = {
  2560. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2561. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2571. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2572. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2594. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2595. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2596. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2598. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2600. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2601. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2602. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2603. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2604. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2607. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2609. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2620. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2621. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2622. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2623. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2624. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2625. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2653. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2654. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2655. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2658. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2686. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2687. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2688. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2691. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2692. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2693. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2694. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2695. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2696. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2697. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2698. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2818. # if ENABLE_ASH_ALIAS
  2819. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2820. # endif
  2821. };
  2822. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2823. #endif /* !USE_SIT_FUNCTION */
  2824. /* ============ Alias handling */
  2825. #if ENABLE_ASH_ALIAS
  2826. #define ALIASINUSE 1
  2827. #define ALIASDEAD 2
  2828. struct alias {
  2829. struct alias *next;
  2830. char *name;
  2831. char *val;
  2832. int flag;
  2833. };
  2834. static struct alias **atab; // [ATABSIZE];
  2835. #define INIT_G_alias() do { \
  2836. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2837. } while (0)
  2838. static struct alias **
  2839. __lookupalias(const char *name) {
  2840. unsigned int hashval;
  2841. struct alias **app;
  2842. const char *p;
  2843. unsigned int ch;
  2844. p = name;
  2845. ch = (unsigned char)*p;
  2846. hashval = ch << 4;
  2847. while (ch) {
  2848. hashval += ch;
  2849. ch = (unsigned char)*++p;
  2850. }
  2851. app = &atab[hashval % ATABSIZE];
  2852. for (; *app; app = &(*app)->next) {
  2853. if (strcmp(name, (*app)->name) == 0) {
  2854. break;
  2855. }
  2856. }
  2857. return app;
  2858. }
  2859. static struct alias *
  2860. lookupalias(const char *name, int check)
  2861. {
  2862. struct alias *ap = *__lookupalias(name);
  2863. if (check && ap && (ap->flag & ALIASINUSE))
  2864. return NULL;
  2865. return ap;
  2866. }
  2867. static struct alias *
  2868. freealias(struct alias *ap)
  2869. {
  2870. struct alias *next;
  2871. if (ap->flag & ALIASINUSE) {
  2872. ap->flag |= ALIASDEAD;
  2873. return ap;
  2874. }
  2875. next = ap->next;
  2876. free(ap->name);
  2877. free(ap->val);
  2878. free(ap);
  2879. return next;
  2880. }
  2881. static void
  2882. setalias(const char *name, const char *val)
  2883. {
  2884. struct alias *ap, **app;
  2885. app = __lookupalias(name);
  2886. ap = *app;
  2887. INT_OFF;
  2888. if (ap) {
  2889. if (!(ap->flag & ALIASINUSE)) {
  2890. free(ap->val);
  2891. }
  2892. ap->val = ckstrdup(val);
  2893. ap->flag &= ~ALIASDEAD;
  2894. } else {
  2895. /* not found */
  2896. ap = ckzalloc(sizeof(struct alias));
  2897. ap->name = ckstrdup(name);
  2898. ap->val = ckstrdup(val);
  2899. /*ap->flag = 0; - ckzalloc did it */
  2900. /*ap->next = NULL;*/
  2901. *app = ap;
  2902. }
  2903. INT_ON;
  2904. }
  2905. static int
  2906. unalias(const char *name)
  2907. {
  2908. struct alias **app;
  2909. app = __lookupalias(name);
  2910. if (*app) {
  2911. INT_OFF;
  2912. *app = freealias(*app);
  2913. INT_ON;
  2914. return 0;
  2915. }
  2916. return 1;
  2917. }
  2918. static void
  2919. rmaliases(void)
  2920. {
  2921. struct alias *ap, **app;
  2922. int i;
  2923. INT_OFF;
  2924. for (i = 0; i < ATABSIZE; i++) {
  2925. app = &atab[i];
  2926. for (ap = *app; ap; ap = *app) {
  2927. *app = freealias(*app);
  2928. if (ap == *app) {
  2929. app = &ap->next;
  2930. }
  2931. }
  2932. }
  2933. INT_ON;
  2934. }
  2935. static void
  2936. printalias(const struct alias *ap)
  2937. {
  2938. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2939. }
  2940. /*
  2941. * TODO - sort output
  2942. */
  2943. static int FAST_FUNC
  2944. aliascmd(int argc UNUSED_PARAM, char **argv)
  2945. {
  2946. char *n, *v;
  2947. int ret = 0;
  2948. struct alias *ap;
  2949. if (!argv[1]) {
  2950. int i;
  2951. for (i = 0; i < ATABSIZE; i++) {
  2952. for (ap = atab[i]; ap; ap = ap->next) {
  2953. printalias(ap);
  2954. }
  2955. }
  2956. return 0;
  2957. }
  2958. while ((n = *++argv) != NULL) {
  2959. v = strchr(n+1, '=');
  2960. if (v == NULL) { /* n+1: funny ksh stuff */
  2961. ap = *__lookupalias(n);
  2962. if (ap == NULL) {
  2963. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2964. ret = 1;
  2965. } else
  2966. printalias(ap);
  2967. } else {
  2968. *v++ = '\0';
  2969. setalias(n, v);
  2970. }
  2971. }
  2972. return ret;
  2973. }
  2974. static int FAST_FUNC
  2975. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2976. {
  2977. int i;
  2978. while ((i = nextopt("a")) != '\0') {
  2979. if (i == 'a') {
  2980. rmaliases();
  2981. return 0;
  2982. }
  2983. }
  2984. for (i = 0; *argptr; argptr++) {
  2985. if (unalias(*argptr)) {
  2986. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2987. i = 1;
  2988. }
  2989. }
  2990. return i;
  2991. }
  2992. #endif /* ASH_ALIAS */
  2993. /* ============ jobs.c */
  2994. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2995. #define FORK_FG 0
  2996. #define FORK_BG 1
  2997. #define FORK_NOJOB 2
  2998. /* mode flags for showjob(s) */
  2999. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3000. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3001. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3002. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3003. /*
  3004. * A job structure contains information about a job. A job is either a
  3005. * single process or a set of processes contained in a pipeline. In the
  3006. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3007. * array of pids.
  3008. */
  3009. struct procstat {
  3010. pid_t ps_pid; /* process id */
  3011. int ps_status; /* last process status from wait() */
  3012. char *ps_cmd; /* text of command being run */
  3013. };
  3014. struct job {
  3015. struct procstat ps0; /* status of process */
  3016. struct procstat *ps; /* status or processes when more than one */
  3017. #if JOBS
  3018. int stopstatus; /* status of a stopped job */
  3019. #endif
  3020. uint32_t
  3021. nprocs: 16, /* number of processes */
  3022. state: 8,
  3023. #define JOBRUNNING 0 /* at least one proc running */
  3024. #define JOBSTOPPED 1 /* all procs are stopped */
  3025. #define JOBDONE 2 /* all procs are completed */
  3026. #if JOBS
  3027. sigint: 1, /* job was killed by SIGINT */
  3028. jobctl: 1, /* job running under job control */
  3029. #endif
  3030. waited: 1, /* true if this entry has been waited for */
  3031. used: 1, /* true if this entry is in used */
  3032. changed: 1; /* true if status has changed */
  3033. struct job *prev_job; /* previous job */
  3034. };
  3035. static struct job *makejob(/*union node *,*/ int);
  3036. static int forkshell(struct job *, union node *, int);
  3037. static int waitforjob(struct job *);
  3038. #if !JOBS
  3039. enum { doing_jobctl = 0 };
  3040. #define setjobctl(on) do {} while (0)
  3041. #else
  3042. static smallint doing_jobctl; //references:8
  3043. static void setjobctl(int);
  3044. #endif
  3045. /*
  3046. * Ignore a signal.
  3047. */
  3048. static void
  3049. ignoresig(int signo)
  3050. {
  3051. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3052. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3053. /* No, need to do it */
  3054. signal(signo, SIG_IGN);
  3055. }
  3056. sigmode[signo - 1] = S_HARD_IGN;
  3057. }
  3058. /*
  3059. * Only one usage site - in setsignal()
  3060. */
  3061. static void
  3062. signal_handler(int signo)
  3063. {
  3064. gotsig[signo - 1] = 1;
  3065. if (signo == SIGINT && !trap[SIGINT]) {
  3066. if (!suppress_int) {
  3067. pending_sig = 0;
  3068. raise_interrupt(); /* does not return */
  3069. }
  3070. pending_int = 1;
  3071. } else {
  3072. pending_sig = signo;
  3073. }
  3074. }
  3075. /*
  3076. * Set the signal handler for the specified signal. The routine figures
  3077. * out what it should be set to.
  3078. */
  3079. static void
  3080. setsignal(int signo)
  3081. {
  3082. char *t;
  3083. char cur_act, new_act;
  3084. struct sigaction act;
  3085. t = trap[signo];
  3086. new_act = S_DFL;
  3087. if (t != NULL) { /* trap for this sig is set */
  3088. new_act = S_CATCH;
  3089. if (t[0] == '\0') /* trap is "": ignore this sig */
  3090. new_act = S_IGN;
  3091. }
  3092. if (rootshell && new_act == S_DFL) {
  3093. switch (signo) {
  3094. case SIGINT:
  3095. if (iflag || minusc || sflag == 0)
  3096. new_act = S_CATCH;
  3097. break;
  3098. case SIGQUIT:
  3099. #if DEBUG
  3100. if (debug)
  3101. break;
  3102. #endif
  3103. /* man bash:
  3104. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3105. * commands run by bash have signal handlers
  3106. * set to the values inherited by the shell
  3107. * from its parent". */
  3108. new_act = S_IGN;
  3109. break;
  3110. case SIGTERM:
  3111. if (iflag)
  3112. new_act = S_IGN;
  3113. break;
  3114. #if JOBS
  3115. case SIGTSTP:
  3116. case SIGTTOU:
  3117. if (mflag)
  3118. new_act = S_IGN;
  3119. break;
  3120. #endif
  3121. }
  3122. }
  3123. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3124. //whereas we have to restore it to what shell got on entry
  3125. //from the parent. See comment above
  3126. t = &sigmode[signo - 1];
  3127. cur_act = *t;
  3128. if (cur_act == 0) {
  3129. /* current setting is not yet known */
  3130. if (sigaction(signo, NULL, &act)) {
  3131. /* pretend it worked; maybe we should give a warning,
  3132. * but other shells don't. We don't alter sigmode,
  3133. * so we retry every time.
  3134. * btw, in Linux it never fails. --vda */
  3135. return;
  3136. }
  3137. if (act.sa_handler == SIG_IGN) {
  3138. cur_act = S_HARD_IGN;
  3139. if (mflag
  3140. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3141. ) {
  3142. cur_act = S_IGN; /* don't hard ignore these */
  3143. }
  3144. }
  3145. }
  3146. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3147. return;
  3148. act.sa_handler = SIG_DFL;
  3149. switch (new_act) {
  3150. case S_CATCH:
  3151. act.sa_handler = signal_handler;
  3152. break;
  3153. case S_IGN:
  3154. act.sa_handler = SIG_IGN;
  3155. break;
  3156. }
  3157. /* flags and mask matter only if !DFL and !IGN, but we do it
  3158. * for all cases for more deterministic behavior:
  3159. */
  3160. act.sa_flags = 0;
  3161. sigfillset(&act.sa_mask);
  3162. sigaction_set(signo, &act);
  3163. *t = new_act;
  3164. }
  3165. /* mode flags for set_curjob */
  3166. #define CUR_DELETE 2
  3167. #define CUR_RUNNING 1
  3168. #define CUR_STOPPED 0
  3169. /* mode flags for dowait */
  3170. #define DOWAIT_NONBLOCK WNOHANG
  3171. #define DOWAIT_BLOCK 0
  3172. #if JOBS
  3173. /* pgrp of shell on invocation */
  3174. static int initialpgrp; //references:2
  3175. static int ttyfd = -1; //5
  3176. #endif
  3177. /* array of jobs */
  3178. static struct job *jobtab; //5
  3179. /* size of array */
  3180. static unsigned njobs; //4
  3181. /* current job */
  3182. static struct job *curjob; //lots
  3183. /* number of presumed living untracked jobs */
  3184. static int jobless; //4
  3185. static void
  3186. set_curjob(struct job *jp, unsigned mode)
  3187. {
  3188. struct job *jp1;
  3189. struct job **jpp, **curp;
  3190. /* first remove from list */
  3191. jpp = curp = &curjob;
  3192. while (1) {
  3193. jp1 = *jpp;
  3194. if (jp1 == jp)
  3195. break;
  3196. jpp = &jp1->prev_job;
  3197. }
  3198. *jpp = jp1->prev_job;
  3199. /* Then re-insert in correct position */
  3200. jpp = curp;
  3201. switch (mode) {
  3202. default:
  3203. #if DEBUG
  3204. abort();
  3205. #endif
  3206. case CUR_DELETE:
  3207. /* job being deleted */
  3208. break;
  3209. case CUR_RUNNING:
  3210. /* newly created job or backgrounded job,
  3211. * put after all stopped jobs.
  3212. */
  3213. while (1) {
  3214. jp1 = *jpp;
  3215. #if JOBS
  3216. if (!jp1 || jp1->state != JOBSTOPPED)
  3217. #endif
  3218. break;
  3219. jpp = &jp1->prev_job;
  3220. }
  3221. /* FALLTHROUGH */
  3222. #if JOBS
  3223. case CUR_STOPPED:
  3224. #endif
  3225. /* newly stopped job - becomes curjob */
  3226. jp->prev_job = *jpp;
  3227. *jpp = jp;
  3228. break;
  3229. }
  3230. }
  3231. #if JOBS || DEBUG
  3232. static int
  3233. jobno(const struct job *jp)
  3234. {
  3235. return jp - jobtab + 1;
  3236. }
  3237. #endif
  3238. /*
  3239. * Convert a job name to a job structure.
  3240. */
  3241. #if !JOBS
  3242. #define getjob(name, getctl) getjob(name)
  3243. #endif
  3244. static struct job *
  3245. getjob(const char *name, int getctl)
  3246. {
  3247. struct job *jp;
  3248. struct job *found;
  3249. const char *err_msg = "%s: no such job";
  3250. unsigned num;
  3251. int c;
  3252. const char *p;
  3253. char *(*match)(const char *, const char *);
  3254. jp = curjob;
  3255. p = name;
  3256. if (!p)
  3257. goto currentjob;
  3258. if (*p != '%')
  3259. goto err;
  3260. c = *++p;
  3261. if (!c)
  3262. goto currentjob;
  3263. if (!p[1]) {
  3264. if (c == '+' || c == '%') {
  3265. currentjob:
  3266. err_msg = "No current job";
  3267. goto check;
  3268. }
  3269. if (c == '-') {
  3270. if (jp)
  3271. jp = jp->prev_job;
  3272. err_msg = "No previous job";
  3273. check:
  3274. if (!jp)
  3275. goto err;
  3276. goto gotit;
  3277. }
  3278. }
  3279. if (is_number(p)) {
  3280. num = atoi(p);
  3281. if (num <= njobs) {
  3282. jp = jobtab + num - 1;
  3283. if (jp->used)
  3284. goto gotit;
  3285. goto err;
  3286. }
  3287. }
  3288. match = prefix;
  3289. if (*p == '?') {
  3290. match = strstr;
  3291. p++;
  3292. }
  3293. found = NULL;
  3294. while (jp) {
  3295. if (match(jp->ps[0].ps_cmd, p)) {
  3296. if (found)
  3297. goto err;
  3298. found = jp;
  3299. err_msg = "%s: ambiguous";
  3300. }
  3301. jp = jp->prev_job;
  3302. }
  3303. if (!found)
  3304. goto err;
  3305. jp = found;
  3306. gotit:
  3307. #if JOBS
  3308. err_msg = "job %s not created under job control";
  3309. if (getctl && jp->jobctl == 0)
  3310. goto err;
  3311. #endif
  3312. return jp;
  3313. err:
  3314. ash_msg_and_raise_error(err_msg, name);
  3315. }
  3316. /*
  3317. * Mark a job structure as unused.
  3318. */
  3319. static void
  3320. freejob(struct job *jp)
  3321. {
  3322. struct procstat *ps;
  3323. int i;
  3324. INT_OFF;
  3325. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3326. if (ps->ps_cmd != nullstr)
  3327. free(ps->ps_cmd);
  3328. }
  3329. if (jp->ps != &jp->ps0)
  3330. free(jp->ps);
  3331. jp->used = 0;
  3332. set_curjob(jp, CUR_DELETE);
  3333. INT_ON;
  3334. }
  3335. #if JOBS
  3336. static void
  3337. xtcsetpgrp(int fd, pid_t pgrp)
  3338. {
  3339. if (tcsetpgrp(fd, pgrp))
  3340. ash_msg_and_raise_error("can't set tty process group (%m)");
  3341. }
  3342. /*
  3343. * Turn job control on and off.
  3344. *
  3345. * Note: This code assumes that the third arg to ioctl is a character
  3346. * pointer, which is true on Berkeley systems but not System V. Since
  3347. * System V doesn't have job control yet, this isn't a problem now.
  3348. *
  3349. * Called with interrupts off.
  3350. */
  3351. static void
  3352. setjobctl(int on)
  3353. {
  3354. int fd;
  3355. int pgrp;
  3356. if (on == doing_jobctl || rootshell == 0)
  3357. return;
  3358. if (on) {
  3359. int ofd;
  3360. ofd = fd = open(_PATH_TTY, O_RDWR);
  3361. if (fd < 0) {
  3362. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3363. * That sometimes helps to acquire controlling tty.
  3364. * Obviously, a workaround for bugs when someone
  3365. * failed to provide a controlling tty to bash! :) */
  3366. fd = 2;
  3367. while (!isatty(fd))
  3368. if (--fd < 0)
  3369. goto out;
  3370. }
  3371. fd = fcntl(fd, F_DUPFD, 10);
  3372. if (ofd >= 0)
  3373. close(ofd);
  3374. if (fd < 0)
  3375. goto out;
  3376. /* fd is a tty at this point */
  3377. close_on_exec_on(fd);
  3378. while (1) { /* while we are in the background */
  3379. pgrp = tcgetpgrp(fd);
  3380. if (pgrp < 0) {
  3381. out:
  3382. ash_msg("can't access tty; job control turned off");
  3383. mflag = on = 0;
  3384. goto close;
  3385. }
  3386. if (pgrp == getpgrp())
  3387. break;
  3388. killpg(0, SIGTTIN);
  3389. }
  3390. initialpgrp = pgrp;
  3391. setsignal(SIGTSTP);
  3392. setsignal(SIGTTOU);
  3393. setsignal(SIGTTIN);
  3394. pgrp = rootpid;
  3395. setpgid(0, pgrp);
  3396. xtcsetpgrp(fd, pgrp);
  3397. } else {
  3398. /* turning job control off */
  3399. fd = ttyfd;
  3400. pgrp = initialpgrp;
  3401. /* was xtcsetpgrp, but this can make exiting ash
  3402. * loop forever if pty is already deleted */
  3403. tcsetpgrp(fd, pgrp);
  3404. setpgid(0, pgrp);
  3405. setsignal(SIGTSTP);
  3406. setsignal(SIGTTOU);
  3407. setsignal(SIGTTIN);
  3408. close:
  3409. if (fd >= 0)
  3410. close(fd);
  3411. fd = -1;
  3412. }
  3413. ttyfd = fd;
  3414. doing_jobctl = on;
  3415. }
  3416. static int FAST_FUNC
  3417. killcmd(int argc, char **argv)
  3418. {
  3419. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3420. int i = 1;
  3421. do {
  3422. if (argv[i][0] == '%') {
  3423. /*
  3424. * "kill %N" - job kill
  3425. * Converting to pgrp / pid kill
  3426. */
  3427. struct job *jp;
  3428. char *dst;
  3429. int j, n;
  3430. jp = getjob(argv[i], 0);
  3431. /*
  3432. * In jobs started under job control, we signal
  3433. * entire process group by kill -PGRP_ID.
  3434. * This happens, f.e., in interactive shell.
  3435. *
  3436. * Otherwise, we signal each child via
  3437. * kill PID1 PID2 PID3.
  3438. * Testcases:
  3439. * sh -c 'sleep 1|sleep 1 & kill %1'
  3440. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3441. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3442. */
  3443. n = jp->nprocs; /* can't be 0 (I hope) */
  3444. if (jp->jobctl)
  3445. n = 1;
  3446. dst = alloca(n * sizeof(int)*4);
  3447. argv[i] = dst;
  3448. for (j = 0; j < n; j++) {
  3449. struct procstat *ps = &jp->ps[j];
  3450. /* Skip non-running and not-stopped members
  3451. * (i.e. dead members) of the job
  3452. */
  3453. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3454. continue;
  3455. /*
  3456. * kill_main has matching code to expect
  3457. * leading space. Needed to not confuse
  3458. * negative pids with "kill -SIGNAL_NO" syntax
  3459. */
  3460. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3461. }
  3462. *dst = '\0';
  3463. }
  3464. } while (argv[++i]);
  3465. }
  3466. return kill_main(argc, argv);
  3467. }
  3468. static void
  3469. showpipe(struct job *jp /*, FILE *out*/)
  3470. {
  3471. struct procstat *ps;
  3472. struct procstat *psend;
  3473. psend = jp->ps + jp->nprocs;
  3474. for (ps = jp->ps + 1; ps < psend; ps++)
  3475. printf(" | %s", ps->ps_cmd);
  3476. newline_and_flush(stdout);
  3477. flush_stdout_stderr();
  3478. }
  3479. static int
  3480. restartjob(struct job *jp, int mode)
  3481. {
  3482. struct procstat *ps;
  3483. int i;
  3484. int status;
  3485. pid_t pgid;
  3486. INT_OFF;
  3487. if (jp->state == JOBDONE)
  3488. goto out;
  3489. jp->state = JOBRUNNING;
  3490. pgid = jp->ps[0].ps_pid;
  3491. if (mode == FORK_FG)
  3492. xtcsetpgrp(ttyfd, pgid);
  3493. killpg(pgid, SIGCONT);
  3494. ps = jp->ps;
  3495. i = jp->nprocs;
  3496. do {
  3497. if (WIFSTOPPED(ps->ps_status)) {
  3498. ps->ps_status = -1;
  3499. }
  3500. ps++;
  3501. } while (--i);
  3502. out:
  3503. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3504. INT_ON;
  3505. return status;
  3506. }
  3507. static int FAST_FUNC
  3508. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3509. {
  3510. struct job *jp;
  3511. int mode;
  3512. int retval;
  3513. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3514. nextopt(nullstr);
  3515. argv = argptr;
  3516. do {
  3517. jp = getjob(*argv, 1);
  3518. if (mode == FORK_BG) {
  3519. set_curjob(jp, CUR_RUNNING);
  3520. printf("[%d] ", jobno(jp));
  3521. }
  3522. out1str(jp->ps[0].ps_cmd);
  3523. showpipe(jp /*, stdout*/);
  3524. retval = restartjob(jp, mode);
  3525. } while (*argv && *++argv);
  3526. return retval;
  3527. }
  3528. #endif
  3529. static int
  3530. sprint_status48(char *s, int status, int sigonly)
  3531. {
  3532. int col;
  3533. int st;
  3534. col = 0;
  3535. if (!WIFEXITED(status)) {
  3536. if (JOBS && WIFSTOPPED(status))
  3537. st = WSTOPSIG(status);
  3538. else
  3539. st = WTERMSIG(status);
  3540. if (sigonly) {
  3541. if (st == SIGINT || st == SIGPIPE)
  3542. goto out;
  3543. if (JOBS && WIFSTOPPED(status))
  3544. goto out;
  3545. }
  3546. st &= 0x7f;
  3547. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3548. col = fmtstr(s, 32, strsignal(st));
  3549. if (WCOREDUMP(status)) {
  3550. strcpy(s + col, " (core dumped)");
  3551. col += sizeof(" (core dumped)")-1;
  3552. }
  3553. } else if (!sigonly) {
  3554. st = WEXITSTATUS(status);
  3555. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3556. }
  3557. out:
  3558. return col;
  3559. }
  3560. static int
  3561. dowait(int wait_flags, struct job *job)
  3562. {
  3563. int pid;
  3564. int status;
  3565. struct job *jp;
  3566. struct job *thisjob;
  3567. TRACE(("dowait(0x%x) called\n", wait_flags));
  3568. /* Do a wait system call. If job control is compiled in, we accept
  3569. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3570. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3571. if (doing_jobctl)
  3572. wait_flags |= WUNTRACED;
  3573. pid = waitpid(-1, &status, wait_flags);
  3574. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3575. pid, status, errno, strerror(errno)));
  3576. if (pid <= 0)
  3577. return pid;
  3578. INT_OFF;
  3579. thisjob = NULL;
  3580. for (jp = curjob; jp; jp = jp->prev_job) {
  3581. int jobstate;
  3582. struct procstat *ps;
  3583. struct procstat *psend;
  3584. if (jp->state == JOBDONE)
  3585. continue;
  3586. jobstate = JOBDONE;
  3587. ps = jp->ps;
  3588. psend = ps + jp->nprocs;
  3589. do {
  3590. if (ps->ps_pid == pid) {
  3591. TRACE(("Job %d: changing status of proc %d "
  3592. "from 0x%x to 0x%x\n",
  3593. jobno(jp), pid, ps->ps_status, status));
  3594. ps->ps_status = status;
  3595. thisjob = jp;
  3596. }
  3597. if (ps->ps_status == -1)
  3598. jobstate = JOBRUNNING;
  3599. #if JOBS
  3600. if (jobstate == JOBRUNNING)
  3601. continue;
  3602. if (WIFSTOPPED(ps->ps_status)) {
  3603. jp->stopstatus = ps->ps_status;
  3604. jobstate = JOBSTOPPED;
  3605. }
  3606. #endif
  3607. } while (++ps < psend);
  3608. if (!thisjob)
  3609. continue;
  3610. /* Found the job where one of its processes changed its state.
  3611. * Is there at least one live and running process in this job? */
  3612. if (jobstate != JOBRUNNING) {
  3613. /* No. All live processes in the job are stopped
  3614. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3615. */
  3616. thisjob->changed = 1;
  3617. if (thisjob->state != jobstate) {
  3618. TRACE(("Job %d: changing state from %d to %d\n",
  3619. jobno(thisjob), thisjob->state, jobstate));
  3620. thisjob->state = jobstate;
  3621. #if JOBS
  3622. if (jobstate == JOBSTOPPED)
  3623. set_curjob(thisjob, CUR_STOPPED);
  3624. #endif
  3625. }
  3626. }
  3627. goto out;
  3628. }
  3629. /* The process wasn't found in job list */
  3630. if (JOBS && !WIFSTOPPED(status))
  3631. jobless--;
  3632. out:
  3633. INT_ON;
  3634. if (thisjob && thisjob == job) {
  3635. char s[48 + 1];
  3636. int len;
  3637. len = sprint_status48(s, status, 1);
  3638. if (len) {
  3639. s[len] = '\n';
  3640. s[len + 1] = '\0';
  3641. out2str(s);
  3642. }
  3643. }
  3644. return pid;
  3645. }
  3646. static int
  3647. blocking_wait_with_raise_on_sig(void)
  3648. {
  3649. pid_t pid = dowait(DOWAIT_BLOCK, NULL);
  3650. if (pid <= 0 && pending_sig)
  3651. raise_exception(EXSIG);
  3652. return pid;
  3653. }
  3654. #if JOBS
  3655. static void
  3656. showjob(struct job *jp, int mode)
  3657. {
  3658. struct procstat *ps;
  3659. struct procstat *psend;
  3660. int col;
  3661. int indent_col;
  3662. char s[16 + 16 + 48];
  3663. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3664. ps = jp->ps;
  3665. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3666. /* just output process (group) id of pipeline */
  3667. fprintf(out, "%d\n", ps->ps_pid);
  3668. return;
  3669. }
  3670. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3671. indent_col = col;
  3672. if (jp == curjob)
  3673. s[col - 3] = '+';
  3674. else if (curjob && jp == curjob->prev_job)
  3675. s[col - 3] = '-';
  3676. if (mode & SHOW_PIDS)
  3677. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3678. psend = ps + jp->nprocs;
  3679. if (jp->state == JOBRUNNING) {
  3680. strcpy(s + col, "Running");
  3681. col += sizeof("Running") - 1;
  3682. } else {
  3683. int status = psend[-1].ps_status;
  3684. if (jp->state == JOBSTOPPED)
  3685. status = jp->stopstatus;
  3686. col += sprint_status48(s + col, status, 0);
  3687. }
  3688. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3689. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3690. * or prints several "PID | <cmdN>" lines,
  3691. * depending on SHOW_PIDS bit.
  3692. * We do not print status of individual processes
  3693. * between PID and <cmdN>. bash does it, but not very well:
  3694. * first line shows overall job status, not process status,
  3695. * making it impossible to know 1st process status.
  3696. */
  3697. goto start;
  3698. do {
  3699. /* for each process */
  3700. s[0] = '\0';
  3701. col = 33;
  3702. if (mode & SHOW_PIDS)
  3703. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3704. start:
  3705. fprintf(out, "%s%*c%s%s",
  3706. s,
  3707. 33 - col >= 0 ? 33 - col : 0, ' ',
  3708. ps == jp->ps ? "" : "| ",
  3709. ps->ps_cmd
  3710. );
  3711. } while (++ps != psend);
  3712. newline_and_flush(out);
  3713. jp->changed = 0;
  3714. if (jp->state == JOBDONE) {
  3715. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3716. freejob(jp);
  3717. }
  3718. }
  3719. /*
  3720. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3721. * statuses have changed since the last call to showjobs.
  3722. */
  3723. static void
  3724. showjobs(int mode)
  3725. {
  3726. struct job *jp;
  3727. TRACE(("showjobs(0x%x) called\n", mode));
  3728. /* Handle all finished jobs */
  3729. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3730. continue;
  3731. for (jp = curjob; jp; jp = jp->prev_job) {
  3732. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3733. showjob(jp, mode);
  3734. }
  3735. }
  3736. }
  3737. static int FAST_FUNC
  3738. jobscmd(int argc UNUSED_PARAM, char **argv)
  3739. {
  3740. int mode, m;
  3741. mode = 0;
  3742. while ((m = nextopt("lp")) != '\0') {
  3743. if (m == 'l')
  3744. mode |= SHOW_PIDS;
  3745. else
  3746. mode |= SHOW_ONLY_PGID;
  3747. }
  3748. argv = argptr;
  3749. if (*argv) {
  3750. do
  3751. showjob(getjob(*argv, 0), mode);
  3752. while (*++argv);
  3753. } else {
  3754. showjobs(mode);
  3755. }
  3756. return 0;
  3757. }
  3758. #endif /* JOBS */
  3759. /* Called only on finished or stopped jobs (no members are running) */
  3760. static int
  3761. getstatus(struct job *job)
  3762. {
  3763. int status;
  3764. int retval;
  3765. struct procstat *ps;
  3766. /* Fetch last member's status */
  3767. ps = job->ps + job->nprocs - 1;
  3768. status = ps->ps_status;
  3769. if (pipefail) {
  3770. /* "set -o pipefail" mode: use last _nonzero_ status */
  3771. while (status == 0 && --ps >= job->ps)
  3772. status = ps->ps_status;
  3773. }
  3774. retval = WEXITSTATUS(status);
  3775. if (!WIFEXITED(status)) {
  3776. #if JOBS
  3777. retval = WSTOPSIG(status);
  3778. if (!WIFSTOPPED(status))
  3779. #endif
  3780. {
  3781. /* XXX: limits number of signals */
  3782. retval = WTERMSIG(status);
  3783. #if JOBS
  3784. if (retval == SIGINT)
  3785. job->sigint = 1;
  3786. #endif
  3787. }
  3788. retval += 128;
  3789. }
  3790. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3791. jobno(job), job->nprocs, status, retval));
  3792. return retval;
  3793. }
  3794. static int FAST_FUNC
  3795. waitcmd(int argc UNUSED_PARAM, char **argv)
  3796. {
  3797. struct job *job;
  3798. int retval;
  3799. struct job *jp;
  3800. if (pending_sig)
  3801. raise_exception(EXSIG);
  3802. nextopt(nullstr);
  3803. retval = 0;
  3804. argv = argptr;
  3805. if (!*argv) {
  3806. /* wait for all jobs */
  3807. for (;;) {
  3808. jp = curjob;
  3809. while (1) {
  3810. if (!jp) /* no running procs */
  3811. goto ret;
  3812. if (jp->state == JOBRUNNING)
  3813. break;
  3814. jp->waited = 1;
  3815. jp = jp->prev_job;
  3816. }
  3817. blocking_wait_with_raise_on_sig();
  3818. /* man bash:
  3819. * "When bash is waiting for an asynchronous command via
  3820. * the wait builtin, the reception of a signal for which a trap
  3821. * has been set will cause the wait builtin to return immediately
  3822. * with an exit status greater than 128, immediately after which
  3823. * the trap is executed."
  3824. *
  3825. * blocking_wait_with_raise_on_sig raises signal handlers
  3826. * if it gets no pid (pid < 0). However,
  3827. * if child sends us a signal *and immediately exits*,
  3828. * blocking_wait_with_raise_on_sig gets pid > 0
  3829. * and does not handle pending_sig. Check this case: */
  3830. if (pending_sig)
  3831. raise_exception(EXSIG);
  3832. }
  3833. }
  3834. retval = 127;
  3835. do {
  3836. if (**argv != '%') {
  3837. pid_t pid = number(*argv);
  3838. job = curjob;
  3839. while (1) {
  3840. if (!job)
  3841. goto repeat;
  3842. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3843. break;
  3844. job = job->prev_job;
  3845. }
  3846. } else {
  3847. job = getjob(*argv, 0);
  3848. }
  3849. /* loop until process terminated or stopped */
  3850. while (job->state == JOBRUNNING)
  3851. blocking_wait_with_raise_on_sig();
  3852. job->waited = 1;
  3853. retval = getstatus(job);
  3854. repeat: ;
  3855. } while (*++argv);
  3856. ret:
  3857. return retval;
  3858. }
  3859. static struct job *
  3860. growjobtab(void)
  3861. {
  3862. size_t len;
  3863. ptrdiff_t offset;
  3864. struct job *jp, *jq;
  3865. len = njobs * sizeof(*jp);
  3866. jq = jobtab;
  3867. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3868. offset = (char *)jp - (char *)jq;
  3869. if (offset) {
  3870. /* Relocate pointers */
  3871. size_t l = len;
  3872. jq = (struct job *)((char *)jq + l);
  3873. while (l) {
  3874. l -= sizeof(*jp);
  3875. jq--;
  3876. #define joff(p) ((struct job *)((char *)(p) + l))
  3877. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3878. if (joff(jp)->ps == &jq->ps0)
  3879. jmove(joff(jp)->ps);
  3880. if (joff(jp)->prev_job)
  3881. jmove(joff(jp)->prev_job);
  3882. }
  3883. if (curjob)
  3884. jmove(curjob);
  3885. #undef joff
  3886. #undef jmove
  3887. }
  3888. njobs += 4;
  3889. jobtab = jp;
  3890. jp = (struct job *)((char *)jp + len);
  3891. jq = jp + 3;
  3892. do {
  3893. jq->used = 0;
  3894. } while (--jq >= jp);
  3895. return jp;
  3896. }
  3897. /*
  3898. * Return a new job structure.
  3899. * Called with interrupts off.
  3900. */
  3901. static struct job *
  3902. makejob(/*union node *node,*/ int nprocs)
  3903. {
  3904. int i;
  3905. struct job *jp;
  3906. for (i = njobs, jp = jobtab; ; jp++) {
  3907. if (--i < 0) {
  3908. jp = growjobtab();
  3909. break;
  3910. }
  3911. if (jp->used == 0)
  3912. break;
  3913. if (jp->state != JOBDONE || !jp->waited)
  3914. continue;
  3915. #if JOBS
  3916. if (doing_jobctl)
  3917. continue;
  3918. #endif
  3919. freejob(jp);
  3920. break;
  3921. }
  3922. memset(jp, 0, sizeof(*jp));
  3923. #if JOBS
  3924. /* jp->jobctl is a bitfield.
  3925. * "jp->jobctl |= jobctl" likely to give awful code */
  3926. if (doing_jobctl)
  3927. jp->jobctl = 1;
  3928. #endif
  3929. jp->prev_job = curjob;
  3930. curjob = jp;
  3931. jp->used = 1;
  3932. jp->ps = &jp->ps0;
  3933. if (nprocs > 1) {
  3934. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3935. }
  3936. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3937. jobno(jp)));
  3938. return jp;
  3939. }
  3940. #if JOBS
  3941. /*
  3942. * Return a string identifying a command (to be printed by the
  3943. * jobs command).
  3944. */
  3945. static char *cmdnextc;
  3946. static void
  3947. cmdputs(const char *s)
  3948. {
  3949. static const char vstype[VSTYPE + 1][3] = {
  3950. "", "}", "-", "+", "?", "=",
  3951. "%", "%%", "#", "##"
  3952. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3953. };
  3954. const char *p, *str;
  3955. char cc[2];
  3956. char *nextc;
  3957. unsigned char c;
  3958. unsigned char subtype = 0;
  3959. int quoted = 0;
  3960. cc[1] = '\0';
  3961. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3962. p = s;
  3963. while ((c = *p++) != '\0') {
  3964. str = NULL;
  3965. switch (c) {
  3966. case CTLESC:
  3967. c = *p++;
  3968. break;
  3969. case CTLVAR:
  3970. subtype = *p++;
  3971. if ((subtype & VSTYPE) == VSLENGTH)
  3972. str = "${#";
  3973. else
  3974. str = "${";
  3975. goto dostr;
  3976. case CTLENDVAR:
  3977. str = "\"}" + !(quoted & 1);
  3978. quoted >>= 1;
  3979. subtype = 0;
  3980. goto dostr;
  3981. case CTLBACKQ:
  3982. str = "$(...)";
  3983. goto dostr;
  3984. #if ENABLE_SH_MATH_SUPPORT
  3985. case CTLARI:
  3986. str = "$((";
  3987. goto dostr;
  3988. case CTLENDARI:
  3989. str = "))";
  3990. goto dostr;
  3991. #endif
  3992. case CTLQUOTEMARK:
  3993. quoted ^= 1;
  3994. c = '"';
  3995. break;
  3996. case '=':
  3997. if (subtype == 0)
  3998. break;
  3999. if ((subtype & VSTYPE) != VSNORMAL)
  4000. quoted <<= 1;
  4001. str = vstype[subtype & VSTYPE];
  4002. if (subtype & VSNUL)
  4003. c = ':';
  4004. else
  4005. goto checkstr;
  4006. break;
  4007. case '\'':
  4008. case '\\':
  4009. case '"':
  4010. case '$':
  4011. /* These can only happen inside quotes */
  4012. cc[0] = c;
  4013. str = cc;
  4014. c = '\\';
  4015. break;
  4016. default:
  4017. break;
  4018. }
  4019. USTPUTC(c, nextc);
  4020. checkstr:
  4021. if (!str)
  4022. continue;
  4023. dostr:
  4024. while ((c = *str++) != '\0') {
  4025. USTPUTC(c, nextc);
  4026. }
  4027. } /* while *p++ not NUL */
  4028. if (quoted & 1) {
  4029. USTPUTC('"', nextc);
  4030. }
  4031. *nextc = 0;
  4032. cmdnextc = nextc;
  4033. }
  4034. /* cmdtxt() and cmdlist() call each other */
  4035. static void cmdtxt(union node *n);
  4036. static void
  4037. cmdlist(union node *np, int sep)
  4038. {
  4039. for (; np; np = np->narg.next) {
  4040. if (!sep)
  4041. cmdputs(" ");
  4042. cmdtxt(np);
  4043. if (sep && np->narg.next)
  4044. cmdputs(" ");
  4045. }
  4046. }
  4047. static void
  4048. cmdtxt(union node *n)
  4049. {
  4050. union node *np;
  4051. struct nodelist *lp;
  4052. const char *p;
  4053. if (!n)
  4054. return;
  4055. switch (n->type) {
  4056. default:
  4057. #if DEBUG
  4058. abort();
  4059. #endif
  4060. case NPIPE:
  4061. lp = n->npipe.cmdlist;
  4062. for (;;) {
  4063. cmdtxt(lp->n);
  4064. lp = lp->next;
  4065. if (!lp)
  4066. break;
  4067. cmdputs(" | ");
  4068. }
  4069. break;
  4070. case NSEMI:
  4071. p = "; ";
  4072. goto binop;
  4073. case NAND:
  4074. p = " && ";
  4075. goto binop;
  4076. case NOR:
  4077. p = " || ";
  4078. binop:
  4079. cmdtxt(n->nbinary.ch1);
  4080. cmdputs(p);
  4081. n = n->nbinary.ch2;
  4082. goto donode;
  4083. case NREDIR:
  4084. case NBACKGND:
  4085. n = n->nredir.n;
  4086. goto donode;
  4087. case NNOT:
  4088. cmdputs("!");
  4089. n = n->nnot.com;
  4090. donode:
  4091. cmdtxt(n);
  4092. break;
  4093. case NIF:
  4094. cmdputs("if ");
  4095. cmdtxt(n->nif.test);
  4096. cmdputs("; then ");
  4097. if (n->nif.elsepart) {
  4098. cmdtxt(n->nif.ifpart);
  4099. cmdputs("; else ");
  4100. n = n->nif.elsepart;
  4101. } else {
  4102. n = n->nif.ifpart;
  4103. }
  4104. p = "; fi";
  4105. goto dotail;
  4106. case NSUBSHELL:
  4107. cmdputs("(");
  4108. n = n->nredir.n;
  4109. p = ")";
  4110. goto dotail;
  4111. case NWHILE:
  4112. p = "while ";
  4113. goto until;
  4114. case NUNTIL:
  4115. p = "until ";
  4116. until:
  4117. cmdputs(p);
  4118. cmdtxt(n->nbinary.ch1);
  4119. n = n->nbinary.ch2;
  4120. p = "; done";
  4121. dodo:
  4122. cmdputs("; do ");
  4123. dotail:
  4124. cmdtxt(n);
  4125. goto dotail2;
  4126. case NFOR:
  4127. cmdputs("for ");
  4128. cmdputs(n->nfor.var);
  4129. cmdputs(" in ");
  4130. cmdlist(n->nfor.args, 1);
  4131. n = n->nfor.body;
  4132. p = "; done";
  4133. goto dodo;
  4134. case NDEFUN:
  4135. cmdputs(n->narg.text);
  4136. p = "() { ... }";
  4137. goto dotail2;
  4138. case NCMD:
  4139. cmdlist(n->ncmd.args, 1);
  4140. cmdlist(n->ncmd.redirect, 0);
  4141. break;
  4142. case NARG:
  4143. p = n->narg.text;
  4144. dotail2:
  4145. cmdputs(p);
  4146. break;
  4147. case NHERE:
  4148. case NXHERE:
  4149. p = "<<...";
  4150. goto dotail2;
  4151. case NCASE:
  4152. cmdputs("case ");
  4153. cmdputs(n->ncase.expr->narg.text);
  4154. cmdputs(" in ");
  4155. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4156. cmdtxt(np->nclist.pattern);
  4157. cmdputs(") ");
  4158. cmdtxt(np->nclist.body);
  4159. cmdputs(";; ");
  4160. }
  4161. p = "esac";
  4162. goto dotail2;
  4163. case NTO:
  4164. p = ">";
  4165. goto redir;
  4166. case NCLOBBER:
  4167. p = ">|";
  4168. goto redir;
  4169. case NAPPEND:
  4170. p = ">>";
  4171. goto redir;
  4172. #if ENABLE_ASH_BASH_COMPAT
  4173. case NTO2:
  4174. #endif
  4175. case NTOFD:
  4176. p = ">&";
  4177. goto redir;
  4178. case NFROM:
  4179. p = "<";
  4180. goto redir;
  4181. case NFROMFD:
  4182. p = "<&";
  4183. goto redir;
  4184. case NFROMTO:
  4185. p = "<>";
  4186. redir:
  4187. cmdputs(utoa(n->nfile.fd));
  4188. cmdputs(p);
  4189. if (n->type == NTOFD || n->type == NFROMFD) {
  4190. cmdputs(utoa(n->ndup.dupfd));
  4191. break;
  4192. }
  4193. n = n->nfile.fname;
  4194. goto donode;
  4195. }
  4196. }
  4197. static char *
  4198. commandtext(union node *n)
  4199. {
  4200. char *name;
  4201. STARTSTACKSTR(cmdnextc);
  4202. cmdtxt(n);
  4203. name = stackblock();
  4204. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4205. name, cmdnextc, cmdnextc));
  4206. return ckstrdup(name);
  4207. }
  4208. #endif /* JOBS */
  4209. /*
  4210. * Fork off a subshell. If we are doing job control, give the subshell its
  4211. * own process group. Jp is a job structure that the job is to be added to.
  4212. * N is the command that will be evaluated by the child. Both jp and n may
  4213. * be NULL. The mode parameter can be one of the following:
  4214. * FORK_FG - Fork off a foreground process.
  4215. * FORK_BG - Fork off a background process.
  4216. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4217. * process group even if job control is on.
  4218. *
  4219. * When job control is turned off, background processes have their standard
  4220. * input redirected to /dev/null (except for the second and later processes
  4221. * in a pipeline).
  4222. *
  4223. * Called with interrupts off.
  4224. */
  4225. /*
  4226. * Clear traps on a fork.
  4227. */
  4228. static void
  4229. clear_traps(void)
  4230. {
  4231. char **tp;
  4232. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4233. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4234. INT_OFF;
  4235. if (trap_ptr == trap)
  4236. free(*tp);
  4237. /* else: it "belongs" to trap_ptr vector, don't free */
  4238. *tp = NULL;
  4239. if ((tp - trap) != 0)
  4240. setsignal(tp - trap);
  4241. INT_ON;
  4242. }
  4243. }
  4244. may_have_traps = 0;
  4245. }
  4246. /* Lives far away from here, needed for forkchild */
  4247. static void closescript(void);
  4248. /* Called after fork(), in child */
  4249. static NOINLINE void
  4250. forkchild(struct job *jp, union node *n, int mode)
  4251. {
  4252. int oldlvl;
  4253. TRACE(("Child shell %d\n", getpid()));
  4254. oldlvl = shlvl;
  4255. shlvl++;
  4256. /* man bash: "Non-builtin commands run by bash have signal handlers
  4257. * set to the values inherited by the shell from its parent".
  4258. * Do we do it correctly? */
  4259. closescript();
  4260. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4261. && n && n->type == NCMD /* is it single cmd? */
  4262. /* && n->ncmd.args->type == NARG - always true? */
  4263. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4264. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4265. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4266. ) {
  4267. TRACE(("Trap hack\n"));
  4268. /* Awful hack for `trap` or $(trap).
  4269. *
  4270. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4271. * contains an example where "trap" is executed in a subshell:
  4272. *
  4273. * save_traps=$(trap)
  4274. * ...
  4275. * eval "$save_traps"
  4276. *
  4277. * Standard does not say that "trap" in subshell shall print
  4278. * parent shell's traps. It only says that its output
  4279. * must have suitable form, but then, in the above example
  4280. * (which is not supposed to be normative), it implies that.
  4281. *
  4282. * bash (and probably other shell) does implement it
  4283. * (traps are reset to defaults, but "trap" still shows them),
  4284. * but as a result, "trap" logic is hopelessly messed up:
  4285. *
  4286. * # trap
  4287. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4288. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4289. * # true | trap <--- trap is in subshell - no output (ditto)
  4290. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4291. * trap -- 'echo Ho' SIGWINCH
  4292. * # echo `(trap)` <--- in subshell in subshell - output
  4293. * trap -- 'echo Ho' SIGWINCH
  4294. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4295. * trap -- 'echo Ho' SIGWINCH
  4296. *
  4297. * The rules when to forget and when to not forget traps
  4298. * get really complex and nonsensical.
  4299. *
  4300. * Our solution: ONLY bare $(trap) or `trap` is special.
  4301. */
  4302. /* Save trap handler strings for trap builtin to print */
  4303. trap_ptr = xmemdup(trap, sizeof(trap));
  4304. /* Fall through into clearing traps */
  4305. }
  4306. clear_traps();
  4307. #if JOBS
  4308. /* do job control only in root shell */
  4309. doing_jobctl = 0;
  4310. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4311. pid_t pgrp;
  4312. if (jp->nprocs == 0)
  4313. pgrp = getpid();
  4314. else
  4315. pgrp = jp->ps[0].ps_pid;
  4316. /* this can fail because we are doing it in the parent also */
  4317. setpgid(0, pgrp);
  4318. if (mode == FORK_FG)
  4319. xtcsetpgrp(ttyfd, pgrp);
  4320. setsignal(SIGTSTP);
  4321. setsignal(SIGTTOU);
  4322. } else
  4323. #endif
  4324. if (mode == FORK_BG) {
  4325. /* man bash: "When job control is not in effect,
  4326. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4327. ignoresig(SIGINT);
  4328. ignoresig(SIGQUIT);
  4329. if (jp->nprocs == 0) {
  4330. close(0);
  4331. if (open(bb_dev_null, O_RDONLY) != 0)
  4332. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4333. }
  4334. }
  4335. if (oldlvl == 0) {
  4336. if (iflag) { /* why if iflag only? */
  4337. setsignal(SIGINT);
  4338. setsignal(SIGTERM);
  4339. }
  4340. /* man bash:
  4341. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4342. * commands run by bash have signal handlers
  4343. * set to the values inherited by the shell
  4344. * from its parent".
  4345. * Take care of the second rule: */
  4346. setsignal(SIGQUIT);
  4347. }
  4348. #if JOBS
  4349. if (n && n->type == NCMD
  4350. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4351. ) {
  4352. TRACE(("Job hack\n"));
  4353. /* "jobs": we do not want to clear job list for it,
  4354. * instead we remove only _its_ own_ job from job list.
  4355. * This makes "jobs .... | cat" more useful.
  4356. */
  4357. freejob(curjob);
  4358. return;
  4359. }
  4360. #endif
  4361. for (jp = curjob; jp; jp = jp->prev_job)
  4362. freejob(jp);
  4363. jobless = 0;
  4364. }
  4365. /* Called after fork(), in parent */
  4366. #if !JOBS
  4367. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4368. #endif
  4369. static void
  4370. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4371. {
  4372. TRACE(("In parent shell: child = %d\n", pid));
  4373. if (!jp) {
  4374. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4375. continue;
  4376. jobless++;
  4377. return;
  4378. }
  4379. #if JOBS
  4380. if (mode != FORK_NOJOB && jp->jobctl) {
  4381. int pgrp;
  4382. if (jp->nprocs == 0)
  4383. pgrp = pid;
  4384. else
  4385. pgrp = jp->ps[0].ps_pid;
  4386. /* This can fail because we are doing it in the child also */
  4387. setpgid(pid, pgrp);
  4388. }
  4389. #endif
  4390. if (mode == FORK_BG) {
  4391. backgndpid = pid; /* set $! */
  4392. set_curjob(jp, CUR_RUNNING);
  4393. }
  4394. if (jp) {
  4395. struct procstat *ps = &jp->ps[jp->nprocs++];
  4396. ps->ps_pid = pid;
  4397. ps->ps_status = -1;
  4398. ps->ps_cmd = nullstr;
  4399. #if JOBS
  4400. if (doing_jobctl && n)
  4401. ps->ps_cmd = commandtext(n);
  4402. #endif
  4403. }
  4404. }
  4405. static int
  4406. forkshell(struct job *jp, union node *n, int mode)
  4407. {
  4408. int pid;
  4409. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4410. pid = fork();
  4411. if (pid < 0) {
  4412. TRACE(("Fork failed, errno=%d", errno));
  4413. if (jp)
  4414. freejob(jp);
  4415. ash_msg_and_raise_error("can't fork");
  4416. }
  4417. if (pid == 0) {
  4418. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4419. forkchild(jp, n, mode);
  4420. } else {
  4421. forkparent(jp, n, mode, pid);
  4422. }
  4423. return pid;
  4424. }
  4425. /*
  4426. * Wait for job to finish.
  4427. *
  4428. * Under job control we have the problem that while a child process
  4429. * is running interrupts generated by the user are sent to the child
  4430. * but not to the shell. This means that an infinite loop started by
  4431. * an interactive user may be hard to kill. With job control turned off,
  4432. * an interactive user may place an interactive program inside a loop.
  4433. * If the interactive program catches interrupts, the user doesn't want
  4434. * these interrupts to also abort the loop. The approach we take here
  4435. * is to have the shell ignore interrupt signals while waiting for a
  4436. * foreground process to terminate, and then send itself an interrupt
  4437. * signal if the child process was terminated by an interrupt signal.
  4438. * Unfortunately, some programs want to do a bit of cleanup and then
  4439. * exit on interrupt; unless these processes terminate themselves by
  4440. * sending a signal to themselves (instead of calling exit) they will
  4441. * confuse this approach.
  4442. *
  4443. * Called with interrupts off.
  4444. */
  4445. static int
  4446. waitforjob(struct job *jp)
  4447. {
  4448. int st;
  4449. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4450. INT_OFF;
  4451. while (jp->state == JOBRUNNING) {
  4452. /* In non-interactive shells, we _can_ get
  4453. * a keyboard signal here and be EINTRed,
  4454. * but we just loop back, waiting for command to complete.
  4455. *
  4456. * man bash:
  4457. * "If bash is waiting for a command to complete and receives
  4458. * a signal for which a trap has been set, the trap
  4459. * will not be executed until the command completes."
  4460. *
  4461. * Reality is that even if trap is not set, bash
  4462. * will not act on the signal until command completes.
  4463. * Try this. sleep5intoff.c:
  4464. * #include <signal.h>
  4465. * #include <unistd.h>
  4466. * int main() {
  4467. * sigset_t set;
  4468. * sigemptyset(&set);
  4469. * sigaddset(&set, SIGINT);
  4470. * sigaddset(&set, SIGQUIT);
  4471. * sigprocmask(SIG_BLOCK, &set, NULL);
  4472. * sleep(5);
  4473. * return 0;
  4474. * }
  4475. * $ bash -c './sleep5intoff; echo hi'
  4476. * ^C^C^C^C <--- pressing ^C once a second
  4477. * $ _
  4478. * $ bash -c './sleep5intoff; echo hi'
  4479. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4480. * $ _
  4481. */
  4482. dowait(DOWAIT_BLOCK, jp);
  4483. }
  4484. INT_ON;
  4485. st = getstatus(jp);
  4486. #if JOBS
  4487. if (jp->jobctl) {
  4488. xtcsetpgrp(ttyfd, rootpid);
  4489. /*
  4490. * This is truly gross.
  4491. * If we're doing job control, then we did a TIOCSPGRP which
  4492. * caused us (the shell) to no longer be in the controlling
  4493. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4494. * intuit from the subprocess exit status whether a SIGINT
  4495. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4496. */
  4497. if (jp->sigint) /* TODO: do the same with all signals */
  4498. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4499. }
  4500. if (jp->state == JOBDONE)
  4501. #endif
  4502. freejob(jp);
  4503. return st;
  4504. }
  4505. /*
  4506. * return 1 if there are stopped jobs, otherwise 0
  4507. */
  4508. static int
  4509. stoppedjobs(void)
  4510. {
  4511. struct job *jp;
  4512. int retval;
  4513. retval = 0;
  4514. if (job_warning)
  4515. goto out;
  4516. jp = curjob;
  4517. if (jp && jp->state == JOBSTOPPED) {
  4518. out2str("You have stopped jobs.\n");
  4519. job_warning = 2;
  4520. retval++;
  4521. }
  4522. out:
  4523. return retval;
  4524. }
  4525. /* ============ redir.c
  4526. *
  4527. * Code for dealing with input/output redirection.
  4528. */
  4529. #undef EMPTY
  4530. #undef CLOSED
  4531. #define EMPTY -2 /* marks an unused slot in redirtab */
  4532. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4533. /*
  4534. * Open a file in noclobber mode.
  4535. * The code was copied from bash.
  4536. */
  4537. static int
  4538. noclobberopen(const char *fname)
  4539. {
  4540. int r, fd;
  4541. struct stat finfo, finfo2;
  4542. /*
  4543. * If the file exists and is a regular file, return an error
  4544. * immediately.
  4545. */
  4546. r = stat(fname, &finfo);
  4547. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4548. errno = EEXIST;
  4549. return -1;
  4550. }
  4551. /*
  4552. * If the file was not present (r != 0), make sure we open it
  4553. * exclusively so that if it is created before we open it, our open
  4554. * will fail. Make sure that we do not truncate an existing file.
  4555. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4556. * file was not a regular file, we leave O_EXCL off.
  4557. */
  4558. if (r != 0)
  4559. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4560. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4561. /* If the open failed, return the file descriptor right away. */
  4562. if (fd < 0)
  4563. return fd;
  4564. /*
  4565. * OK, the open succeeded, but the file may have been changed from a
  4566. * non-regular file to a regular file between the stat and the open.
  4567. * We are assuming that the O_EXCL open handles the case where FILENAME
  4568. * did not exist and is symlinked to an existing file between the stat
  4569. * and open.
  4570. */
  4571. /*
  4572. * If we can open it and fstat the file descriptor, and neither check
  4573. * revealed that it was a regular file, and the file has not been
  4574. * replaced, return the file descriptor.
  4575. */
  4576. if (fstat(fd, &finfo2) == 0
  4577. && !S_ISREG(finfo2.st_mode)
  4578. && finfo.st_dev == finfo2.st_dev
  4579. && finfo.st_ino == finfo2.st_ino
  4580. ) {
  4581. return fd;
  4582. }
  4583. /* The file has been replaced. badness. */
  4584. close(fd);
  4585. errno = EEXIST;
  4586. return -1;
  4587. }
  4588. /*
  4589. * Handle here documents. Normally we fork off a process to write the
  4590. * data to a pipe. If the document is short, we can stuff the data in
  4591. * the pipe without forking.
  4592. */
  4593. /* openhere needs this forward reference */
  4594. static void expandhere(union node *arg, int fd);
  4595. static int
  4596. openhere(union node *redir)
  4597. {
  4598. int pip[2];
  4599. size_t len = 0;
  4600. if (pipe(pip) < 0)
  4601. ash_msg_and_raise_error("pipe call failed");
  4602. if (redir->type == NHERE) {
  4603. len = strlen(redir->nhere.doc->narg.text);
  4604. if (len <= PIPE_BUF) {
  4605. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4606. goto out;
  4607. }
  4608. }
  4609. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4610. /* child */
  4611. close(pip[0]);
  4612. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4613. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4614. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4615. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4616. signal(SIGPIPE, SIG_DFL);
  4617. if (redir->type == NHERE)
  4618. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4619. else /* NXHERE */
  4620. expandhere(redir->nhere.doc, pip[1]);
  4621. _exit(EXIT_SUCCESS);
  4622. }
  4623. out:
  4624. close(pip[1]);
  4625. return pip[0];
  4626. }
  4627. static int
  4628. openredirect(union node *redir)
  4629. {
  4630. char *fname;
  4631. int f;
  4632. fname = redir->nfile.expfname;
  4633. switch (redir->nfile.type) {
  4634. case NFROM:
  4635. f = open(fname, O_RDONLY);
  4636. if (f < 0)
  4637. goto eopen;
  4638. break;
  4639. case NFROMTO:
  4640. f = open(fname, O_RDWR|O_CREAT, 0666);
  4641. if (f < 0)
  4642. goto ecreate;
  4643. break;
  4644. case NTO:
  4645. #if ENABLE_ASH_BASH_COMPAT
  4646. case NTO2:
  4647. #endif
  4648. /* Take care of noclobber mode. */
  4649. if (Cflag) {
  4650. f = noclobberopen(fname);
  4651. if (f < 0)
  4652. goto ecreate;
  4653. break;
  4654. }
  4655. /* FALLTHROUGH */
  4656. case NCLOBBER:
  4657. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4658. if (f < 0)
  4659. goto ecreate;
  4660. break;
  4661. case NAPPEND:
  4662. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4663. if (f < 0)
  4664. goto ecreate;
  4665. break;
  4666. default:
  4667. #if DEBUG
  4668. abort();
  4669. #endif
  4670. /* Fall through to eliminate warning. */
  4671. /* Our single caller does this itself */
  4672. // case NTOFD:
  4673. // case NFROMFD:
  4674. // f = -1;
  4675. // break;
  4676. case NHERE:
  4677. case NXHERE:
  4678. f = openhere(redir);
  4679. break;
  4680. }
  4681. return f;
  4682. ecreate:
  4683. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4684. eopen:
  4685. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4686. }
  4687. /*
  4688. * Copy a file descriptor to be >= to. Returns -1
  4689. * if the source file descriptor is closed, EMPTY if there are no unused
  4690. * file descriptors left.
  4691. */
  4692. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4693. * old code was doing close(to) prior to copyfd() to achieve the same */
  4694. enum {
  4695. COPYFD_EXACT = (int)~(INT_MAX),
  4696. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4697. };
  4698. static int
  4699. copyfd(int from, int to)
  4700. {
  4701. int newfd;
  4702. if (to & COPYFD_EXACT) {
  4703. to &= ~COPYFD_EXACT;
  4704. /*if (from != to)*/
  4705. newfd = dup2(from, to);
  4706. } else {
  4707. newfd = fcntl(from, F_DUPFD, to);
  4708. }
  4709. if (newfd < 0) {
  4710. if (errno == EMFILE)
  4711. return EMPTY;
  4712. /* Happens when source fd is not open: try "echo >&99" */
  4713. ash_msg_and_raise_error("%d: %m", from);
  4714. }
  4715. return newfd;
  4716. }
  4717. /* Struct def and variable are moved down to the first usage site */
  4718. struct two_fd_t {
  4719. int orig, copy;
  4720. };
  4721. struct redirtab {
  4722. struct redirtab *next;
  4723. int nullredirs;
  4724. int pair_count;
  4725. struct two_fd_t two_fd[];
  4726. };
  4727. #define redirlist (G_var.redirlist)
  4728. static int need_to_remember(struct redirtab *rp, int fd)
  4729. {
  4730. int i;
  4731. if (!rp) /* remembering was not requested */
  4732. return 0;
  4733. for (i = 0; i < rp->pair_count; i++) {
  4734. if (rp->two_fd[i].orig == fd) {
  4735. /* already remembered */
  4736. return 0;
  4737. }
  4738. }
  4739. return 1;
  4740. }
  4741. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4742. static int is_hidden_fd(struct redirtab *rp, int fd)
  4743. {
  4744. int i;
  4745. struct parsefile *pf;
  4746. if (fd == -1)
  4747. return 0;
  4748. /* Check open scripts' fds */
  4749. pf = g_parsefile;
  4750. while (pf) {
  4751. /* We skip pf_fd == 0 case because of the following case:
  4752. * $ ash # running ash interactively
  4753. * $ . ./script.sh
  4754. * and in script.sh: "exec 9>&0".
  4755. * Even though top-level pf_fd _is_ 0,
  4756. * it's still ok to use it: "read" builtin uses it,
  4757. * why should we cripple "exec" builtin?
  4758. */
  4759. if (pf->pf_fd > 0 && fd == pf->pf_fd) {
  4760. return 1;
  4761. }
  4762. pf = pf->prev;
  4763. }
  4764. if (!rp)
  4765. return 0;
  4766. /* Check saved fds of redirects */
  4767. fd |= COPYFD_RESTORE;
  4768. for (i = 0; i < rp->pair_count; i++) {
  4769. if (rp->two_fd[i].copy == fd) {
  4770. return 1;
  4771. }
  4772. }
  4773. return 0;
  4774. }
  4775. /*
  4776. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4777. * old file descriptors are stashed away so that the redirection can be
  4778. * undone by calling popredir.
  4779. */
  4780. /* flags passed to redirect */
  4781. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4782. #define REDIR_SAVEFD2 03 /* set preverrout */
  4783. static void
  4784. redirect(union node *redir, int flags)
  4785. {
  4786. struct redirtab *sv;
  4787. int sv_pos;
  4788. int i;
  4789. int fd;
  4790. int newfd;
  4791. int copied_fd2 = -1;
  4792. g_nullredirs++;
  4793. if (!redir) {
  4794. return;
  4795. }
  4796. sv = NULL;
  4797. sv_pos = 0;
  4798. INT_OFF;
  4799. if (flags & REDIR_PUSH) {
  4800. union node *tmp = redir;
  4801. do {
  4802. sv_pos++;
  4803. #if ENABLE_ASH_BASH_COMPAT
  4804. if (tmp->nfile.type == NTO2)
  4805. sv_pos++;
  4806. #endif
  4807. tmp = tmp->nfile.next;
  4808. } while (tmp);
  4809. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4810. sv->next = redirlist;
  4811. sv->pair_count = sv_pos;
  4812. redirlist = sv;
  4813. sv->nullredirs = g_nullredirs - 1;
  4814. g_nullredirs = 0;
  4815. while (sv_pos > 0) {
  4816. sv_pos--;
  4817. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4818. }
  4819. }
  4820. do {
  4821. int right_fd = -1;
  4822. fd = redir->nfile.fd;
  4823. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4824. right_fd = redir->ndup.dupfd;
  4825. //bb_error_msg("doing %d > %d", fd, right_fd);
  4826. /* redirect from/to same file descriptor? */
  4827. if (right_fd == fd)
  4828. continue;
  4829. /* "echo >&10" and 10 is a fd opened to a sh script? */
  4830. if (is_hidden_fd(sv, right_fd)) {
  4831. errno = EBADF; /* as if it is closed */
  4832. ash_msg_and_raise_error("%d: %m", right_fd);
  4833. }
  4834. newfd = -1;
  4835. } else {
  4836. newfd = openredirect(redir); /* always >= 0 */
  4837. if (fd == newfd) {
  4838. /* Descriptor wasn't open before redirect.
  4839. * Mark it for close in the future */
  4840. if (need_to_remember(sv, fd)) {
  4841. goto remember_to_close;
  4842. }
  4843. continue;
  4844. }
  4845. }
  4846. #if ENABLE_ASH_BASH_COMPAT
  4847. redirect_more:
  4848. #endif
  4849. if (need_to_remember(sv, fd)) {
  4850. /* Copy old descriptor */
  4851. /* Careful to not accidentally "save"
  4852. * to the same fd as right side fd in N>&M */
  4853. int minfd = right_fd < 10 ? 10 : right_fd + 1;
  4854. i = fcntl(fd, F_DUPFD, minfd);
  4855. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4856. * are closed in popredir() in the child, preventing them from leaking
  4857. * into child. (popredir() also cleans up the mess in case of failures)
  4858. */
  4859. if (i == -1) {
  4860. i = errno;
  4861. if (i != EBADF) {
  4862. /* Strange error (e.g. "too many files" EMFILE?) */
  4863. if (newfd >= 0)
  4864. close(newfd);
  4865. errno = i;
  4866. ash_msg_and_raise_error("%d: %m", fd);
  4867. /* NOTREACHED */
  4868. }
  4869. /* EBADF: it is not open - good, remember to close it */
  4870. remember_to_close:
  4871. i = CLOSED;
  4872. } else { /* fd is open, save its copy */
  4873. /* "exec fd>&-" should not close fds
  4874. * which point to script file(s).
  4875. * Force them to be restored afterwards */
  4876. if (is_hidden_fd(sv, fd))
  4877. i |= COPYFD_RESTORE;
  4878. }
  4879. if (fd == 2)
  4880. copied_fd2 = i;
  4881. sv->two_fd[sv_pos].orig = fd;
  4882. sv->two_fd[sv_pos].copy = i;
  4883. sv_pos++;
  4884. }
  4885. if (newfd < 0) {
  4886. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4887. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4888. /* Don't want to trigger debugging */
  4889. if (fd != -1)
  4890. close(fd);
  4891. } else {
  4892. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4893. }
  4894. } else if (fd != newfd) { /* move newfd to fd */
  4895. copyfd(newfd, fd | COPYFD_EXACT);
  4896. #if ENABLE_ASH_BASH_COMPAT
  4897. if (!(redir->nfile.type == NTO2 && fd == 2))
  4898. #endif
  4899. close(newfd);
  4900. }
  4901. #if ENABLE_ASH_BASH_COMPAT
  4902. if (redir->nfile.type == NTO2 && fd == 1) {
  4903. /* We already redirected it to fd 1, now copy it to 2 */
  4904. newfd = 1;
  4905. fd = 2;
  4906. goto redirect_more;
  4907. }
  4908. #endif
  4909. } while ((redir = redir->nfile.next) != NULL);
  4910. INT_ON;
  4911. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4912. preverrout_fd = copied_fd2;
  4913. }
  4914. /*
  4915. * Undo the effects of the last redirection.
  4916. */
  4917. static void
  4918. popredir(int drop, int restore)
  4919. {
  4920. struct redirtab *rp;
  4921. int i;
  4922. if (--g_nullredirs >= 0)
  4923. return;
  4924. INT_OFF;
  4925. rp = redirlist;
  4926. for (i = 0; i < rp->pair_count; i++) {
  4927. int fd = rp->two_fd[i].orig;
  4928. int copy = rp->two_fd[i].copy;
  4929. if (copy == CLOSED) {
  4930. if (!drop)
  4931. close(fd);
  4932. continue;
  4933. }
  4934. if (copy != EMPTY) {
  4935. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4936. copy &= ~COPYFD_RESTORE;
  4937. /*close(fd);*/
  4938. copyfd(copy, fd | COPYFD_EXACT);
  4939. }
  4940. close(copy & ~COPYFD_RESTORE);
  4941. }
  4942. }
  4943. redirlist = rp->next;
  4944. g_nullredirs = rp->nullredirs;
  4945. free(rp);
  4946. INT_ON;
  4947. }
  4948. /*
  4949. * Undo all redirections. Called on error or interrupt.
  4950. */
  4951. /*
  4952. * Discard all saved file descriptors.
  4953. */
  4954. static void
  4955. clearredir(int drop)
  4956. {
  4957. for (;;) {
  4958. g_nullredirs = 0;
  4959. if (!redirlist)
  4960. break;
  4961. popredir(drop, /*restore:*/ 0);
  4962. }
  4963. }
  4964. static int
  4965. redirectsafe(union node *redir, int flags)
  4966. {
  4967. int err;
  4968. volatile int saveint;
  4969. struct jmploc *volatile savehandler = exception_handler;
  4970. struct jmploc jmploc;
  4971. SAVE_INT(saveint);
  4972. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4973. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4974. if (!err) {
  4975. exception_handler = &jmploc;
  4976. redirect(redir, flags);
  4977. }
  4978. exception_handler = savehandler;
  4979. if (err && exception_type != EXERROR)
  4980. longjmp(exception_handler->loc, 1);
  4981. RESTORE_INT(saveint);
  4982. return err;
  4983. }
  4984. /* ============ Routines to expand arguments to commands
  4985. *
  4986. * We have to deal with backquotes, shell variables, and file metacharacters.
  4987. */
  4988. #if ENABLE_SH_MATH_SUPPORT
  4989. static arith_t
  4990. ash_arith(const char *s)
  4991. {
  4992. arith_state_t math_state;
  4993. arith_t result;
  4994. math_state.lookupvar = lookupvar;
  4995. math_state.setvar = setvar0;
  4996. //math_state.endofname = endofname;
  4997. INT_OFF;
  4998. result = arith(&math_state, s);
  4999. if (math_state.errmsg)
  5000. ash_msg_and_raise_error(math_state.errmsg);
  5001. INT_ON;
  5002. return result;
  5003. }
  5004. #endif
  5005. /*
  5006. * expandarg flags
  5007. */
  5008. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5009. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5010. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5011. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5012. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5013. #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
  5014. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5015. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5016. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5017. /*
  5018. * rmescape() flags
  5019. */
  5020. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5021. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5022. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5023. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5024. #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
  5025. /* Add CTLESC when necessary. */
  5026. #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT | EXP_REDIR)
  5027. /* Do not skip NUL characters. */
  5028. #define QUOTES_KEEPNUL EXP_TILDE
  5029. /*
  5030. * Structure specifying which parts of the string should be searched
  5031. * for IFS characters.
  5032. */
  5033. struct ifsregion {
  5034. struct ifsregion *next; /* next region in list */
  5035. int begoff; /* offset of start of region */
  5036. int endoff; /* offset of end of region */
  5037. int nulonly; /* search for nul bytes only */
  5038. };
  5039. struct arglist {
  5040. struct strlist *list;
  5041. struct strlist **lastp;
  5042. };
  5043. /* output of current string */
  5044. static char *expdest;
  5045. /* list of back quote expressions */
  5046. static struct nodelist *argbackq;
  5047. /* first struct in list of ifs regions */
  5048. static struct ifsregion ifsfirst;
  5049. /* last struct in list */
  5050. static struct ifsregion *ifslastp;
  5051. /* holds expanded arg list */
  5052. static struct arglist exparg;
  5053. /*
  5054. * Our own itoa().
  5055. */
  5056. #if !ENABLE_SH_MATH_SUPPORT
  5057. /* cvtnum() is used even if math support is off (to prepare $? values and such) */
  5058. typedef long arith_t;
  5059. # define ARITH_FMT "%ld"
  5060. #endif
  5061. static int
  5062. cvtnum(arith_t num)
  5063. {
  5064. int len;
  5065. expdest = makestrspace(sizeof(arith_t)*3 + 2, expdest);
  5066. len = fmtstr(expdest, sizeof(arith_t)*3 + 2, ARITH_FMT, num);
  5067. STADJUST(len, expdest);
  5068. return len;
  5069. }
  5070. static size_t
  5071. esclen(const char *start, const char *p)
  5072. {
  5073. size_t esc = 0;
  5074. while (p > start && (unsigned char)*--p == CTLESC) {
  5075. esc++;
  5076. }
  5077. return esc;
  5078. }
  5079. /*
  5080. * Remove any CTLESC characters from a string.
  5081. */
  5082. static char *
  5083. rmescapes(char *str, int flag)
  5084. {
  5085. static const char qchars[] ALIGN1 = {
  5086. IF_ASH_BASH_COMPAT('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5087. char *p, *q, *r;
  5088. unsigned inquotes;
  5089. unsigned protect_against_glob;
  5090. unsigned globbing;
  5091. IF_ASH_BASH_COMPAT(unsigned slash = flag & RMESCAPE_SLASH;)
  5092. p = strpbrk(str, qchars IF_ASH_BASH_COMPAT(+ !slash));
  5093. if (!p)
  5094. return str;
  5095. q = p;
  5096. r = str;
  5097. if (flag & RMESCAPE_ALLOC) {
  5098. size_t len = p - str;
  5099. size_t fulllen = len + strlen(p) + 1;
  5100. if (flag & RMESCAPE_GROW) {
  5101. int strloc = str - (char *)stackblock();
  5102. r = makestrspace(fulllen, expdest);
  5103. /* p and str may be invalidated by makestrspace */
  5104. str = (char *)stackblock() + strloc;
  5105. p = str + len;
  5106. } else if (flag & RMESCAPE_HEAP) {
  5107. r = ckmalloc(fulllen);
  5108. } else {
  5109. r = stalloc(fulllen);
  5110. }
  5111. q = r;
  5112. if (len > 0) {
  5113. q = (char *)memcpy(q, str, len) + len;
  5114. }
  5115. }
  5116. inquotes = 0;
  5117. globbing = flag & RMESCAPE_GLOB;
  5118. protect_against_glob = globbing;
  5119. while (*p) {
  5120. if ((unsigned char)*p == CTLQUOTEMARK) {
  5121. // Note: both inquotes and protect_against_glob only affect whether
  5122. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5123. inquotes = ~inquotes;
  5124. p++;
  5125. protect_against_glob = globbing;
  5126. continue;
  5127. }
  5128. if ((unsigned char)*p == CTLESC) {
  5129. p++;
  5130. if (protect_against_glob) {
  5131. *q++ = '\\';
  5132. }
  5133. } else if (*p == '\\' && !inquotes) {
  5134. /* naked back slash */
  5135. protect_against_glob = 0;
  5136. goto copy;
  5137. }
  5138. #if ENABLE_ASH_BASH_COMPAT
  5139. else if (*p == '/' && slash) {
  5140. /* stop handling globbing and mark location of slash */
  5141. globbing = slash = 0;
  5142. *p = CTLESC;
  5143. }
  5144. #endif
  5145. protect_against_glob = globbing;
  5146. copy:
  5147. *q++ = *p++;
  5148. }
  5149. *q = '\0';
  5150. if (flag & RMESCAPE_GROW) {
  5151. expdest = r;
  5152. STADJUST(q - r + 1, expdest);
  5153. }
  5154. return r;
  5155. }
  5156. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5157. /*
  5158. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5159. *
  5160. * Returns an stalloced string.
  5161. */
  5162. static char *
  5163. preglob(const char *pattern, int flag)
  5164. {
  5165. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
  5166. }
  5167. /*
  5168. * Put a string on the stack.
  5169. */
  5170. static void
  5171. memtodest(const char *p, size_t len, int syntax, int quotes)
  5172. {
  5173. char *q;
  5174. if (!len)
  5175. return;
  5176. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5177. do {
  5178. unsigned char c = *p++;
  5179. if (c) {
  5180. int n = SIT(c, syntax);
  5181. if ((quotes & QUOTES_ESC) &&
  5182. ((n == CCTL) ||
  5183. (((quotes & EXP_FULL) || syntax != BASESYNTAX) &&
  5184. n == CBACK)))
  5185. USTPUTC(CTLESC, q);
  5186. } else if (!(quotes & QUOTES_KEEPNUL))
  5187. continue;
  5188. USTPUTC(c, q);
  5189. } while (--len);
  5190. expdest = q;
  5191. }
  5192. static size_t
  5193. strtodest(const char *p, int syntax, int quotes)
  5194. {
  5195. size_t len = strlen(p);
  5196. memtodest(p, len, syntax, quotes);
  5197. return len;
  5198. }
  5199. /*
  5200. * Record the fact that we have to scan this region of the
  5201. * string for IFS characters.
  5202. */
  5203. static void
  5204. recordregion(int start, int end, int nulonly)
  5205. {
  5206. struct ifsregion *ifsp;
  5207. if (ifslastp == NULL) {
  5208. ifsp = &ifsfirst;
  5209. } else {
  5210. INT_OFF;
  5211. ifsp = ckzalloc(sizeof(*ifsp));
  5212. /*ifsp->next = NULL; - ckzalloc did it */
  5213. ifslastp->next = ifsp;
  5214. INT_ON;
  5215. }
  5216. ifslastp = ifsp;
  5217. ifslastp->begoff = start;
  5218. ifslastp->endoff = end;
  5219. ifslastp->nulonly = nulonly;
  5220. }
  5221. static void
  5222. removerecordregions(int endoff)
  5223. {
  5224. if (ifslastp == NULL)
  5225. return;
  5226. if (ifsfirst.endoff > endoff) {
  5227. while (ifsfirst.next) {
  5228. struct ifsregion *ifsp;
  5229. INT_OFF;
  5230. ifsp = ifsfirst.next->next;
  5231. free(ifsfirst.next);
  5232. ifsfirst.next = ifsp;
  5233. INT_ON;
  5234. }
  5235. if (ifsfirst.begoff > endoff) {
  5236. ifslastp = NULL;
  5237. } else {
  5238. ifslastp = &ifsfirst;
  5239. ifsfirst.endoff = endoff;
  5240. }
  5241. return;
  5242. }
  5243. ifslastp = &ifsfirst;
  5244. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5245. ifslastp = ifslastp->next;
  5246. while (ifslastp->next) {
  5247. struct ifsregion *ifsp;
  5248. INT_OFF;
  5249. ifsp = ifslastp->next->next;
  5250. free(ifslastp->next);
  5251. ifslastp->next = ifsp;
  5252. INT_ON;
  5253. }
  5254. if (ifslastp->endoff > endoff)
  5255. ifslastp->endoff = endoff;
  5256. }
  5257. static char *
  5258. exptilde(char *startp, char *p, int flags)
  5259. {
  5260. unsigned char c;
  5261. char *name;
  5262. struct passwd *pw;
  5263. const char *home;
  5264. int quotes = flags & QUOTES_ESC;
  5265. name = p + 1;
  5266. while ((c = *++p) != '\0') {
  5267. switch (c) {
  5268. case CTLESC:
  5269. return startp;
  5270. case CTLQUOTEMARK:
  5271. return startp;
  5272. case ':':
  5273. if (flags & EXP_VARTILDE)
  5274. goto done;
  5275. break;
  5276. case '/':
  5277. case CTLENDVAR:
  5278. goto done;
  5279. }
  5280. }
  5281. done:
  5282. *p = '\0';
  5283. if (*name == '\0') {
  5284. home = lookupvar("HOME");
  5285. } else {
  5286. pw = getpwnam(name);
  5287. if (pw == NULL)
  5288. goto lose;
  5289. home = pw->pw_dir;
  5290. }
  5291. if (!home || !*home)
  5292. goto lose;
  5293. *p = c;
  5294. strtodest(home, SQSYNTAX, quotes);
  5295. return p;
  5296. lose:
  5297. *p = c;
  5298. return startp;
  5299. }
  5300. /*
  5301. * Execute a command inside back quotes. If it's a builtin command, we
  5302. * want to save its output in a block obtained from malloc. Otherwise
  5303. * we fork off a subprocess and get the output of the command via a pipe.
  5304. * Should be called with interrupts off.
  5305. */
  5306. struct backcmd { /* result of evalbackcmd */
  5307. int fd; /* file descriptor to read from */
  5308. int nleft; /* number of chars in buffer */
  5309. char *buf; /* buffer */
  5310. struct job *jp; /* job structure for command */
  5311. };
  5312. /* These forward decls are needed to use "eval" code for backticks handling: */
  5313. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5314. #define EV_EXIT 01 /* exit after evaluating tree */
  5315. static void evaltree(union node *, int);
  5316. static void FAST_FUNC
  5317. evalbackcmd(union node *n, struct backcmd *result)
  5318. {
  5319. int saveherefd;
  5320. result->fd = -1;
  5321. result->buf = NULL;
  5322. result->nleft = 0;
  5323. result->jp = NULL;
  5324. if (n == NULL)
  5325. goto out;
  5326. saveherefd = herefd;
  5327. herefd = -1;
  5328. {
  5329. int pip[2];
  5330. struct job *jp;
  5331. if (pipe(pip) < 0)
  5332. ash_msg_and_raise_error("pipe call failed");
  5333. jp = makejob(/*n,*/ 1);
  5334. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5335. FORCE_INT_ON;
  5336. close(pip[0]);
  5337. if (pip[1] != 1) {
  5338. /*close(1);*/
  5339. copyfd(pip[1], 1 | COPYFD_EXACT);
  5340. close(pip[1]);
  5341. }
  5342. eflag = 0;
  5343. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5344. /* NOTREACHED */
  5345. }
  5346. close(pip[1]);
  5347. result->fd = pip[0];
  5348. result->jp = jp;
  5349. }
  5350. herefd = saveherefd;
  5351. out:
  5352. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5353. result->fd, result->buf, result->nleft, result->jp));
  5354. }
  5355. /*
  5356. * Expand stuff in backwards quotes.
  5357. */
  5358. static void
  5359. expbackq(union node *cmd, int flag)
  5360. {
  5361. struct backcmd in;
  5362. int i;
  5363. char buf[128];
  5364. char *p;
  5365. char *dest;
  5366. int startloc;
  5367. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5368. struct stackmark smark;
  5369. INT_OFF;
  5370. setstackmark(&smark);
  5371. dest = expdest;
  5372. startloc = dest - (char *)stackblock();
  5373. grabstackstr(dest);
  5374. evalbackcmd(cmd, &in);
  5375. popstackmark(&smark);
  5376. p = in.buf;
  5377. i = in.nleft;
  5378. if (i == 0)
  5379. goto read;
  5380. for (;;) {
  5381. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5382. read:
  5383. if (in.fd < 0)
  5384. break;
  5385. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5386. TRACE(("expbackq: read returns %d\n", i));
  5387. if (i <= 0)
  5388. break;
  5389. p = buf;
  5390. }
  5391. free(in.buf);
  5392. if (in.fd >= 0) {
  5393. close(in.fd);
  5394. back_exitstatus = waitforjob(in.jp);
  5395. }
  5396. INT_ON;
  5397. /* Eat all trailing newlines */
  5398. dest = expdest;
  5399. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5400. STUNPUTC(dest);
  5401. expdest = dest;
  5402. if (!(flag & EXP_QUOTED))
  5403. recordregion(startloc, dest - (char *)stackblock(), 0);
  5404. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5405. (int)((dest - (char *)stackblock()) - startloc),
  5406. (int)((dest - (char *)stackblock()) - startloc),
  5407. stackblock() + startloc));
  5408. }
  5409. #if ENABLE_SH_MATH_SUPPORT
  5410. /*
  5411. * Expand arithmetic expression. Backup to start of expression,
  5412. * evaluate, place result in (backed up) result, adjust string position.
  5413. */
  5414. static void
  5415. expari(int flag)
  5416. {
  5417. char *p, *start;
  5418. int begoff;
  5419. int len;
  5420. /* ifsfree(); */
  5421. /*
  5422. * This routine is slightly over-complicated for
  5423. * efficiency. Next we scan backwards looking for the
  5424. * start of arithmetic.
  5425. */
  5426. start = stackblock();
  5427. p = expdest - 1;
  5428. *p = '\0';
  5429. p--;
  5430. while (1) {
  5431. int esc;
  5432. while ((unsigned char)*p != CTLARI) {
  5433. p--;
  5434. #if DEBUG
  5435. if (p < start) {
  5436. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5437. }
  5438. #endif
  5439. }
  5440. esc = esclen(start, p);
  5441. if (!(esc % 2)) {
  5442. break;
  5443. }
  5444. p -= esc + 1;
  5445. }
  5446. begoff = p - start;
  5447. removerecordregions(begoff);
  5448. expdest = p;
  5449. if (flag & QUOTES_ESC)
  5450. rmescapes(p + 1, 0);
  5451. len = cvtnum(ash_arith(p + 1));
  5452. if (!(flag & EXP_QUOTED))
  5453. recordregion(begoff, begoff + len, 0);
  5454. }
  5455. #endif
  5456. /* argstr needs it */
  5457. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5458. /*
  5459. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5460. * characters to allow for further processing. Otherwise treat
  5461. * $@ like $* since no splitting will be performed.
  5462. *
  5463. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5464. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5465. * for correct expansion of "B=$A" word.
  5466. */
  5467. static void
  5468. argstr(char *p, int flags, struct strlist *var_str_list)
  5469. {
  5470. static const char spclchars[] ALIGN1 = {
  5471. '=',
  5472. ':',
  5473. CTLQUOTEMARK,
  5474. CTLENDVAR,
  5475. CTLESC,
  5476. CTLVAR,
  5477. CTLBACKQ,
  5478. #if ENABLE_SH_MATH_SUPPORT
  5479. CTLENDARI,
  5480. #endif
  5481. '\0'
  5482. };
  5483. const char *reject = spclchars;
  5484. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5485. int inquotes;
  5486. size_t length;
  5487. int startloc;
  5488. if (!(flags & EXP_VARTILDE)) {
  5489. reject += 2;
  5490. } else if (flags & EXP_VARTILDE2) {
  5491. reject++;
  5492. }
  5493. inquotes = 0;
  5494. length = 0;
  5495. if (flags & EXP_TILDE) {
  5496. char *q;
  5497. flags &= ~EXP_TILDE;
  5498. tilde:
  5499. q = p;
  5500. if (*q == '~')
  5501. p = exptilde(p, q, flags);
  5502. }
  5503. start:
  5504. startloc = expdest - (char *)stackblock();
  5505. for (;;) {
  5506. unsigned char c;
  5507. length += strcspn(p + length, reject);
  5508. c = p[length];
  5509. if (c) {
  5510. if (!(c & 0x80)
  5511. IF_SH_MATH_SUPPORT(|| c == CTLENDARI)
  5512. ) {
  5513. /* c == '=' || c == ':' || c == CTLENDARI */
  5514. length++;
  5515. }
  5516. }
  5517. if (length > 0) {
  5518. int newloc;
  5519. expdest = stack_nputstr(p, length, expdest);
  5520. newloc = expdest - (char *)stackblock();
  5521. if (breakall && !inquotes && newloc > startloc) {
  5522. recordregion(startloc, newloc, 0);
  5523. }
  5524. startloc = newloc;
  5525. }
  5526. p += length + 1;
  5527. length = 0;
  5528. switch (c) {
  5529. case '\0':
  5530. goto breakloop;
  5531. case '=':
  5532. if (flags & EXP_VARTILDE2) {
  5533. p--;
  5534. continue;
  5535. }
  5536. flags |= EXP_VARTILDE2;
  5537. reject++;
  5538. /* fall through */
  5539. case ':':
  5540. /*
  5541. * sort of a hack - expand tildes in variable
  5542. * assignments (after the first '=' and after ':'s).
  5543. */
  5544. if (*--p == '~') {
  5545. goto tilde;
  5546. }
  5547. continue;
  5548. }
  5549. switch (c) {
  5550. case CTLENDVAR: /* ??? */
  5551. goto breakloop;
  5552. case CTLQUOTEMARK:
  5553. inquotes ^= EXP_QUOTED;
  5554. /* "$@" syntax adherence hack */
  5555. if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  5556. p = evalvar(p + 1, flags | inquotes, /* var_str_list: */ NULL) + 1;
  5557. goto start;
  5558. }
  5559. addquote:
  5560. if (flags & QUOTES_ESC) {
  5561. p--;
  5562. length++;
  5563. startloc++;
  5564. }
  5565. break;
  5566. case CTLESC:
  5567. startloc++;
  5568. length++;
  5569. /*
  5570. * Quoted parameter expansion pattern: remove quote
  5571. * unless inside inner quotes or we have a literal
  5572. * backslash.
  5573. */
  5574. if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
  5575. EXP_QPAT && *p != '\\')
  5576. break;
  5577. goto addquote;
  5578. case CTLVAR:
  5579. TRACE(("argstr: evalvar('%s')\n", p));
  5580. p = evalvar(p, flags | inquotes, var_str_list);
  5581. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  5582. goto start;
  5583. case CTLBACKQ:
  5584. expbackq(argbackq->n, flags | inquotes);
  5585. argbackq = argbackq->next;
  5586. goto start;
  5587. #if ENABLE_SH_MATH_SUPPORT
  5588. case CTLENDARI:
  5589. p--;
  5590. expari(flags | inquotes);
  5591. goto start;
  5592. #endif
  5593. }
  5594. }
  5595. breakloop: ;
  5596. }
  5597. static char *
  5598. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  5599. char *pattern, int quotes, int zero)
  5600. {
  5601. char *loc, *loc2;
  5602. char c;
  5603. loc = startp;
  5604. loc2 = rmesc;
  5605. do {
  5606. int match;
  5607. const char *s = loc2;
  5608. c = *loc2;
  5609. if (zero) {
  5610. *loc2 = '\0';
  5611. s = rmesc;
  5612. }
  5613. match = pmatch(pattern, s);
  5614. *loc2 = c;
  5615. if (match)
  5616. return loc;
  5617. if (quotes && (unsigned char)*loc == CTLESC)
  5618. loc++;
  5619. loc++;
  5620. loc2++;
  5621. } while (c);
  5622. return NULL;
  5623. }
  5624. static char *
  5625. scanright(char *startp, char *rmesc, char *rmescend,
  5626. char *pattern, int quotes, int match_at_start)
  5627. {
  5628. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5629. int try2optimize = match_at_start;
  5630. #endif
  5631. int esc = 0;
  5632. char *loc;
  5633. char *loc2;
  5634. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  5635. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  5636. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  5637. * Logic:
  5638. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  5639. * and on each iteration they go back two/one char until they reach the beginning.
  5640. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  5641. */
  5642. /* TODO: document in what other circumstances we are called. */
  5643. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5644. int match;
  5645. char c = *loc2;
  5646. const char *s = loc2;
  5647. if (match_at_start) {
  5648. *loc2 = '\0';
  5649. s = rmesc;
  5650. }
  5651. match = pmatch(pattern, s);
  5652. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  5653. *loc2 = c;
  5654. if (match)
  5655. return loc;
  5656. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  5657. if (try2optimize) {
  5658. /* Maybe we can optimize this:
  5659. * if pattern ends with unescaped *, we can avoid checking
  5660. * shorter strings: if "foo*" doesnt match "raw_value_of_v",
  5661. * it wont match truncated "raw_value_of_" strings too.
  5662. */
  5663. unsigned plen = strlen(pattern);
  5664. /* Does it end with "*"? */
  5665. if (plen != 0 && pattern[--plen] == '*') {
  5666. /* "xxxx*" is not escaped */
  5667. /* "xxx\*" is escaped */
  5668. /* "xx\\*" is not escaped */
  5669. /* "x\\\*" is escaped */
  5670. int slashes = 0;
  5671. while (plen != 0 && pattern[--plen] == '\\')
  5672. slashes++;
  5673. if (!(slashes & 1))
  5674. break; /* ends with unescaped "*" */
  5675. }
  5676. try2optimize = 0;
  5677. }
  5678. #endif
  5679. loc--;
  5680. if (quotes) {
  5681. if (--esc < 0) {
  5682. esc = esclen(startp, loc);
  5683. }
  5684. if (esc % 2) {
  5685. esc--;
  5686. loc--;
  5687. }
  5688. }
  5689. }
  5690. return NULL;
  5691. }
  5692. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5693. static void
  5694. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5695. {
  5696. const char *msg;
  5697. const char *tail;
  5698. tail = nullstr;
  5699. msg = "parameter not set";
  5700. if (umsg) {
  5701. if ((unsigned char)*end == CTLENDVAR) {
  5702. if (varflags & VSNUL)
  5703. tail = " or null";
  5704. } else {
  5705. msg = umsg;
  5706. }
  5707. }
  5708. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  5709. }
  5710. static const char *
  5711. subevalvar(char *p, char *varname, int strloc, int subtype,
  5712. int startloc, int varflags, int flag, struct strlist *var_str_list)
  5713. {
  5714. struct nodelist *saveargbackq = argbackq;
  5715. int quotes = flag & QUOTES_ESC;
  5716. char *startp;
  5717. char *loc;
  5718. char *rmesc, *rmescend;
  5719. char *str;
  5720. IF_ASH_BASH_COMPAT(char *repl = NULL;)
  5721. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5722. int saveherefd = herefd;
  5723. int amount, resetloc;
  5724. IF_ASH_BASH_COMPAT(int workloc;)
  5725. int zero;
  5726. char *(*scan)(char*, char*, char*, char*, int, int);
  5727. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  5728. // p, varname, strloc, subtype, startloc, varflags, quotes);
  5729. herefd = -1;
  5730. argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
  5731. (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0),
  5732. var_str_list);
  5733. STPUTC('\0', expdest);
  5734. herefd = saveherefd;
  5735. argbackq = saveargbackq;
  5736. startp = (char *)stackblock() + startloc;
  5737. switch (subtype) {
  5738. case VSASSIGN:
  5739. setvar0(varname, startp);
  5740. amount = startp - expdest;
  5741. STADJUST(amount, expdest);
  5742. return startp;
  5743. case VSQUESTION:
  5744. varunset(p, varname, startp, varflags);
  5745. /* NOTREACHED */
  5746. #if ENABLE_ASH_BASH_COMPAT
  5747. case VSSUBSTR:
  5748. loc = str = stackblock() + strloc;
  5749. /* Read POS in ${var:POS:LEN} */
  5750. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5751. len = str - startp - 1;
  5752. /* *loc != '\0', guaranteed by parser */
  5753. if (quotes) {
  5754. char *ptr;
  5755. /* Adjust the length by the number of escapes */
  5756. for (ptr = startp; ptr < (str - 1); ptr++) {
  5757. if ((unsigned char)*ptr == CTLESC) {
  5758. len--;
  5759. ptr++;
  5760. }
  5761. }
  5762. }
  5763. orig_len = len;
  5764. if (*loc++ == ':') {
  5765. /* ${var::LEN} */
  5766. len = number(loc);
  5767. } else {
  5768. /* Skip POS in ${var:POS:LEN} */
  5769. len = orig_len;
  5770. while (*loc && *loc != ':') {
  5771. /* TODO?
  5772. * bash complains on: var=qwe; echo ${var:1a:123}
  5773. if (!isdigit(*loc))
  5774. ash_msg_and_raise_error(msg_illnum, str);
  5775. */
  5776. loc++;
  5777. }
  5778. if (*loc++ == ':') {
  5779. len = number(loc);
  5780. }
  5781. }
  5782. if (pos < 0) {
  5783. /* ${VAR:$((-n)):l} starts n chars from the end */
  5784. pos = orig_len + pos;
  5785. }
  5786. if ((unsigned)pos >= orig_len) {
  5787. /* apart from obvious ${VAR:999999:l},
  5788. * covers ${VAR:$((-9999999)):l} - result is ""
  5789. * (bash-compat)
  5790. */
  5791. pos = 0;
  5792. len = 0;
  5793. }
  5794. if (len > (orig_len - pos))
  5795. len = orig_len - pos;
  5796. for (str = startp; pos; str++, pos--) {
  5797. if (quotes && (unsigned char)*str == CTLESC)
  5798. str++;
  5799. }
  5800. for (loc = startp; len; len--) {
  5801. if (quotes && (unsigned char)*str == CTLESC)
  5802. *loc++ = *str++;
  5803. *loc++ = *str++;
  5804. }
  5805. *loc = '\0';
  5806. amount = loc - expdest;
  5807. STADJUST(amount, expdest);
  5808. return loc;
  5809. #endif
  5810. }
  5811. resetloc = expdest - (char *)stackblock();
  5812. /* We'll comeback here if we grow the stack while handling
  5813. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5814. * stack will need rebasing, and we'll need to remove our work
  5815. * areas each time
  5816. */
  5817. IF_ASH_BASH_COMPAT(restart:)
  5818. amount = expdest - ((char *)stackblock() + resetloc);
  5819. STADJUST(-amount, expdest);
  5820. startp = (char *)stackblock() + startloc;
  5821. rmesc = startp;
  5822. rmescend = (char *)stackblock() + strloc;
  5823. if (quotes) {
  5824. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5825. if (rmesc != startp) {
  5826. rmescend = expdest;
  5827. startp = (char *)stackblock() + startloc;
  5828. }
  5829. }
  5830. rmescend--;
  5831. str = (char *)stackblock() + strloc;
  5832. /*
  5833. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  5834. * The result is a_\_z_c (not a\_\_z_c)!
  5835. *
  5836. * The search pattern and replace string treat backslashes differently!
  5837. * RMESCAPE_SLASH causes preglob to work differently on the pattern
  5838. * and string. It's only used on the first call.
  5839. */
  5840. preglob(str, IF_ASH_BASH_COMPAT(
  5841. (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
  5842. RMESCAPE_SLASH :) 0);
  5843. #if ENABLE_ASH_BASH_COMPAT
  5844. workloc = expdest - (char *)stackblock();
  5845. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5846. char *idx, *end;
  5847. if (!repl) {
  5848. if ((repl=strchr(str, CTLESC)))
  5849. *repl++ = '\0';
  5850. else
  5851. repl = nullstr;
  5852. }
  5853. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  5854. /* If there's no pattern to match, return the expansion unmolested */
  5855. if (str[0] == '\0')
  5856. return NULL;
  5857. len = 0;
  5858. idx = startp;
  5859. end = str - 1;
  5860. while (idx < end) {
  5861. try_to_match:
  5862. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5863. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  5864. if (!loc) {
  5865. /* No match, advance */
  5866. char *restart_detect = stackblock();
  5867. skip_matching:
  5868. STPUTC(*idx, expdest);
  5869. if (quotes && (unsigned char)*idx == CTLESC) {
  5870. idx++;
  5871. len++;
  5872. STPUTC(*idx, expdest);
  5873. }
  5874. if (stackblock() != restart_detect)
  5875. goto restart;
  5876. idx++;
  5877. len++;
  5878. rmesc++;
  5879. /* continue; - prone to quadratic behavior, smarter code: */
  5880. if (idx >= end)
  5881. break;
  5882. if (str[0] == '*') {
  5883. /* Pattern is "*foo". If "*foo" does not match "long_string",
  5884. * it would never match "ong_string" etc, no point in trying.
  5885. */
  5886. goto skip_matching;
  5887. }
  5888. goto try_to_match;
  5889. }
  5890. if (subtype == VSREPLACEALL) {
  5891. while (idx < loc) {
  5892. if (quotes && (unsigned char)*idx == CTLESC)
  5893. idx++;
  5894. idx++;
  5895. rmesc++;
  5896. }
  5897. } else {
  5898. idx = loc;
  5899. }
  5900. //bb_error_msg("repl:'%s'", repl);
  5901. for (loc = (char*)repl; *loc; loc++) {
  5902. char *restart_detect = stackblock();
  5903. if (quotes && *loc == '\\') {
  5904. STPUTC(CTLESC, expdest);
  5905. len++;
  5906. }
  5907. STPUTC(*loc, expdest);
  5908. if (stackblock() != restart_detect)
  5909. goto restart;
  5910. len++;
  5911. }
  5912. if (subtype == VSREPLACE) {
  5913. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  5914. while (*idx) {
  5915. char *restart_detect = stackblock();
  5916. STPUTC(*idx, expdest);
  5917. if (stackblock() != restart_detect)
  5918. goto restart;
  5919. len++;
  5920. idx++;
  5921. }
  5922. break;
  5923. }
  5924. }
  5925. /* We've put the replaced text into a buffer at workloc, now
  5926. * move it to the right place and adjust the stack.
  5927. */
  5928. STPUTC('\0', expdest);
  5929. startp = (char *)stackblock() + startloc;
  5930. memmove(startp, (char *)stackblock() + workloc, len + 1);
  5931. //bb_error_msg("startp:'%s'", startp);
  5932. amount = expdest - (startp + len);
  5933. STADJUST(-amount, expdest);
  5934. return startp;
  5935. }
  5936. #endif /* ENABLE_ASH_BASH_COMPAT */
  5937. subtype -= VSTRIMRIGHT;
  5938. #if DEBUG
  5939. if (subtype < 0 || subtype > 7)
  5940. abort();
  5941. #endif
  5942. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  5943. zero = subtype >> 1;
  5944. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5945. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5946. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5947. if (loc) {
  5948. if (zero) {
  5949. memmove(startp, loc, str - loc);
  5950. loc = startp + (str - loc) - 1;
  5951. }
  5952. *loc = '\0';
  5953. amount = loc - expdest;
  5954. STADJUST(amount, expdest);
  5955. }
  5956. return loc;
  5957. }
  5958. /*
  5959. * Add the value of a specialized variable to the stack string.
  5960. * name parameter (examples):
  5961. * ash -c 'echo $1' name:'1='
  5962. * ash -c 'echo $qwe' name:'qwe='
  5963. * ash -c 'echo $$' name:'$='
  5964. * ash -c 'echo ${$}' name:'$='
  5965. * ash -c 'echo ${$##q}' name:'$=q'
  5966. * ash -c 'echo ${#$}' name:'$='
  5967. * note: examples with bad shell syntax:
  5968. * ash -c 'echo ${#$1}' name:'$=1'
  5969. * ash -c 'echo ${#1#}' name:'1=#'
  5970. */
  5971. static NOINLINE ssize_t
  5972. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5973. {
  5974. const char *p;
  5975. int num;
  5976. int i;
  5977. ssize_t len = 0;
  5978. int sep;
  5979. int quoted = flags & EXP_QUOTED;
  5980. int subtype = varflags & VSTYPE;
  5981. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  5982. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  5983. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5984. sep = quoted ? ((flags & EXP_FULL) << CHAR_BIT) : 0;
  5985. switch (*name) {
  5986. case '$':
  5987. num = rootpid;
  5988. goto numvar;
  5989. case '?':
  5990. num = exitstatus;
  5991. goto numvar;
  5992. case '#':
  5993. num = shellparam.nparam;
  5994. goto numvar;
  5995. case '!':
  5996. num = backgndpid;
  5997. if (num == 0)
  5998. return -1;
  5999. numvar:
  6000. len = cvtnum(num);
  6001. goto check_1char_name;
  6002. case '-':
  6003. expdest = makestrspace(NOPTS, expdest);
  6004. for (i = NOPTS - 1; i >= 0; i--) {
  6005. if (optlist[i]) {
  6006. USTPUTC(optletters(i), expdest);
  6007. len++;
  6008. }
  6009. }
  6010. check_1char_name:
  6011. #if 0
  6012. /* handles cases similar to ${#$1} */
  6013. if (name[2] != '\0')
  6014. raise_error_syntax("bad substitution");
  6015. #endif
  6016. break;
  6017. case '@': {
  6018. char **ap;
  6019. char sepc;
  6020. if (quoted && (flags & EXP_FULL)) {
  6021. /* note: this is not meant as PEOF value */
  6022. sep = 1 << CHAR_BIT;
  6023. goto param;
  6024. }
  6025. /* fall through */
  6026. case '*':
  6027. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  6028. param:
  6029. ap = shellparam.p;
  6030. sepc = sep;
  6031. if (!ap)
  6032. return -1;
  6033. while ((p = *ap++) != NULL) {
  6034. len += strtodest(p, syntax, quotes);
  6035. if (*ap && sep) {
  6036. len++;
  6037. memtodest(&sepc, 1, syntax, quotes);
  6038. }
  6039. }
  6040. break;
  6041. } /* case '@' and '*' */
  6042. case '0':
  6043. case '1':
  6044. case '2':
  6045. case '3':
  6046. case '4':
  6047. case '5':
  6048. case '6':
  6049. case '7':
  6050. case '8':
  6051. case '9':
  6052. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6053. if (num < 0 || num > shellparam.nparam)
  6054. return -1;
  6055. p = num ? shellparam.p[num - 1] : arg0;
  6056. goto value;
  6057. default:
  6058. /* NB: name has form "VAR=..." */
  6059. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  6060. * which should be considered before we check variables. */
  6061. if (var_str_list) {
  6062. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  6063. p = NULL;
  6064. do {
  6065. char *str, *eq;
  6066. str = var_str_list->text;
  6067. eq = strchr(str, '=');
  6068. if (!eq) /* stop at first non-assignment */
  6069. break;
  6070. eq++;
  6071. if (name_len == (unsigned)(eq - str)
  6072. && strncmp(str, name, name_len) == 0
  6073. ) {
  6074. p = eq;
  6075. /* goto value; - WRONG! */
  6076. /* think "A=1 A=2 B=$A" */
  6077. }
  6078. var_str_list = var_str_list->next;
  6079. } while (var_str_list);
  6080. if (p)
  6081. goto value;
  6082. }
  6083. p = lookupvar(name);
  6084. value:
  6085. if (!p)
  6086. return -1;
  6087. len = strtodest(p, syntax, quotes);
  6088. #if ENABLE_UNICODE_SUPPORT
  6089. if (subtype == VSLENGTH && len > 0) {
  6090. reinit_unicode_for_ash();
  6091. if (unicode_status == UNICODE_ON) {
  6092. STADJUST(-len, expdest);
  6093. discard = 0;
  6094. len = unicode_strlen(p);
  6095. }
  6096. }
  6097. #endif
  6098. break;
  6099. }
  6100. if (discard)
  6101. STADJUST(-len, expdest);
  6102. return len;
  6103. }
  6104. /*
  6105. * Expand a variable, and return a pointer to the next character in the
  6106. * input string.
  6107. */
  6108. static char *
  6109. evalvar(char *p, int flags, struct strlist *var_str_list)
  6110. {
  6111. char varflags;
  6112. char subtype;
  6113. int quoted;
  6114. char easy;
  6115. char *var;
  6116. int patloc;
  6117. int startloc;
  6118. ssize_t varlen;
  6119. varflags = (unsigned char) *p++;
  6120. subtype = varflags & VSTYPE;
  6121. quoted = flags & EXP_QUOTED;
  6122. var = p;
  6123. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6124. startloc = expdest - (char *)stackblock();
  6125. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6126. again:
  6127. varlen = varvalue(var, varflags, flags, var_str_list);
  6128. if (varflags & VSNUL)
  6129. varlen--;
  6130. if (subtype == VSPLUS) {
  6131. varlen = -1 - varlen;
  6132. goto vsplus;
  6133. }
  6134. if (subtype == VSMINUS) {
  6135. vsplus:
  6136. if (varlen < 0) {
  6137. argstr(
  6138. p,
  6139. flags | EXP_TILDE | EXP_WORD,
  6140. var_str_list
  6141. );
  6142. goto end;
  6143. }
  6144. if (easy)
  6145. goto record;
  6146. goto end;
  6147. }
  6148. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6149. if (varlen < 0) {
  6150. if (subevalvar(p, var, /* strloc: */ 0,
  6151. subtype, startloc, varflags,
  6152. /* quotes: */ flags & ~QUOTES_ESC,
  6153. var_str_list)
  6154. ) {
  6155. varflags &= ~VSNUL;
  6156. /*
  6157. * Remove any recorded regions beyond
  6158. * start of variable
  6159. */
  6160. removerecordregions(startloc);
  6161. goto again;
  6162. }
  6163. goto end;
  6164. }
  6165. if (easy)
  6166. goto record;
  6167. goto end;
  6168. }
  6169. if (varlen < 0 && uflag)
  6170. varunset(p, var, 0, 0);
  6171. if (subtype == VSLENGTH) {
  6172. cvtnum(varlen > 0 ? varlen : 0);
  6173. goto record;
  6174. }
  6175. if (subtype == VSNORMAL) {
  6176. if (easy)
  6177. goto record;
  6178. goto end;
  6179. }
  6180. #if DEBUG
  6181. switch (subtype) {
  6182. case VSTRIMLEFT:
  6183. case VSTRIMLEFTMAX:
  6184. case VSTRIMRIGHT:
  6185. case VSTRIMRIGHTMAX:
  6186. #if ENABLE_ASH_BASH_COMPAT
  6187. case VSSUBSTR:
  6188. case VSREPLACE:
  6189. case VSREPLACEALL:
  6190. #endif
  6191. break;
  6192. default:
  6193. abort();
  6194. }
  6195. #endif
  6196. if (varlen >= 0) {
  6197. /*
  6198. * Terminate the string and start recording the pattern
  6199. * right after it
  6200. */
  6201. STPUTC('\0', expdest);
  6202. patloc = expdest - (char *)stackblock();
  6203. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6204. startloc, varflags, flags, var_str_list)) {
  6205. int amount = expdest - (
  6206. (char *)stackblock() + patloc - 1
  6207. );
  6208. STADJUST(-amount, expdest);
  6209. }
  6210. /* Remove any recorded regions beyond start of variable */
  6211. removerecordregions(startloc);
  6212. record:
  6213. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6214. }
  6215. end:
  6216. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6217. int nesting = 1;
  6218. for (;;) {
  6219. unsigned char c = *p++;
  6220. if (c == CTLESC)
  6221. p++;
  6222. else if (c == CTLBACKQ) {
  6223. if (varlen >= 0)
  6224. argbackq = argbackq->next;
  6225. } else if (c == CTLVAR) {
  6226. if ((*p++ & VSTYPE) != VSNORMAL)
  6227. nesting++;
  6228. } else if (c == CTLENDVAR) {
  6229. if (--nesting == 0)
  6230. break;
  6231. }
  6232. }
  6233. }
  6234. return p;
  6235. }
  6236. /*
  6237. * Break the argument string into pieces based upon IFS and add the
  6238. * strings to the argument list. The regions of the string to be
  6239. * searched for IFS characters have been stored by recordregion.
  6240. */
  6241. static void
  6242. ifsbreakup(char *string, struct arglist *arglist)
  6243. {
  6244. struct ifsregion *ifsp;
  6245. struct strlist *sp;
  6246. char *start;
  6247. char *p;
  6248. char *q;
  6249. const char *ifs, *realifs;
  6250. int ifsspc;
  6251. int nulonly;
  6252. start = string;
  6253. if (ifslastp != NULL) {
  6254. ifsspc = 0;
  6255. nulonly = 0;
  6256. realifs = ifsset() ? ifsval() : defifs;
  6257. ifsp = &ifsfirst;
  6258. do {
  6259. p = string + ifsp->begoff;
  6260. nulonly = ifsp->nulonly;
  6261. ifs = nulonly ? nullstr : realifs;
  6262. ifsspc = 0;
  6263. while (p < string + ifsp->endoff) {
  6264. q = p;
  6265. if ((unsigned char)*p == CTLESC)
  6266. p++;
  6267. if (!strchr(ifs, *p)) {
  6268. p++;
  6269. continue;
  6270. }
  6271. if (!nulonly)
  6272. ifsspc = (strchr(defifs, *p) != NULL);
  6273. /* Ignore IFS whitespace at start */
  6274. if (q == start && ifsspc) {
  6275. p++;
  6276. start = p;
  6277. continue;
  6278. }
  6279. *q = '\0';
  6280. sp = stzalloc(sizeof(*sp));
  6281. sp->text = start;
  6282. *arglist->lastp = sp;
  6283. arglist->lastp = &sp->next;
  6284. p++;
  6285. if (!nulonly) {
  6286. for (;;) {
  6287. if (p >= string + ifsp->endoff) {
  6288. break;
  6289. }
  6290. q = p;
  6291. if ((unsigned char)*p == CTLESC)
  6292. p++;
  6293. if (strchr(ifs, *p) == NULL) {
  6294. p = q;
  6295. break;
  6296. }
  6297. if (strchr(defifs, *p) == NULL) {
  6298. if (ifsspc) {
  6299. p++;
  6300. ifsspc = 0;
  6301. } else {
  6302. p = q;
  6303. break;
  6304. }
  6305. } else
  6306. p++;
  6307. }
  6308. }
  6309. start = p;
  6310. } /* while */
  6311. ifsp = ifsp->next;
  6312. } while (ifsp != NULL);
  6313. if (nulonly)
  6314. goto add;
  6315. }
  6316. if (!*start)
  6317. return;
  6318. add:
  6319. sp = stzalloc(sizeof(*sp));
  6320. sp->text = start;
  6321. *arglist->lastp = sp;
  6322. arglist->lastp = &sp->next;
  6323. }
  6324. static void
  6325. ifsfree(void)
  6326. {
  6327. struct ifsregion *p;
  6328. INT_OFF;
  6329. p = ifsfirst.next;
  6330. do {
  6331. struct ifsregion *ifsp;
  6332. ifsp = p->next;
  6333. free(p);
  6334. p = ifsp;
  6335. } while (p);
  6336. ifslastp = NULL;
  6337. ifsfirst.next = NULL;
  6338. INT_ON;
  6339. }
  6340. /*
  6341. * Add a file name to the list.
  6342. */
  6343. static void
  6344. addfname(const char *name)
  6345. {
  6346. struct strlist *sp;
  6347. sp = stzalloc(sizeof(*sp));
  6348. sp->text = ststrdup(name);
  6349. *exparg.lastp = sp;
  6350. exparg.lastp = &sp->next;
  6351. }
  6352. /*
  6353. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6354. */
  6355. static void
  6356. expmeta(char *expdir, char *enddir, char *name)
  6357. {
  6358. char *p;
  6359. const char *cp;
  6360. char *start;
  6361. char *endname;
  6362. int metaflag;
  6363. struct stat statb;
  6364. DIR *dirp;
  6365. struct dirent *dp;
  6366. int atend;
  6367. int matchdot;
  6368. int esc;
  6369. metaflag = 0;
  6370. start = name;
  6371. for (p = name; esc = 0, *p; p += esc + 1) {
  6372. if (*p == '*' || *p == '?')
  6373. metaflag = 1;
  6374. else if (*p == '[') {
  6375. char *q = p + 1;
  6376. if (*q == '!')
  6377. q++;
  6378. for (;;) {
  6379. if (*q == '\\')
  6380. q++;
  6381. if (*q == '/' || *q == '\0')
  6382. break;
  6383. if (*++q == ']') {
  6384. metaflag = 1;
  6385. break;
  6386. }
  6387. }
  6388. } else {
  6389. if (*p == '\\')
  6390. esc++;
  6391. if (p[esc] == '/') {
  6392. if (metaflag)
  6393. break;
  6394. start = p + esc + 1;
  6395. }
  6396. }
  6397. }
  6398. if (metaflag == 0) { /* we've reached the end of the file name */
  6399. if (enddir != expdir)
  6400. metaflag++;
  6401. p = name;
  6402. do {
  6403. if (*p == '\\')
  6404. p++;
  6405. *enddir++ = *p;
  6406. } while (*p++);
  6407. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6408. addfname(expdir);
  6409. return;
  6410. }
  6411. endname = p;
  6412. if (name < start) {
  6413. p = name;
  6414. do {
  6415. if (*p == '\\')
  6416. p++;
  6417. *enddir++ = *p++;
  6418. } while (p < start);
  6419. }
  6420. if (enddir == expdir) {
  6421. cp = ".";
  6422. } else if (enddir == expdir + 1 && *expdir == '/') {
  6423. cp = "/";
  6424. } else {
  6425. cp = expdir;
  6426. enddir[-1] = '\0';
  6427. }
  6428. dirp = opendir(cp);
  6429. if (dirp == NULL)
  6430. return;
  6431. if (enddir != expdir)
  6432. enddir[-1] = '/';
  6433. if (*endname == 0) {
  6434. atend = 1;
  6435. } else {
  6436. atend = 0;
  6437. *endname = '\0';
  6438. endname += esc + 1;
  6439. }
  6440. matchdot = 0;
  6441. p = start;
  6442. if (*p == '\\')
  6443. p++;
  6444. if (*p == '.')
  6445. matchdot++;
  6446. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6447. if (dp->d_name[0] == '.' && !matchdot)
  6448. continue;
  6449. if (pmatch(start, dp->d_name)) {
  6450. if (atend) {
  6451. strcpy(enddir, dp->d_name);
  6452. addfname(expdir);
  6453. } else {
  6454. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6455. continue;
  6456. p[-1] = '/';
  6457. expmeta(expdir, p, endname);
  6458. }
  6459. }
  6460. }
  6461. closedir(dirp);
  6462. if (!atend)
  6463. endname[-esc - 1] = esc ? '\\' : '/';
  6464. }
  6465. static struct strlist *
  6466. msort(struct strlist *list, int len)
  6467. {
  6468. struct strlist *p, *q = NULL;
  6469. struct strlist **lpp;
  6470. int half;
  6471. int n;
  6472. if (len <= 1)
  6473. return list;
  6474. half = len >> 1;
  6475. p = list;
  6476. for (n = half; --n >= 0;) {
  6477. q = p;
  6478. p = p->next;
  6479. }
  6480. q->next = NULL; /* terminate first half of list */
  6481. q = msort(list, half); /* sort first half of list */
  6482. p = msort(p, len - half); /* sort second half */
  6483. lpp = &list;
  6484. for (;;) {
  6485. #if ENABLE_LOCALE_SUPPORT
  6486. if (strcoll(p->text, q->text) < 0)
  6487. #else
  6488. if (strcmp(p->text, q->text) < 0)
  6489. #endif
  6490. {
  6491. *lpp = p;
  6492. lpp = &p->next;
  6493. p = *lpp;
  6494. if (p == NULL) {
  6495. *lpp = q;
  6496. break;
  6497. }
  6498. } else {
  6499. *lpp = q;
  6500. lpp = &q->next;
  6501. q = *lpp;
  6502. if (q == NULL) {
  6503. *lpp = p;
  6504. break;
  6505. }
  6506. }
  6507. }
  6508. return list;
  6509. }
  6510. /*
  6511. * Sort the results of file name expansion. It calculates the number of
  6512. * strings to sort and then calls msort (short for merge sort) to do the
  6513. * work.
  6514. */
  6515. static struct strlist *
  6516. expsort(struct strlist *str)
  6517. {
  6518. int len;
  6519. struct strlist *sp;
  6520. len = 0;
  6521. for (sp = str; sp; sp = sp->next)
  6522. len++;
  6523. return msort(str, len);
  6524. }
  6525. static void
  6526. expandmeta(struct strlist *str /*, int flag*/)
  6527. {
  6528. static const char metachars[] ALIGN1 = {
  6529. '*', '?', '[', 0
  6530. };
  6531. /* TODO - EXP_REDIR */
  6532. while (str) {
  6533. char *expdir;
  6534. struct strlist **savelastp;
  6535. struct strlist *sp;
  6536. char *p;
  6537. if (fflag)
  6538. goto nometa;
  6539. if (!strpbrk(str->text, metachars))
  6540. goto nometa;
  6541. savelastp = exparg.lastp;
  6542. INT_OFF;
  6543. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6544. {
  6545. int i = strlen(str->text);
  6546. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6547. }
  6548. expmeta(expdir, expdir, p);
  6549. free(expdir);
  6550. if (p != str->text)
  6551. free(p);
  6552. INT_ON;
  6553. if (exparg.lastp == savelastp) {
  6554. /*
  6555. * no matches
  6556. */
  6557. nometa:
  6558. *exparg.lastp = str;
  6559. rmescapes(str->text, 0);
  6560. exparg.lastp = &str->next;
  6561. } else {
  6562. *exparg.lastp = NULL;
  6563. *savelastp = sp = expsort(*savelastp);
  6564. while (sp->next != NULL)
  6565. sp = sp->next;
  6566. exparg.lastp = &sp->next;
  6567. }
  6568. str = str->next;
  6569. }
  6570. }
  6571. /*
  6572. * Perform variable substitution and command substitution on an argument,
  6573. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6574. * perform splitting and file name expansion. When arglist is NULL, perform
  6575. * here document expansion.
  6576. */
  6577. static void
  6578. expandarg(union node *arg, struct arglist *arglist, int flag)
  6579. {
  6580. struct strlist *sp;
  6581. char *p;
  6582. argbackq = arg->narg.backquote;
  6583. STARTSTACKSTR(expdest);
  6584. ifsfirst.next = NULL;
  6585. ifslastp = NULL;
  6586. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  6587. argstr(arg->narg.text, flag,
  6588. /* var_str_list: */ arglist ? arglist->list : NULL);
  6589. p = _STPUTC('\0', expdest);
  6590. expdest = p - 1;
  6591. if (arglist == NULL) {
  6592. return; /* here document expanded */
  6593. }
  6594. p = grabstackstr(p);
  6595. TRACE(("expandarg: p:'%s'\n", p));
  6596. exparg.lastp = &exparg.list;
  6597. /*
  6598. * TODO - EXP_REDIR
  6599. */
  6600. if (flag & EXP_FULL) {
  6601. ifsbreakup(p, &exparg);
  6602. *exparg.lastp = NULL;
  6603. exparg.lastp = &exparg.list;
  6604. expandmeta(exparg.list /*, flag*/);
  6605. } else {
  6606. if (flag & EXP_REDIR) { /*XXX - for now, just remove escapes */
  6607. rmescapes(p, 0);
  6608. TRACE(("expandarg: rmescapes:'%s'\n", p));
  6609. }
  6610. sp = stzalloc(sizeof(*sp));
  6611. sp->text = p;
  6612. *exparg.lastp = sp;
  6613. exparg.lastp = &sp->next;
  6614. }
  6615. if (ifsfirst.next)
  6616. ifsfree();
  6617. *exparg.lastp = NULL;
  6618. if (exparg.list) {
  6619. *arglist->lastp = exparg.list;
  6620. arglist->lastp = exparg.lastp;
  6621. }
  6622. }
  6623. /*
  6624. * Expand shell variables and backquotes inside a here document.
  6625. */
  6626. static void
  6627. expandhere(union node *arg, int fd)
  6628. {
  6629. herefd = fd;
  6630. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  6631. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6632. }
  6633. /*
  6634. * Returns true if the pattern matches the string.
  6635. */
  6636. static int
  6637. patmatch(char *pattern, const char *string)
  6638. {
  6639. return pmatch(preglob(pattern, 0), string);
  6640. }
  6641. /*
  6642. * See if a pattern matches in a case statement.
  6643. */
  6644. static int
  6645. casematch(union node *pattern, char *val)
  6646. {
  6647. struct stackmark smark;
  6648. int result;
  6649. setstackmark(&smark);
  6650. argbackq = pattern->narg.backquote;
  6651. STARTSTACKSTR(expdest);
  6652. ifslastp = NULL;
  6653. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6654. /* var_str_list: */ NULL);
  6655. STACKSTRNUL(expdest);
  6656. result = patmatch(stackblock(), val);
  6657. popstackmark(&smark);
  6658. return result;
  6659. }
  6660. /* ============ find_command */
  6661. struct builtincmd {
  6662. const char *name;
  6663. int (*builtin)(int, char **) FAST_FUNC;
  6664. /* unsigned flags; */
  6665. };
  6666. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6667. /* "regular" builtins always take precedence over commands,
  6668. * regardless of PATH=....%builtin... position */
  6669. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6670. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6671. struct cmdentry {
  6672. smallint cmdtype; /* CMDxxx */
  6673. union param {
  6674. int index;
  6675. /* index >= 0 for commands without path (slashes) */
  6676. /* (TODO: what exactly does the value mean? PATH position?) */
  6677. /* index == -1 for commands with slashes */
  6678. /* index == (-2 - applet_no) for NOFORK applets */
  6679. const struct builtincmd *cmd;
  6680. struct funcnode *func;
  6681. } u;
  6682. };
  6683. /* values of cmdtype */
  6684. #define CMDUNKNOWN -1 /* no entry in table for command */
  6685. #define CMDNORMAL 0 /* command is an executable program */
  6686. #define CMDFUNCTION 1 /* command is a shell function */
  6687. #define CMDBUILTIN 2 /* command is a shell builtin */
  6688. /* action to find_command() */
  6689. #define DO_ERR 0x01 /* prints errors */
  6690. #define DO_ABS 0x02 /* checks absolute paths */
  6691. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6692. #define DO_ALTPATH 0x08 /* using alternate path */
  6693. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6694. static void find_command(char *, struct cmdentry *, int, const char *);
  6695. /* ============ Hashing commands */
  6696. /*
  6697. * When commands are first encountered, they are entered in a hash table.
  6698. * This ensures that a full path search will not have to be done for them
  6699. * on each invocation.
  6700. *
  6701. * We should investigate converting to a linear search, even though that
  6702. * would make the command name "hash" a misnomer.
  6703. */
  6704. struct tblentry {
  6705. struct tblentry *next; /* next entry in hash chain */
  6706. union param param; /* definition of builtin function */
  6707. smallint cmdtype; /* CMDxxx */
  6708. char rehash; /* if set, cd done since entry created */
  6709. char cmdname[1]; /* name of command */
  6710. };
  6711. static struct tblentry **cmdtable;
  6712. #define INIT_G_cmdtable() do { \
  6713. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6714. } while (0)
  6715. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6716. static void
  6717. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6718. {
  6719. #if ENABLE_FEATURE_SH_STANDALONE
  6720. if (applet_no >= 0) {
  6721. if (APPLET_IS_NOEXEC(applet_no)) {
  6722. clearenv();
  6723. while (*envp)
  6724. putenv(*envp++);
  6725. run_applet_no_and_exit(applet_no, argv);
  6726. }
  6727. /* re-exec ourselves with the new arguments */
  6728. execve(bb_busybox_exec_path, argv, envp);
  6729. /* If they called chroot or otherwise made the binary no longer
  6730. * executable, fall through */
  6731. }
  6732. #endif
  6733. repeat:
  6734. #ifdef SYSV
  6735. do {
  6736. execve(cmd, argv, envp);
  6737. } while (errno == EINTR);
  6738. #else
  6739. execve(cmd, argv, envp);
  6740. #endif
  6741. if (cmd == (char*) bb_busybox_exec_path) {
  6742. /* We already visited ENOEXEC branch below, don't do it again */
  6743. //TODO: try execve(initial_argv0_of_shell, argv, envp) before giving up?
  6744. free(argv);
  6745. return;
  6746. }
  6747. if (errno == ENOEXEC) {
  6748. /* Run "cmd" as a shell script:
  6749. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  6750. * "If the execve() function fails with ENOEXEC, the shell
  6751. * shall execute a command equivalent to having a shell invoked
  6752. * with the command name as its first operand,
  6753. * with any remaining arguments passed to the new shell"
  6754. *
  6755. * That is, do not use $SHELL, user's shell, or /bin/sh;
  6756. * just call ourselves.
  6757. *
  6758. * Note that bash reads ~80 chars of the file, and if it sees
  6759. * a zero byte before it sees newline, it doesn't try to
  6760. * interpret it, but fails with "cannot execute binary file"
  6761. * message and exit code 126. For one, this prevents attempts
  6762. * to interpret foreign ELF binaries as shell scripts.
  6763. */
  6764. char **ap;
  6765. char **new;
  6766. for (ap = argv; *ap; ap++)
  6767. continue;
  6768. new = ckmalloc((ap - argv + 2) * sizeof(new[0]));
  6769. new[0] = (char*) "ash";
  6770. new[1] = cmd;
  6771. ap = new + 2;
  6772. while ((*ap++ = *++argv) != NULL)
  6773. continue;
  6774. cmd = (char*) bb_busybox_exec_path;
  6775. argv = new;
  6776. goto repeat;
  6777. }
  6778. }
  6779. /*
  6780. * Exec a program. Never returns. If you change this routine, you may
  6781. * have to change the find_command routine as well.
  6782. */
  6783. static void shellexec(char **, const char *, int) NORETURN;
  6784. static void
  6785. shellexec(char **argv, const char *path, int idx)
  6786. {
  6787. char *cmdname;
  6788. int e;
  6789. char **envp;
  6790. int exerrno;
  6791. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  6792. clearredir(/*drop:*/ 1);
  6793. envp = listvars(VEXPORT, VUNSET, /*end:*/ NULL);
  6794. if (strchr(argv[0], '/') != NULL
  6795. #if ENABLE_FEATURE_SH_STANDALONE
  6796. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6797. #endif
  6798. ) {
  6799. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6800. if (applet_no >= 0) {
  6801. /* We tried execing ourself, but it didn't work.
  6802. * Maybe /proc/self/exe doesn't exist?
  6803. * Try $PATH search.
  6804. */
  6805. goto try_PATH;
  6806. }
  6807. e = errno;
  6808. } else {
  6809. try_PATH:
  6810. e = ENOENT;
  6811. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6812. if (--idx < 0 && pathopt == NULL) {
  6813. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6814. if (errno != ENOENT && errno != ENOTDIR)
  6815. e = errno;
  6816. }
  6817. stunalloc(cmdname);
  6818. }
  6819. }
  6820. /* Map to POSIX errors */
  6821. switch (e) {
  6822. case EACCES:
  6823. exerrno = 126;
  6824. break;
  6825. case ENOENT:
  6826. exerrno = 127;
  6827. break;
  6828. default:
  6829. exerrno = 2;
  6830. break;
  6831. }
  6832. exitstatus = exerrno;
  6833. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6834. argv[0], e, suppress_int));
  6835. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6836. /* NOTREACHED */
  6837. }
  6838. static void
  6839. printentry(struct tblentry *cmdp)
  6840. {
  6841. int idx;
  6842. const char *path;
  6843. char *name;
  6844. idx = cmdp->param.index;
  6845. path = pathval();
  6846. do {
  6847. name = path_advance(&path, cmdp->cmdname);
  6848. stunalloc(name);
  6849. } while (--idx >= 0);
  6850. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6851. }
  6852. /*
  6853. * Clear out command entries. The argument specifies the first entry in
  6854. * PATH which has changed.
  6855. */
  6856. static void
  6857. clearcmdentry(int firstchange)
  6858. {
  6859. struct tblentry **tblp;
  6860. struct tblentry **pp;
  6861. struct tblentry *cmdp;
  6862. INT_OFF;
  6863. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6864. pp = tblp;
  6865. while ((cmdp = *pp) != NULL) {
  6866. if ((cmdp->cmdtype == CMDNORMAL &&
  6867. cmdp->param.index >= firstchange)
  6868. || (cmdp->cmdtype == CMDBUILTIN &&
  6869. builtinloc >= firstchange)
  6870. ) {
  6871. *pp = cmdp->next;
  6872. free(cmdp);
  6873. } else {
  6874. pp = &cmdp->next;
  6875. }
  6876. }
  6877. }
  6878. INT_ON;
  6879. }
  6880. /*
  6881. * Locate a command in the command hash table. If "add" is nonzero,
  6882. * add the command to the table if it is not already present. The
  6883. * variable "lastcmdentry" is set to point to the address of the link
  6884. * pointing to the entry, so that delete_cmd_entry can delete the
  6885. * entry.
  6886. *
  6887. * Interrupts must be off if called with add != 0.
  6888. */
  6889. static struct tblentry **lastcmdentry;
  6890. static struct tblentry *
  6891. cmdlookup(const char *name, int add)
  6892. {
  6893. unsigned int hashval;
  6894. const char *p;
  6895. struct tblentry *cmdp;
  6896. struct tblentry **pp;
  6897. p = name;
  6898. hashval = (unsigned char)*p << 4;
  6899. while (*p)
  6900. hashval += (unsigned char)*p++;
  6901. hashval &= 0x7FFF;
  6902. pp = &cmdtable[hashval % CMDTABLESIZE];
  6903. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6904. if (strcmp(cmdp->cmdname, name) == 0)
  6905. break;
  6906. pp = &cmdp->next;
  6907. }
  6908. if (add && cmdp == NULL) {
  6909. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6910. + strlen(name)
  6911. /* + 1 - already done because
  6912. * tblentry::cmdname is char[1] */);
  6913. /*cmdp->next = NULL; - ckzalloc did it */
  6914. cmdp->cmdtype = CMDUNKNOWN;
  6915. strcpy(cmdp->cmdname, name);
  6916. }
  6917. lastcmdentry = pp;
  6918. return cmdp;
  6919. }
  6920. /*
  6921. * Delete the command entry returned on the last lookup.
  6922. */
  6923. static void
  6924. delete_cmd_entry(void)
  6925. {
  6926. struct tblentry *cmdp;
  6927. INT_OFF;
  6928. cmdp = *lastcmdentry;
  6929. *lastcmdentry = cmdp->next;
  6930. if (cmdp->cmdtype == CMDFUNCTION)
  6931. freefunc(cmdp->param.func);
  6932. free(cmdp);
  6933. INT_ON;
  6934. }
  6935. /*
  6936. * Add a new command entry, replacing any existing command entry for
  6937. * the same name - except special builtins.
  6938. */
  6939. static void
  6940. addcmdentry(char *name, struct cmdentry *entry)
  6941. {
  6942. struct tblentry *cmdp;
  6943. cmdp = cmdlookup(name, 1);
  6944. if (cmdp->cmdtype == CMDFUNCTION) {
  6945. freefunc(cmdp->param.func);
  6946. }
  6947. cmdp->cmdtype = entry->cmdtype;
  6948. cmdp->param = entry->u;
  6949. cmdp->rehash = 0;
  6950. }
  6951. static int FAST_FUNC
  6952. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6953. {
  6954. struct tblentry **pp;
  6955. struct tblentry *cmdp;
  6956. int c;
  6957. struct cmdentry entry;
  6958. char *name;
  6959. if (nextopt("r") != '\0') {
  6960. clearcmdentry(0);
  6961. return 0;
  6962. }
  6963. if (*argptr == NULL) {
  6964. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6965. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6966. if (cmdp->cmdtype == CMDNORMAL)
  6967. printentry(cmdp);
  6968. }
  6969. }
  6970. return 0;
  6971. }
  6972. c = 0;
  6973. while ((name = *argptr) != NULL) {
  6974. cmdp = cmdlookup(name, 0);
  6975. if (cmdp != NULL
  6976. && (cmdp->cmdtype == CMDNORMAL
  6977. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6978. ) {
  6979. delete_cmd_entry();
  6980. }
  6981. find_command(name, &entry, DO_ERR, pathval());
  6982. if (entry.cmdtype == CMDUNKNOWN)
  6983. c = 1;
  6984. argptr++;
  6985. }
  6986. return c;
  6987. }
  6988. /*
  6989. * Called when a cd is done. Marks all commands so the next time they
  6990. * are executed they will be rehashed.
  6991. */
  6992. static void
  6993. hashcd(void)
  6994. {
  6995. struct tblentry **pp;
  6996. struct tblentry *cmdp;
  6997. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6998. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6999. if (cmdp->cmdtype == CMDNORMAL
  7000. || (cmdp->cmdtype == CMDBUILTIN
  7001. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7002. && builtinloc > 0)
  7003. ) {
  7004. cmdp->rehash = 1;
  7005. }
  7006. }
  7007. }
  7008. }
  7009. /*
  7010. * Fix command hash table when PATH changed.
  7011. * Called before PATH is changed. The argument is the new value of PATH;
  7012. * pathval() still returns the old value at this point.
  7013. * Called with interrupts off.
  7014. */
  7015. static void FAST_FUNC
  7016. changepath(const char *new)
  7017. {
  7018. const char *old;
  7019. int firstchange;
  7020. int idx;
  7021. int idx_bltin;
  7022. old = pathval();
  7023. firstchange = 9999; /* assume no change */
  7024. idx = 0;
  7025. idx_bltin = -1;
  7026. for (;;) {
  7027. if (*old != *new) {
  7028. firstchange = idx;
  7029. if ((*old == '\0' && *new == ':')
  7030. || (*old == ':' && *new == '\0')
  7031. ) {
  7032. firstchange++;
  7033. }
  7034. old = new; /* ignore subsequent differences */
  7035. }
  7036. if (*new == '\0')
  7037. break;
  7038. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7039. idx_bltin = idx;
  7040. if (*new == ':')
  7041. idx++;
  7042. new++;
  7043. old++;
  7044. }
  7045. if (builtinloc < 0 && idx_bltin >= 0)
  7046. builtinloc = idx_bltin; /* zap builtins */
  7047. if (builtinloc >= 0 && idx_bltin < 0)
  7048. firstchange = 0;
  7049. clearcmdentry(firstchange);
  7050. builtinloc = idx_bltin;
  7051. }
  7052. #define TEOF 0
  7053. #define TNL 1
  7054. #define TREDIR 2
  7055. #define TWORD 3
  7056. #define TSEMI 4
  7057. #define TBACKGND 5
  7058. #define TAND 6
  7059. #define TOR 7
  7060. #define TPIPE 8
  7061. #define TLP 9
  7062. #define TRP 10
  7063. #define TENDCASE 11
  7064. #define TENDBQUOTE 12
  7065. #define TNOT 13
  7066. #define TCASE 14
  7067. #define TDO 15
  7068. #define TDONE 16
  7069. #define TELIF 17
  7070. #define TELSE 18
  7071. #define TESAC 19
  7072. #define TFI 20
  7073. #define TFOR 21
  7074. #define TIF 22
  7075. #define TIN 23
  7076. #define TTHEN 24
  7077. #define TUNTIL 25
  7078. #define TWHILE 26
  7079. #define TBEGIN 27
  7080. #define TEND 28
  7081. typedef smallint token_id_t;
  7082. /* first char is indicating which tokens mark the end of a list */
  7083. static const char *const tokname_array[] = {
  7084. "\1end of file",
  7085. "\0newline",
  7086. "\0redirection",
  7087. "\0word",
  7088. "\0;",
  7089. "\0&",
  7090. "\0&&",
  7091. "\0||",
  7092. "\0|",
  7093. "\0(",
  7094. "\1)",
  7095. "\1;;",
  7096. "\1`",
  7097. #define KWDOFFSET 13
  7098. /* the following are keywords */
  7099. "\0!",
  7100. "\0case",
  7101. "\1do",
  7102. "\1done",
  7103. "\1elif",
  7104. "\1else",
  7105. "\1esac",
  7106. "\1fi",
  7107. "\0for",
  7108. "\0if",
  7109. "\0in",
  7110. "\1then",
  7111. "\0until",
  7112. "\0while",
  7113. "\0{",
  7114. "\1}",
  7115. };
  7116. /* Wrapper around strcmp for qsort/bsearch/... */
  7117. static int
  7118. pstrcmp(const void *a, const void *b)
  7119. {
  7120. return strcmp((char*) a, (*(char**) b) + 1);
  7121. }
  7122. static const char *const *
  7123. findkwd(const char *s)
  7124. {
  7125. return bsearch(s, tokname_array + KWDOFFSET,
  7126. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7127. sizeof(tokname_array[0]), pstrcmp);
  7128. }
  7129. /*
  7130. * Locate and print what a word is...
  7131. */
  7132. static int
  7133. describe_command(char *command, int describe_command_verbose)
  7134. {
  7135. struct cmdentry entry;
  7136. struct tblentry *cmdp;
  7137. #if ENABLE_ASH_ALIAS
  7138. const struct alias *ap;
  7139. #endif
  7140. const char *path = pathval();
  7141. if (describe_command_verbose) {
  7142. out1str(command);
  7143. }
  7144. /* First look at the keywords */
  7145. if (findkwd(command)) {
  7146. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7147. goto out;
  7148. }
  7149. #if ENABLE_ASH_ALIAS
  7150. /* Then look at the aliases */
  7151. ap = lookupalias(command, 0);
  7152. if (ap != NULL) {
  7153. if (!describe_command_verbose) {
  7154. out1str("alias ");
  7155. printalias(ap);
  7156. return 0;
  7157. }
  7158. out1fmt(" is an alias for %s", ap->val);
  7159. goto out;
  7160. }
  7161. #endif
  7162. /* Then check if it is a tracked alias */
  7163. cmdp = cmdlookup(command, 0);
  7164. if (cmdp != NULL) {
  7165. entry.cmdtype = cmdp->cmdtype;
  7166. entry.u = cmdp->param;
  7167. } else {
  7168. /* Finally use brute force */
  7169. find_command(command, &entry, DO_ABS, path);
  7170. }
  7171. switch (entry.cmdtype) {
  7172. case CMDNORMAL: {
  7173. int j = entry.u.index;
  7174. char *p;
  7175. if (j < 0) {
  7176. p = command;
  7177. } else {
  7178. do {
  7179. p = path_advance(&path, command);
  7180. stunalloc(p);
  7181. } while (--j >= 0);
  7182. }
  7183. if (describe_command_verbose) {
  7184. out1fmt(" is%s %s",
  7185. (cmdp ? " a tracked alias for" : nullstr), p
  7186. );
  7187. } else {
  7188. out1str(p);
  7189. }
  7190. break;
  7191. }
  7192. case CMDFUNCTION:
  7193. if (describe_command_verbose) {
  7194. out1str(" is a shell function");
  7195. } else {
  7196. out1str(command);
  7197. }
  7198. break;
  7199. case CMDBUILTIN:
  7200. if (describe_command_verbose) {
  7201. out1fmt(" is a %sshell builtin",
  7202. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7203. "special " : nullstr
  7204. );
  7205. } else {
  7206. out1str(command);
  7207. }
  7208. break;
  7209. default:
  7210. if (describe_command_verbose) {
  7211. out1str(": not found\n");
  7212. }
  7213. return 127;
  7214. }
  7215. out:
  7216. out1str("\n");
  7217. return 0;
  7218. }
  7219. static int FAST_FUNC
  7220. typecmd(int argc UNUSED_PARAM, char **argv)
  7221. {
  7222. int i = 1;
  7223. int err = 0;
  7224. int verbose = 1;
  7225. /* type -p ... ? (we don't bother checking for 'p') */
  7226. if (argv[1] && argv[1][0] == '-') {
  7227. i++;
  7228. verbose = 0;
  7229. }
  7230. while (argv[i]) {
  7231. err |= describe_command(argv[i++], verbose);
  7232. }
  7233. return err;
  7234. }
  7235. #if ENABLE_ASH_CMDCMD
  7236. static int FAST_FUNC
  7237. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7238. {
  7239. int c;
  7240. enum {
  7241. VERIFY_BRIEF = 1,
  7242. VERIFY_VERBOSE = 2,
  7243. } verify = 0;
  7244. while ((c = nextopt("pvV")) != '\0')
  7245. if (c == 'V')
  7246. verify |= VERIFY_VERBOSE;
  7247. else if (c == 'v')
  7248. verify |= VERIFY_BRIEF;
  7249. #if DEBUG
  7250. else if (c != 'p')
  7251. abort();
  7252. #endif
  7253. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7254. if (verify && (*argptr != NULL)) {
  7255. return describe_command(*argptr, verify - VERIFY_BRIEF);
  7256. }
  7257. return 0;
  7258. }
  7259. #endif
  7260. /* ============ eval.c */
  7261. static int funcblocksize; /* size of structures in function */
  7262. static int funcstringsize; /* size of strings in node */
  7263. static void *funcblock; /* block to allocate function from */
  7264. static char *funcstring; /* block to allocate strings from */
  7265. /* flags in argument to evaltree */
  7266. #define EV_EXIT 01 /* exit after evaluating tree */
  7267. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7268. #define EV_BACKCMD 04 /* command executing within back quotes */
  7269. static const uint8_t nodesize[N_NUMBER] = {
  7270. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7271. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7272. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7273. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7274. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7275. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7276. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7277. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7278. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7279. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7280. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7281. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7282. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7283. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7284. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7285. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7286. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7287. #if ENABLE_ASH_BASH_COMPAT
  7288. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7289. #endif
  7290. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7291. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7292. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7293. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7294. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7295. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7296. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7297. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7298. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7299. };
  7300. static void calcsize(union node *n);
  7301. static void
  7302. sizenodelist(struct nodelist *lp)
  7303. {
  7304. while (lp) {
  7305. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7306. calcsize(lp->n);
  7307. lp = lp->next;
  7308. }
  7309. }
  7310. static void
  7311. calcsize(union node *n)
  7312. {
  7313. if (n == NULL)
  7314. return;
  7315. funcblocksize += nodesize[n->type];
  7316. switch (n->type) {
  7317. case NCMD:
  7318. calcsize(n->ncmd.redirect);
  7319. calcsize(n->ncmd.args);
  7320. calcsize(n->ncmd.assign);
  7321. break;
  7322. case NPIPE:
  7323. sizenodelist(n->npipe.cmdlist);
  7324. break;
  7325. case NREDIR:
  7326. case NBACKGND:
  7327. case NSUBSHELL:
  7328. calcsize(n->nredir.redirect);
  7329. calcsize(n->nredir.n);
  7330. break;
  7331. case NAND:
  7332. case NOR:
  7333. case NSEMI:
  7334. case NWHILE:
  7335. case NUNTIL:
  7336. calcsize(n->nbinary.ch2);
  7337. calcsize(n->nbinary.ch1);
  7338. break;
  7339. case NIF:
  7340. calcsize(n->nif.elsepart);
  7341. calcsize(n->nif.ifpart);
  7342. calcsize(n->nif.test);
  7343. break;
  7344. case NFOR:
  7345. funcstringsize += strlen(n->nfor.var) + 1;
  7346. calcsize(n->nfor.body);
  7347. calcsize(n->nfor.args);
  7348. break;
  7349. case NCASE:
  7350. calcsize(n->ncase.cases);
  7351. calcsize(n->ncase.expr);
  7352. break;
  7353. case NCLIST:
  7354. calcsize(n->nclist.body);
  7355. calcsize(n->nclist.pattern);
  7356. calcsize(n->nclist.next);
  7357. break;
  7358. case NDEFUN:
  7359. case NARG:
  7360. sizenodelist(n->narg.backquote);
  7361. funcstringsize += strlen(n->narg.text) + 1;
  7362. calcsize(n->narg.next);
  7363. break;
  7364. case NTO:
  7365. #if ENABLE_ASH_BASH_COMPAT
  7366. case NTO2:
  7367. #endif
  7368. case NCLOBBER:
  7369. case NFROM:
  7370. case NFROMTO:
  7371. case NAPPEND:
  7372. calcsize(n->nfile.fname);
  7373. calcsize(n->nfile.next);
  7374. break;
  7375. case NTOFD:
  7376. case NFROMFD:
  7377. calcsize(n->ndup.vname);
  7378. calcsize(n->ndup.next);
  7379. break;
  7380. case NHERE:
  7381. case NXHERE:
  7382. calcsize(n->nhere.doc);
  7383. calcsize(n->nhere.next);
  7384. break;
  7385. case NNOT:
  7386. calcsize(n->nnot.com);
  7387. break;
  7388. };
  7389. }
  7390. static char *
  7391. nodeckstrdup(char *s)
  7392. {
  7393. char *rtn = funcstring;
  7394. strcpy(funcstring, s);
  7395. funcstring += strlen(s) + 1;
  7396. return rtn;
  7397. }
  7398. static union node *copynode(union node *);
  7399. static struct nodelist *
  7400. copynodelist(struct nodelist *lp)
  7401. {
  7402. struct nodelist *start;
  7403. struct nodelist **lpp;
  7404. lpp = &start;
  7405. while (lp) {
  7406. *lpp = funcblock;
  7407. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7408. (*lpp)->n = copynode(lp->n);
  7409. lp = lp->next;
  7410. lpp = &(*lpp)->next;
  7411. }
  7412. *lpp = NULL;
  7413. return start;
  7414. }
  7415. static union node *
  7416. copynode(union node *n)
  7417. {
  7418. union node *new;
  7419. if (n == NULL)
  7420. return NULL;
  7421. new = funcblock;
  7422. funcblock = (char *) funcblock + nodesize[n->type];
  7423. switch (n->type) {
  7424. case NCMD:
  7425. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7426. new->ncmd.args = copynode(n->ncmd.args);
  7427. new->ncmd.assign = copynode(n->ncmd.assign);
  7428. break;
  7429. case NPIPE:
  7430. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7431. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7432. break;
  7433. case NREDIR:
  7434. case NBACKGND:
  7435. case NSUBSHELL:
  7436. new->nredir.redirect = copynode(n->nredir.redirect);
  7437. new->nredir.n = copynode(n->nredir.n);
  7438. break;
  7439. case NAND:
  7440. case NOR:
  7441. case NSEMI:
  7442. case NWHILE:
  7443. case NUNTIL:
  7444. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7445. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7446. break;
  7447. case NIF:
  7448. new->nif.elsepart = copynode(n->nif.elsepart);
  7449. new->nif.ifpart = copynode(n->nif.ifpart);
  7450. new->nif.test = copynode(n->nif.test);
  7451. break;
  7452. case NFOR:
  7453. new->nfor.var = nodeckstrdup(n->nfor.var);
  7454. new->nfor.body = copynode(n->nfor.body);
  7455. new->nfor.args = copynode(n->nfor.args);
  7456. break;
  7457. case NCASE:
  7458. new->ncase.cases = copynode(n->ncase.cases);
  7459. new->ncase.expr = copynode(n->ncase.expr);
  7460. break;
  7461. case NCLIST:
  7462. new->nclist.body = copynode(n->nclist.body);
  7463. new->nclist.pattern = copynode(n->nclist.pattern);
  7464. new->nclist.next = copynode(n->nclist.next);
  7465. break;
  7466. case NDEFUN:
  7467. case NARG:
  7468. new->narg.backquote = copynodelist(n->narg.backquote);
  7469. new->narg.text = nodeckstrdup(n->narg.text);
  7470. new->narg.next = copynode(n->narg.next);
  7471. break;
  7472. case NTO:
  7473. #if ENABLE_ASH_BASH_COMPAT
  7474. case NTO2:
  7475. #endif
  7476. case NCLOBBER:
  7477. case NFROM:
  7478. case NFROMTO:
  7479. case NAPPEND:
  7480. new->nfile.fname = copynode(n->nfile.fname);
  7481. new->nfile.fd = n->nfile.fd;
  7482. new->nfile.next = copynode(n->nfile.next);
  7483. break;
  7484. case NTOFD:
  7485. case NFROMFD:
  7486. new->ndup.vname = copynode(n->ndup.vname);
  7487. new->ndup.dupfd = n->ndup.dupfd;
  7488. new->ndup.fd = n->ndup.fd;
  7489. new->ndup.next = copynode(n->ndup.next);
  7490. break;
  7491. case NHERE:
  7492. case NXHERE:
  7493. new->nhere.doc = copynode(n->nhere.doc);
  7494. new->nhere.fd = n->nhere.fd;
  7495. new->nhere.next = copynode(n->nhere.next);
  7496. break;
  7497. case NNOT:
  7498. new->nnot.com = copynode(n->nnot.com);
  7499. break;
  7500. };
  7501. new->type = n->type;
  7502. return new;
  7503. }
  7504. /*
  7505. * Make a copy of a parse tree.
  7506. */
  7507. static struct funcnode *
  7508. copyfunc(union node *n)
  7509. {
  7510. struct funcnode *f;
  7511. size_t blocksize;
  7512. funcblocksize = offsetof(struct funcnode, n);
  7513. funcstringsize = 0;
  7514. calcsize(n);
  7515. blocksize = funcblocksize;
  7516. f = ckmalloc(blocksize + funcstringsize);
  7517. funcblock = (char *) f + offsetof(struct funcnode, n);
  7518. funcstring = (char *) f + blocksize;
  7519. copynode(n);
  7520. f->count = 0;
  7521. return f;
  7522. }
  7523. /*
  7524. * Define a shell function.
  7525. */
  7526. static void
  7527. defun(char *name, union node *func)
  7528. {
  7529. struct cmdentry entry;
  7530. INT_OFF;
  7531. entry.cmdtype = CMDFUNCTION;
  7532. entry.u.func = copyfunc(func);
  7533. addcmdentry(name, &entry);
  7534. INT_ON;
  7535. }
  7536. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7537. #define SKIPBREAK (1 << 0)
  7538. #define SKIPCONT (1 << 1)
  7539. #define SKIPFUNC (1 << 2)
  7540. #define SKIPFILE (1 << 3)
  7541. #define SKIPEVAL (1 << 4)
  7542. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7543. static int skipcount; /* number of levels to skip */
  7544. static int funcnest; /* depth of function calls */
  7545. static int loopnest; /* current loop nesting level */
  7546. /* Forward decl way out to parsing code - dotrap needs it */
  7547. static int evalstring(char *s, int mask);
  7548. /* Called to execute a trap.
  7549. * Single callsite - at the end of evaltree().
  7550. * If we return non-zero, evaltree raises EXEXIT exception.
  7551. *
  7552. * Perhaps we should avoid entering new trap handlers
  7553. * while we are executing a trap handler. [is it a TODO?]
  7554. */
  7555. static int
  7556. dotrap(void)
  7557. {
  7558. uint8_t *g;
  7559. int sig;
  7560. uint8_t savestatus;
  7561. savestatus = exitstatus;
  7562. pending_sig = 0;
  7563. xbarrier();
  7564. TRACE(("dotrap entered\n"));
  7565. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7566. int want_exexit;
  7567. char *t;
  7568. if (*g == 0)
  7569. continue;
  7570. t = trap[sig];
  7571. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7572. * don't upset it by resetting gotsig[SIGINT-1] */
  7573. if (sig == SIGINT && !t)
  7574. continue;
  7575. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7576. *g = 0;
  7577. if (!t)
  7578. continue;
  7579. want_exexit = evalstring(t, SKIPEVAL);
  7580. exitstatus = savestatus;
  7581. if (want_exexit) {
  7582. TRACE(("dotrap returns %d\n", want_exexit));
  7583. return want_exexit;
  7584. }
  7585. }
  7586. TRACE(("dotrap returns 0\n"));
  7587. return 0;
  7588. }
  7589. /* forward declarations - evaluation is fairly recursive business... */
  7590. static void evalloop(union node *, int);
  7591. static void evalfor(union node *, int);
  7592. static void evalcase(union node *, int);
  7593. static void evalsubshell(union node *, int);
  7594. static void expredir(union node *);
  7595. static void evalpipe(union node *, int);
  7596. static void evalcommand(union node *, int);
  7597. static int evalbltin(const struct builtincmd *, int, char **);
  7598. static void prehash(union node *);
  7599. /*
  7600. * Evaluate a parse tree. The value is left in the global variable
  7601. * exitstatus.
  7602. */
  7603. static void
  7604. evaltree(union node *n, int flags)
  7605. {
  7606. struct jmploc *volatile savehandler = exception_handler;
  7607. struct jmploc jmploc;
  7608. int checkexit = 0;
  7609. void (*evalfn)(union node *, int);
  7610. int status;
  7611. int int_level;
  7612. SAVE_INT(int_level);
  7613. if (n == NULL) {
  7614. TRACE(("evaltree(NULL) called\n"));
  7615. goto out1;
  7616. }
  7617. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7618. exception_handler = &jmploc;
  7619. {
  7620. int err = setjmp(jmploc.loc);
  7621. if (err) {
  7622. /* if it was a signal, check for trap handlers */
  7623. if (exception_type == EXSIG) {
  7624. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7625. exception_type, err));
  7626. goto out;
  7627. }
  7628. /* continue on the way out */
  7629. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7630. exception_type, err));
  7631. exception_handler = savehandler;
  7632. longjmp(exception_handler->loc, err);
  7633. }
  7634. }
  7635. switch (n->type) {
  7636. default:
  7637. #if DEBUG
  7638. out1fmt("Node type = %d\n", n->type);
  7639. fflush_all();
  7640. break;
  7641. #endif
  7642. case NNOT:
  7643. evaltree(n->nnot.com, EV_TESTED);
  7644. status = !exitstatus;
  7645. goto setstatus;
  7646. case NREDIR:
  7647. expredir(n->nredir.redirect);
  7648. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7649. if (!status) {
  7650. evaltree(n->nredir.n, flags & EV_TESTED);
  7651. status = exitstatus;
  7652. }
  7653. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7654. goto setstatus;
  7655. case NCMD:
  7656. evalfn = evalcommand;
  7657. checkexit:
  7658. if (eflag && !(flags & EV_TESTED))
  7659. checkexit = ~0;
  7660. goto calleval;
  7661. case NFOR:
  7662. evalfn = evalfor;
  7663. goto calleval;
  7664. case NWHILE:
  7665. case NUNTIL:
  7666. evalfn = evalloop;
  7667. goto calleval;
  7668. case NSUBSHELL:
  7669. case NBACKGND:
  7670. evalfn = evalsubshell;
  7671. goto calleval;
  7672. case NPIPE:
  7673. evalfn = evalpipe;
  7674. goto checkexit;
  7675. case NCASE:
  7676. evalfn = evalcase;
  7677. goto calleval;
  7678. case NAND:
  7679. case NOR:
  7680. case NSEMI: {
  7681. #if NAND + 1 != NOR
  7682. #error NAND + 1 != NOR
  7683. #endif
  7684. #if NOR + 1 != NSEMI
  7685. #error NOR + 1 != NSEMI
  7686. #endif
  7687. unsigned is_or = n->type - NAND;
  7688. evaltree(
  7689. n->nbinary.ch1,
  7690. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7691. );
  7692. if (!exitstatus == is_or)
  7693. break;
  7694. if (!evalskip) {
  7695. n = n->nbinary.ch2;
  7696. evaln:
  7697. evalfn = evaltree;
  7698. calleval:
  7699. evalfn(n, flags);
  7700. break;
  7701. }
  7702. break;
  7703. }
  7704. case NIF:
  7705. evaltree(n->nif.test, EV_TESTED);
  7706. if (evalskip)
  7707. break;
  7708. if (exitstatus == 0) {
  7709. n = n->nif.ifpart;
  7710. goto evaln;
  7711. }
  7712. if (n->nif.elsepart) {
  7713. n = n->nif.elsepart;
  7714. goto evaln;
  7715. }
  7716. goto success;
  7717. case NDEFUN:
  7718. defun(n->narg.text, n->narg.next);
  7719. success:
  7720. status = 0;
  7721. setstatus:
  7722. exitstatus = status;
  7723. break;
  7724. }
  7725. out:
  7726. exception_handler = savehandler;
  7727. out1:
  7728. /* Order of checks below is important:
  7729. * signal handlers trigger before exit caused by "set -e".
  7730. */
  7731. if (pending_sig && dotrap())
  7732. goto exexit;
  7733. if (checkexit & exitstatus)
  7734. evalskip |= SKIPEVAL;
  7735. if (flags & EV_EXIT) {
  7736. exexit:
  7737. raise_exception(EXEXIT);
  7738. }
  7739. RESTORE_INT(int_level);
  7740. TRACE(("leaving evaltree (no interrupts)\n"));
  7741. }
  7742. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7743. static
  7744. #endif
  7745. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7746. static void
  7747. evalloop(union node *n, int flags)
  7748. {
  7749. int status;
  7750. loopnest++;
  7751. status = 0;
  7752. flags &= EV_TESTED;
  7753. for (;;) {
  7754. int i;
  7755. evaltree(n->nbinary.ch1, EV_TESTED);
  7756. if (evalskip) {
  7757. skipping:
  7758. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7759. evalskip = 0;
  7760. continue;
  7761. }
  7762. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7763. evalskip = 0;
  7764. break;
  7765. }
  7766. i = exitstatus;
  7767. if (n->type != NWHILE)
  7768. i = !i;
  7769. if (i != 0)
  7770. break;
  7771. evaltree(n->nbinary.ch2, flags);
  7772. status = exitstatus;
  7773. if (evalskip)
  7774. goto skipping;
  7775. }
  7776. loopnest--;
  7777. exitstatus = status;
  7778. }
  7779. static void
  7780. evalfor(union node *n, int flags)
  7781. {
  7782. struct arglist arglist;
  7783. union node *argp;
  7784. struct strlist *sp;
  7785. struct stackmark smark;
  7786. setstackmark(&smark);
  7787. arglist.list = NULL;
  7788. arglist.lastp = &arglist.list;
  7789. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7790. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  7791. /* XXX */
  7792. if (evalskip)
  7793. goto out;
  7794. }
  7795. *arglist.lastp = NULL;
  7796. exitstatus = 0;
  7797. loopnest++;
  7798. flags &= EV_TESTED;
  7799. for (sp = arglist.list; sp; sp = sp->next) {
  7800. setvar0(n->nfor.var, sp->text);
  7801. evaltree(n->nfor.body, flags);
  7802. if (evalskip) {
  7803. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7804. evalskip = 0;
  7805. continue;
  7806. }
  7807. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7808. evalskip = 0;
  7809. break;
  7810. }
  7811. }
  7812. loopnest--;
  7813. out:
  7814. popstackmark(&smark);
  7815. }
  7816. static void
  7817. evalcase(union node *n, int flags)
  7818. {
  7819. union node *cp;
  7820. union node *patp;
  7821. struct arglist arglist;
  7822. struct stackmark smark;
  7823. setstackmark(&smark);
  7824. arglist.list = NULL;
  7825. arglist.lastp = &arglist.list;
  7826. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7827. exitstatus = 0;
  7828. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7829. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7830. if (casematch(patp, arglist.list->text)) {
  7831. if (evalskip == 0) {
  7832. evaltree(cp->nclist.body, flags);
  7833. }
  7834. goto out;
  7835. }
  7836. }
  7837. }
  7838. out:
  7839. popstackmark(&smark);
  7840. }
  7841. /*
  7842. * Kick off a subshell to evaluate a tree.
  7843. */
  7844. static void
  7845. evalsubshell(union node *n, int flags)
  7846. {
  7847. struct job *jp;
  7848. int backgnd = (n->type == NBACKGND);
  7849. int status;
  7850. expredir(n->nredir.redirect);
  7851. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  7852. goto nofork;
  7853. INT_OFF;
  7854. jp = makejob(/*n,*/ 1);
  7855. if (forkshell(jp, n, backgnd) == 0) {
  7856. /* child */
  7857. INT_ON;
  7858. flags |= EV_EXIT;
  7859. if (backgnd)
  7860. flags &= ~EV_TESTED;
  7861. nofork:
  7862. redirect(n->nredir.redirect, 0);
  7863. evaltreenr(n->nredir.n, flags);
  7864. /* never returns */
  7865. }
  7866. status = 0;
  7867. if (!backgnd)
  7868. status = waitforjob(jp);
  7869. exitstatus = status;
  7870. INT_ON;
  7871. }
  7872. /*
  7873. * Compute the names of the files in a redirection list.
  7874. */
  7875. static void fixredir(union node *, const char *, int);
  7876. static void
  7877. expredir(union node *n)
  7878. {
  7879. union node *redir;
  7880. for (redir = n; redir; redir = redir->nfile.next) {
  7881. struct arglist fn;
  7882. fn.list = NULL;
  7883. fn.lastp = &fn.list;
  7884. switch (redir->type) {
  7885. case NFROMTO:
  7886. case NFROM:
  7887. case NTO:
  7888. #if ENABLE_ASH_BASH_COMPAT
  7889. case NTO2:
  7890. #endif
  7891. case NCLOBBER:
  7892. case NAPPEND:
  7893. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7894. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  7895. #if ENABLE_ASH_BASH_COMPAT
  7896. store_expfname:
  7897. #endif
  7898. #if 0
  7899. // By the design of stack allocator, the loop of this kind:
  7900. // while true; do while true; do break; done </dev/null; done
  7901. // will look like a memory leak: ash plans to free expfname's
  7902. // of "/dev/null" as soon as it finishes running the loop
  7903. // (in this case, never).
  7904. // This "fix" is wrong:
  7905. if (redir->nfile.expfname)
  7906. stunalloc(redir->nfile.expfname);
  7907. // It results in corrupted state of stacked allocations.
  7908. #endif
  7909. redir->nfile.expfname = fn.list->text;
  7910. break;
  7911. case NFROMFD:
  7912. case NTOFD: /* >& */
  7913. if (redir->ndup.vname) {
  7914. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7915. if (fn.list == NULL)
  7916. ash_msg_and_raise_error("redir error");
  7917. #if ENABLE_ASH_BASH_COMPAT
  7918. //FIXME: we used expandarg with different args!
  7919. if (!isdigit_str9(fn.list->text)) {
  7920. /* >&file, not >&fd */
  7921. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7922. ash_msg_and_raise_error("redir error");
  7923. redir->type = NTO2;
  7924. goto store_expfname;
  7925. }
  7926. #endif
  7927. fixredir(redir, fn.list->text, 1);
  7928. }
  7929. break;
  7930. }
  7931. }
  7932. }
  7933. /*
  7934. * Evaluate a pipeline. All the processes in the pipeline are children
  7935. * of the process creating the pipeline. (This differs from some versions
  7936. * of the shell, which make the last process in a pipeline the parent
  7937. * of all the rest.)
  7938. */
  7939. static void
  7940. evalpipe(union node *n, int flags)
  7941. {
  7942. struct job *jp;
  7943. struct nodelist *lp;
  7944. int pipelen;
  7945. int prevfd;
  7946. int pip[2];
  7947. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7948. pipelen = 0;
  7949. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7950. pipelen++;
  7951. flags |= EV_EXIT;
  7952. INT_OFF;
  7953. jp = makejob(/*n,*/ pipelen);
  7954. prevfd = -1;
  7955. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7956. prehash(lp->n);
  7957. pip[1] = -1;
  7958. if (lp->next) {
  7959. if (pipe(pip) < 0) {
  7960. close(prevfd);
  7961. ash_msg_and_raise_error("pipe call failed");
  7962. }
  7963. }
  7964. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7965. INT_ON;
  7966. if (pip[1] >= 0) {
  7967. close(pip[0]);
  7968. }
  7969. if (prevfd > 0) {
  7970. dup2(prevfd, 0);
  7971. close(prevfd);
  7972. }
  7973. if (pip[1] > 1) {
  7974. dup2(pip[1], 1);
  7975. close(pip[1]);
  7976. }
  7977. evaltreenr(lp->n, flags);
  7978. /* never returns */
  7979. }
  7980. if (prevfd >= 0)
  7981. close(prevfd);
  7982. prevfd = pip[0];
  7983. /* Don't want to trigger debugging */
  7984. if (pip[1] != -1)
  7985. close(pip[1]);
  7986. }
  7987. if (n->npipe.pipe_backgnd == 0) {
  7988. exitstatus = waitforjob(jp);
  7989. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7990. }
  7991. INT_ON;
  7992. }
  7993. /*
  7994. * Controls whether the shell is interactive or not.
  7995. */
  7996. static void
  7997. setinteractive(int on)
  7998. {
  7999. static smallint is_interactive;
  8000. if (++on == is_interactive)
  8001. return;
  8002. is_interactive = on;
  8003. setsignal(SIGINT);
  8004. setsignal(SIGQUIT);
  8005. setsignal(SIGTERM);
  8006. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8007. if (is_interactive > 1) {
  8008. /* Looks like they want an interactive shell */
  8009. static smallint did_banner;
  8010. if (!did_banner) {
  8011. /* note: ash and hush share this string */
  8012. out1fmt("\n\n%s %s\n"
  8013. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8014. "\n",
  8015. bb_banner,
  8016. "built-in shell (ash)"
  8017. );
  8018. did_banner = 1;
  8019. }
  8020. }
  8021. #endif
  8022. }
  8023. static void
  8024. optschanged(void)
  8025. {
  8026. #if DEBUG
  8027. opentrace();
  8028. #endif
  8029. setinteractive(iflag);
  8030. setjobctl(mflag);
  8031. #if ENABLE_FEATURE_EDITING_VI
  8032. if (viflag)
  8033. line_input_state->flags |= VI_MODE;
  8034. else
  8035. line_input_state->flags &= ~VI_MODE;
  8036. #else
  8037. viflag = 0; /* forcibly keep the option off */
  8038. #endif
  8039. }
  8040. static struct localvar *localvars;
  8041. /*
  8042. * Called after a function returns.
  8043. * Interrupts must be off.
  8044. */
  8045. static void
  8046. poplocalvars(void)
  8047. {
  8048. struct localvar *lvp;
  8049. struct var *vp;
  8050. while ((lvp = localvars) != NULL) {
  8051. localvars = lvp->next;
  8052. vp = lvp->vp;
  8053. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8054. if (vp == NULL) { /* $- saved */
  8055. memcpy(optlist, lvp->text, sizeof(optlist));
  8056. free((char*)lvp->text);
  8057. optschanged();
  8058. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  8059. unsetvar(vp->var_text);
  8060. } else {
  8061. if (vp->var_func)
  8062. vp->var_func(var_end(lvp->text));
  8063. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8064. free((char*)vp->var_text);
  8065. vp->flags = lvp->flags;
  8066. vp->var_text = lvp->text;
  8067. }
  8068. free(lvp);
  8069. }
  8070. }
  8071. static int
  8072. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8073. {
  8074. volatile struct shparam saveparam;
  8075. struct localvar *volatile savelocalvars;
  8076. struct jmploc *volatile savehandler;
  8077. struct jmploc jmploc;
  8078. int e;
  8079. saveparam = shellparam;
  8080. savelocalvars = localvars;
  8081. e = setjmp(jmploc.loc);
  8082. if (e) {
  8083. goto funcdone;
  8084. }
  8085. INT_OFF;
  8086. savehandler = exception_handler;
  8087. exception_handler = &jmploc;
  8088. localvars = NULL;
  8089. shellparam.malloced = 0;
  8090. func->count++;
  8091. funcnest++;
  8092. INT_ON;
  8093. shellparam.nparam = argc - 1;
  8094. shellparam.p = argv + 1;
  8095. #if ENABLE_ASH_GETOPTS
  8096. shellparam.optind = 1;
  8097. shellparam.optoff = -1;
  8098. #endif
  8099. evaltree(&func->n, flags & EV_TESTED);
  8100. funcdone:
  8101. INT_OFF;
  8102. funcnest--;
  8103. freefunc(func);
  8104. poplocalvars();
  8105. localvars = savelocalvars;
  8106. freeparam(&shellparam);
  8107. shellparam = saveparam;
  8108. exception_handler = savehandler;
  8109. INT_ON;
  8110. evalskip &= ~SKIPFUNC;
  8111. return e;
  8112. }
  8113. #if ENABLE_ASH_CMDCMD
  8114. static char **
  8115. parse_command_args(char **argv, const char **path)
  8116. {
  8117. char *cp, c;
  8118. for (;;) {
  8119. cp = *++argv;
  8120. if (!cp)
  8121. return 0;
  8122. if (*cp++ != '-')
  8123. break;
  8124. c = *cp++;
  8125. if (!c)
  8126. break;
  8127. if (c == '-' && !*cp) {
  8128. argv++;
  8129. break;
  8130. }
  8131. do {
  8132. switch (c) {
  8133. case 'p':
  8134. *path = bb_default_path;
  8135. break;
  8136. default:
  8137. /* run 'typecmd' for other options */
  8138. return 0;
  8139. }
  8140. c = *cp++;
  8141. } while (c);
  8142. }
  8143. return argv;
  8144. }
  8145. #endif
  8146. /*
  8147. * Make a variable a local variable. When a variable is made local, it's
  8148. * value and flags are saved in a localvar structure. The saved values
  8149. * will be restored when the shell function returns. We handle the name
  8150. * "-" as a special case: it makes changes to "set +-options" local
  8151. * (options will be restored on return from the function).
  8152. */
  8153. static void
  8154. mklocal(char *name)
  8155. {
  8156. struct localvar *lvp;
  8157. struct var **vpp;
  8158. struct var *vp;
  8159. char *eq = strchr(name, '=');
  8160. INT_OFF;
  8161. /* Cater for duplicate "local". Examples:
  8162. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8163. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8164. */
  8165. lvp = localvars;
  8166. while (lvp) {
  8167. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8168. if (eq)
  8169. setvareq(name, 0);
  8170. /* else:
  8171. * it's a duplicate "local VAR" declaration, do nothing
  8172. */
  8173. return;
  8174. }
  8175. lvp = lvp->next;
  8176. }
  8177. lvp = ckzalloc(sizeof(*lvp));
  8178. if (LONE_DASH(name)) {
  8179. char *p;
  8180. p = ckmalloc(sizeof(optlist));
  8181. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8182. vp = NULL;
  8183. } else {
  8184. vpp = hashvar(name);
  8185. vp = *findvar(vpp, name);
  8186. if (vp == NULL) {
  8187. /* variable did not exist yet */
  8188. if (eq)
  8189. setvareq(name, VSTRFIXED);
  8190. else
  8191. setvar(name, NULL, VSTRFIXED);
  8192. vp = *vpp; /* the new variable */
  8193. lvp->flags = VUNSET;
  8194. } else {
  8195. lvp->text = vp->var_text;
  8196. lvp->flags = vp->flags;
  8197. /* make sure neither "struct var" nor string gets freed
  8198. * during (un)setting:
  8199. */
  8200. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8201. if (eq)
  8202. setvareq(name, 0);
  8203. else
  8204. /* "local VAR" unsets VAR: */
  8205. setvar0(name, NULL);
  8206. }
  8207. }
  8208. lvp->vp = vp;
  8209. lvp->next = localvars;
  8210. localvars = lvp;
  8211. INT_ON;
  8212. }
  8213. /*
  8214. * The "local" command.
  8215. */
  8216. static int FAST_FUNC
  8217. localcmd(int argc UNUSED_PARAM, char **argv)
  8218. {
  8219. char *name;
  8220. argv = argptr;
  8221. while ((name = *argv++) != NULL) {
  8222. mklocal(name);
  8223. }
  8224. return 0;
  8225. }
  8226. static int FAST_FUNC
  8227. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8228. {
  8229. return 1;
  8230. }
  8231. static int FAST_FUNC
  8232. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8233. {
  8234. return 0;
  8235. }
  8236. static int FAST_FUNC
  8237. execcmd(int argc UNUSED_PARAM, char **argv)
  8238. {
  8239. if (argv[1]) {
  8240. iflag = 0; /* exit on error */
  8241. mflag = 0;
  8242. optschanged();
  8243. shellexec(argv + 1, pathval(), 0);
  8244. }
  8245. return 0;
  8246. }
  8247. /*
  8248. * The return command.
  8249. */
  8250. static int FAST_FUNC
  8251. returncmd(int argc UNUSED_PARAM, char **argv)
  8252. {
  8253. /*
  8254. * If called outside a function, do what ksh does;
  8255. * skip the rest of the file.
  8256. */
  8257. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8258. return argv[1] ? number(argv[1]) : exitstatus;
  8259. }
  8260. /* Forward declarations for builtintab[] */
  8261. static int breakcmd(int, char **) FAST_FUNC;
  8262. static int dotcmd(int, char **) FAST_FUNC;
  8263. static int evalcmd(int, char **) FAST_FUNC;
  8264. static int exitcmd(int, char **) FAST_FUNC;
  8265. static int exportcmd(int, char **) FAST_FUNC;
  8266. #if ENABLE_ASH_GETOPTS
  8267. static int getoptscmd(int, char **) FAST_FUNC;
  8268. #endif
  8269. #if ENABLE_ASH_HELP
  8270. static int helpcmd(int, char **) FAST_FUNC;
  8271. #endif
  8272. #if MAX_HISTORY
  8273. static int historycmd(int, char **) FAST_FUNC;
  8274. #endif
  8275. #if ENABLE_SH_MATH_SUPPORT
  8276. static int letcmd(int, char **) FAST_FUNC;
  8277. #endif
  8278. static int readcmd(int, char **) FAST_FUNC;
  8279. static int setcmd(int, char **) FAST_FUNC;
  8280. static int shiftcmd(int, char **) FAST_FUNC;
  8281. static int timescmd(int, char **) FAST_FUNC;
  8282. static int trapcmd(int, char **) FAST_FUNC;
  8283. static int umaskcmd(int, char **) FAST_FUNC;
  8284. static int unsetcmd(int, char **) FAST_FUNC;
  8285. static int ulimitcmd(int, char **) FAST_FUNC;
  8286. #define BUILTIN_NOSPEC "0"
  8287. #define BUILTIN_SPECIAL "1"
  8288. #define BUILTIN_REGULAR "2"
  8289. #define BUILTIN_SPEC_REG "3"
  8290. #define BUILTIN_ASSIGN "4"
  8291. #define BUILTIN_SPEC_ASSG "5"
  8292. #define BUILTIN_REG_ASSG "6"
  8293. #define BUILTIN_SPEC_REG_ASSG "7"
  8294. /* Stubs for calling non-FAST_FUNC's */
  8295. #if ENABLE_ASH_BUILTIN_ECHO
  8296. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8297. #endif
  8298. #if ENABLE_ASH_BUILTIN_PRINTF
  8299. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8300. #endif
  8301. #if ENABLE_ASH_BUILTIN_TEST
  8302. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8303. #endif
  8304. /* Keep these in proper order since it is searched via bsearch() */
  8305. static const struct builtincmd builtintab[] = {
  8306. { BUILTIN_SPEC_REG "." , dotcmd },
  8307. { BUILTIN_SPEC_REG ":" , truecmd },
  8308. #if ENABLE_ASH_BUILTIN_TEST
  8309. { BUILTIN_REGULAR "[" , testcmd },
  8310. #if ENABLE_ASH_BASH_COMPAT
  8311. { BUILTIN_REGULAR "[[" , testcmd },
  8312. #endif
  8313. #endif
  8314. #if ENABLE_ASH_ALIAS
  8315. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8316. #endif
  8317. #if JOBS
  8318. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8319. #endif
  8320. { BUILTIN_SPEC_REG "break" , breakcmd },
  8321. { BUILTIN_REGULAR "cd" , cdcmd },
  8322. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8323. #if ENABLE_ASH_CMDCMD
  8324. { BUILTIN_REGULAR "command" , commandcmd },
  8325. #endif
  8326. { BUILTIN_SPEC_REG "continue", breakcmd },
  8327. #if ENABLE_ASH_BUILTIN_ECHO
  8328. { BUILTIN_REGULAR "echo" , echocmd },
  8329. #endif
  8330. { BUILTIN_SPEC_REG "eval" , evalcmd },
  8331. { BUILTIN_SPEC_REG "exec" , execcmd },
  8332. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8333. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8334. { BUILTIN_REGULAR "false" , falsecmd },
  8335. #if JOBS
  8336. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8337. #endif
  8338. #if ENABLE_ASH_GETOPTS
  8339. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8340. #endif
  8341. { BUILTIN_NOSPEC "hash" , hashcmd },
  8342. #if ENABLE_ASH_HELP
  8343. { BUILTIN_NOSPEC "help" , helpcmd },
  8344. #endif
  8345. #if MAX_HISTORY
  8346. { BUILTIN_NOSPEC "history" , historycmd },
  8347. #endif
  8348. #if JOBS
  8349. { BUILTIN_REGULAR "jobs" , jobscmd },
  8350. { BUILTIN_REGULAR "kill" , killcmd },
  8351. #endif
  8352. #if ENABLE_SH_MATH_SUPPORT
  8353. { BUILTIN_NOSPEC "let" , letcmd },
  8354. #endif
  8355. { BUILTIN_ASSIGN "local" , localcmd },
  8356. #if ENABLE_ASH_BUILTIN_PRINTF
  8357. { BUILTIN_REGULAR "printf" , printfcmd },
  8358. #endif
  8359. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8360. { BUILTIN_REGULAR "read" , readcmd },
  8361. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8362. { BUILTIN_SPEC_REG "return" , returncmd },
  8363. { BUILTIN_SPEC_REG "set" , setcmd },
  8364. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8365. #if ENABLE_ASH_BASH_COMPAT
  8366. { BUILTIN_SPEC_REG "source" , dotcmd },
  8367. #endif
  8368. #if ENABLE_ASH_BUILTIN_TEST
  8369. { BUILTIN_REGULAR "test" , testcmd },
  8370. #endif
  8371. { BUILTIN_SPEC_REG "times" , timescmd },
  8372. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8373. { BUILTIN_REGULAR "true" , truecmd },
  8374. { BUILTIN_NOSPEC "type" , typecmd },
  8375. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8376. { BUILTIN_REGULAR "umask" , umaskcmd },
  8377. #if ENABLE_ASH_ALIAS
  8378. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8379. #endif
  8380. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8381. { BUILTIN_REGULAR "wait" , waitcmd },
  8382. };
  8383. /* Should match the above table! */
  8384. #define COMMANDCMD (builtintab + \
  8385. 2 + \
  8386. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8387. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8388. 1 * ENABLE_ASH_ALIAS + \
  8389. 1 * ENABLE_ASH_JOB_CONTROL + \
  8390. 3)
  8391. #define EXECCMD (builtintab + \
  8392. 2 + \
  8393. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8394. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8395. 1 * ENABLE_ASH_ALIAS + \
  8396. 1 * ENABLE_ASH_JOB_CONTROL + \
  8397. 3 + \
  8398. 1 * ENABLE_ASH_CMDCMD + \
  8399. 1 + \
  8400. ENABLE_ASH_BUILTIN_ECHO + \
  8401. 1)
  8402. /*
  8403. * Search the table of builtin commands.
  8404. */
  8405. static struct builtincmd *
  8406. find_builtin(const char *name)
  8407. {
  8408. struct builtincmd *bp;
  8409. bp = bsearch(
  8410. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8411. pstrcmp
  8412. );
  8413. return bp;
  8414. }
  8415. /*
  8416. * Execute a simple command.
  8417. */
  8418. static int
  8419. isassignment(const char *p)
  8420. {
  8421. const char *q = endofname(p);
  8422. if (p == q)
  8423. return 0;
  8424. return *q == '=';
  8425. }
  8426. static int FAST_FUNC
  8427. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8428. {
  8429. /* Preserve exitstatus of a previous possible redirection
  8430. * as POSIX mandates */
  8431. return back_exitstatus;
  8432. }
  8433. static void
  8434. evalcommand(union node *cmd, int flags)
  8435. {
  8436. static const struct builtincmd null_bltin = {
  8437. "\0\0", bltincmd /* why three NULs? */
  8438. };
  8439. struct stackmark smark;
  8440. union node *argp;
  8441. struct arglist arglist;
  8442. struct arglist varlist;
  8443. char **argv;
  8444. int argc;
  8445. const struct strlist *sp;
  8446. struct cmdentry cmdentry;
  8447. struct job *jp;
  8448. char *lastarg;
  8449. const char *path;
  8450. int spclbltin;
  8451. int status;
  8452. char **nargv;
  8453. struct builtincmd *bcmd;
  8454. smallint cmd_is_exec;
  8455. smallint pseudovarflag = 0;
  8456. /* First expand the arguments. */
  8457. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8458. setstackmark(&smark);
  8459. back_exitstatus = 0;
  8460. cmdentry.cmdtype = CMDBUILTIN;
  8461. cmdentry.u.cmd = &null_bltin;
  8462. varlist.lastp = &varlist.list;
  8463. *varlist.lastp = NULL;
  8464. arglist.lastp = &arglist.list;
  8465. *arglist.lastp = NULL;
  8466. argc = 0;
  8467. if (cmd->ncmd.args) {
  8468. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8469. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8470. }
  8471. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8472. struct strlist **spp;
  8473. spp = arglist.lastp;
  8474. if (pseudovarflag && isassignment(argp->narg.text))
  8475. expandarg(argp, &arglist, EXP_VARTILDE);
  8476. else
  8477. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8478. for (sp = *spp; sp; sp = sp->next)
  8479. argc++;
  8480. }
  8481. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8482. for (sp = arglist.list; sp; sp = sp->next) {
  8483. TRACE(("evalcommand arg: %s\n", sp->text));
  8484. *nargv++ = sp->text;
  8485. }
  8486. *nargv = NULL;
  8487. lastarg = NULL;
  8488. if (iflag && funcnest == 0 && argc > 0)
  8489. lastarg = nargv[-1];
  8490. preverrout_fd = 2;
  8491. expredir(cmd->ncmd.redirect);
  8492. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8493. path = vpath.var_text;
  8494. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8495. struct strlist **spp;
  8496. char *p;
  8497. spp = varlist.lastp;
  8498. expandarg(argp, &varlist, EXP_VARTILDE);
  8499. /*
  8500. * Modify the command lookup path, if a PATH= assignment
  8501. * is present
  8502. */
  8503. p = (*spp)->text;
  8504. if (varcmp(p, path) == 0)
  8505. path = p;
  8506. }
  8507. /* Print the command if xflag is set. */
  8508. if (xflag) {
  8509. int n;
  8510. const char *p = " %s" + 1;
  8511. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8512. sp = varlist.list;
  8513. for (n = 0; n < 2; n++) {
  8514. while (sp) {
  8515. fdprintf(preverrout_fd, p, sp->text);
  8516. sp = sp->next;
  8517. p = " %s";
  8518. }
  8519. sp = arglist.list;
  8520. }
  8521. safe_write(preverrout_fd, "\n", 1);
  8522. }
  8523. cmd_is_exec = 0;
  8524. spclbltin = -1;
  8525. /* Now locate the command. */
  8526. if (argc) {
  8527. int cmd_flag = DO_ERR;
  8528. #if ENABLE_ASH_CMDCMD
  8529. const char *oldpath = path + 5;
  8530. #endif
  8531. path += 5;
  8532. for (;;) {
  8533. find_command(argv[0], &cmdentry, cmd_flag, path);
  8534. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8535. flush_stdout_stderr();
  8536. status = 127;
  8537. goto bail;
  8538. }
  8539. /* implement bltin and command here */
  8540. if (cmdentry.cmdtype != CMDBUILTIN)
  8541. break;
  8542. if (spclbltin < 0)
  8543. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8544. if (cmdentry.u.cmd == EXECCMD)
  8545. cmd_is_exec = 1;
  8546. #if ENABLE_ASH_CMDCMD
  8547. if (cmdentry.u.cmd == COMMANDCMD) {
  8548. path = oldpath;
  8549. nargv = parse_command_args(argv, &path);
  8550. if (!nargv)
  8551. break;
  8552. argc -= nargv - argv;
  8553. argv = nargv;
  8554. cmd_flag |= DO_NOFUNC;
  8555. } else
  8556. #endif
  8557. break;
  8558. }
  8559. }
  8560. if (status) {
  8561. /* We have a redirection error. */
  8562. if (spclbltin > 0)
  8563. raise_exception(EXERROR);
  8564. bail:
  8565. exitstatus = status;
  8566. goto out;
  8567. }
  8568. /* Execute the command. */
  8569. switch (cmdentry.cmdtype) {
  8570. default: {
  8571. #if ENABLE_FEATURE_SH_NOFORK
  8572. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  8573. * around run_nofork_applet() call.
  8574. * (2) Should this check also be done in forkshell()?
  8575. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  8576. */
  8577. /* find_command() encodes applet_no as (-2 - applet_no) */
  8578. int applet_no = (- cmdentry.u.index - 2);
  8579. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8580. listsetvar(varlist.list, VEXPORT|VSTACK);
  8581. /* run <applet>_main() */
  8582. exitstatus = run_nofork_applet(applet_no, argv);
  8583. break;
  8584. }
  8585. #endif
  8586. /* Can we avoid forking off? For example, very last command
  8587. * in a script or a subshell does not need forking,
  8588. * we can just exec it.
  8589. */
  8590. if (!(flags & EV_EXIT) || may_have_traps) {
  8591. /* No, forking off a child is necessary */
  8592. INT_OFF;
  8593. jp = makejob(/*cmd,*/ 1);
  8594. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8595. /* parent */
  8596. exitstatus = waitforjob(jp);
  8597. INT_ON;
  8598. TRACE(("forked child exited with %d\n", exitstatus));
  8599. break;
  8600. }
  8601. /* child */
  8602. FORCE_INT_ON;
  8603. /* fall through to exec'ing external program */
  8604. }
  8605. listsetvar(varlist.list, VEXPORT|VSTACK);
  8606. shellexec(argv, path, cmdentry.u.index);
  8607. /* NOTREACHED */
  8608. } /* default */
  8609. case CMDBUILTIN:
  8610. cmdenviron = varlist.list;
  8611. if (cmdenviron) {
  8612. struct strlist *list = cmdenviron;
  8613. int i = VNOSET;
  8614. if (spclbltin > 0 || argc == 0) {
  8615. i = 0;
  8616. if (cmd_is_exec && argc > 1)
  8617. i = VEXPORT;
  8618. }
  8619. listsetvar(list, i);
  8620. }
  8621. /* Tight loop with builtins only:
  8622. * "while kill -0 $child; do true; done"
  8623. * will never exit even if $child died, unless we do this
  8624. * to reap the zombie and make kill detect that it's gone: */
  8625. dowait(DOWAIT_NONBLOCK, NULL);
  8626. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8627. int exit_status;
  8628. int i = exception_type;
  8629. if (i == EXEXIT)
  8630. goto raise;
  8631. exit_status = 2;
  8632. if (i == EXINT)
  8633. exit_status = 128 + SIGINT;
  8634. if (i == EXSIG)
  8635. exit_status = 128 + pending_sig;
  8636. exitstatus = exit_status;
  8637. if (i == EXINT || spclbltin > 0) {
  8638. raise:
  8639. longjmp(exception_handler->loc, 1);
  8640. }
  8641. FORCE_INT_ON;
  8642. }
  8643. break;
  8644. case CMDFUNCTION:
  8645. listsetvar(varlist.list, 0);
  8646. /* See above for the rationale */
  8647. dowait(DOWAIT_NONBLOCK, NULL);
  8648. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8649. goto raise;
  8650. break;
  8651. } /* switch */
  8652. out:
  8653. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8654. if (lastarg) {
  8655. /* dsl: I think this is intended to be used to support
  8656. * '_' in 'vi' command mode during line editing...
  8657. * However I implemented that within libedit itself.
  8658. */
  8659. setvar0("_", lastarg);
  8660. }
  8661. popstackmark(&smark);
  8662. }
  8663. static int
  8664. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8665. {
  8666. char *volatile savecmdname;
  8667. struct jmploc *volatile savehandler;
  8668. struct jmploc jmploc;
  8669. int i;
  8670. savecmdname = commandname;
  8671. i = setjmp(jmploc.loc);
  8672. if (i)
  8673. goto cmddone;
  8674. savehandler = exception_handler;
  8675. exception_handler = &jmploc;
  8676. commandname = argv[0];
  8677. argptr = argv + 1;
  8678. optptr = NULL; /* initialize nextopt */
  8679. exitstatus = (*cmd->builtin)(argc, argv);
  8680. flush_stdout_stderr();
  8681. cmddone:
  8682. exitstatus |= ferror(stdout);
  8683. clearerr(stdout);
  8684. commandname = savecmdname;
  8685. exception_handler = savehandler;
  8686. return i;
  8687. }
  8688. static int
  8689. goodname(const char *p)
  8690. {
  8691. return endofname(p)[0] == '\0';
  8692. }
  8693. /*
  8694. * Search for a command. This is called before we fork so that the
  8695. * location of the command will be available in the parent as well as
  8696. * the child. The check for "goodname" is an overly conservative
  8697. * check that the name will not be subject to expansion.
  8698. */
  8699. static void
  8700. prehash(union node *n)
  8701. {
  8702. struct cmdentry entry;
  8703. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8704. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8705. }
  8706. /* ============ Builtin commands
  8707. *
  8708. * Builtin commands whose functions are closely tied to evaluation
  8709. * are implemented here.
  8710. */
  8711. /*
  8712. * Handle break and continue commands. Break, continue, and return are
  8713. * all handled by setting the evalskip flag. The evaluation routines
  8714. * above all check this flag, and if it is set they start skipping
  8715. * commands rather than executing them. The variable skipcount is
  8716. * the number of loops to break/continue, or the number of function
  8717. * levels to return. (The latter is always 1.) It should probably
  8718. * be an error to break out of more loops than exist, but it isn't
  8719. * in the standard shell so we don't make it one here.
  8720. */
  8721. static int FAST_FUNC
  8722. breakcmd(int argc UNUSED_PARAM, char **argv)
  8723. {
  8724. int n = argv[1] ? number(argv[1]) : 1;
  8725. if (n <= 0)
  8726. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8727. if (n > loopnest)
  8728. n = loopnest;
  8729. if (n > 0) {
  8730. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8731. skipcount = n;
  8732. }
  8733. return 0;
  8734. }
  8735. /* ============ input.c
  8736. *
  8737. * This implements the input routines used by the parser.
  8738. */
  8739. enum {
  8740. INPUT_PUSH_FILE = 1,
  8741. INPUT_NOFILE_OK = 2,
  8742. };
  8743. static smallint checkkwd;
  8744. /* values of checkkwd variable */
  8745. #define CHKALIAS 0x1
  8746. #define CHKKWD 0x2
  8747. #define CHKNL 0x4
  8748. /*
  8749. * Push a string back onto the input at this current parsefile level.
  8750. * We handle aliases this way.
  8751. */
  8752. #if !ENABLE_ASH_ALIAS
  8753. #define pushstring(s, ap) pushstring(s)
  8754. #endif
  8755. static void
  8756. pushstring(char *s, struct alias *ap)
  8757. {
  8758. struct strpush *sp;
  8759. int len;
  8760. len = strlen(s);
  8761. INT_OFF;
  8762. if (g_parsefile->strpush) {
  8763. sp = ckzalloc(sizeof(*sp));
  8764. sp->prev = g_parsefile->strpush;
  8765. } else {
  8766. sp = &(g_parsefile->basestrpush);
  8767. }
  8768. g_parsefile->strpush = sp;
  8769. sp->prev_string = g_parsefile->next_to_pgetc;
  8770. sp->prev_left_in_line = g_parsefile->left_in_line;
  8771. #if ENABLE_ASH_ALIAS
  8772. sp->ap = ap;
  8773. if (ap) {
  8774. ap->flag |= ALIASINUSE;
  8775. sp->string = s;
  8776. }
  8777. #endif
  8778. g_parsefile->next_to_pgetc = s;
  8779. g_parsefile->left_in_line = len;
  8780. INT_ON;
  8781. }
  8782. static void
  8783. popstring(void)
  8784. {
  8785. struct strpush *sp = g_parsefile->strpush;
  8786. INT_OFF;
  8787. #if ENABLE_ASH_ALIAS
  8788. if (sp->ap) {
  8789. if (g_parsefile->next_to_pgetc[-1] == ' '
  8790. || g_parsefile->next_to_pgetc[-1] == '\t'
  8791. ) {
  8792. checkkwd |= CHKALIAS;
  8793. }
  8794. if (sp->string != sp->ap->val) {
  8795. free(sp->string);
  8796. }
  8797. sp->ap->flag &= ~ALIASINUSE;
  8798. if (sp->ap->flag & ALIASDEAD) {
  8799. unalias(sp->ap->name);
  8800. }
  8801. }
  8802. #endif
  8803. g_parsefile->next_to_pgetc = sp->prev_string;
  8804. g_parsefile->left_in_line = sp->prev_left_in_line;
  8805. g_parsefile->strpush = sp->prev;
  8806. if (sp != &(g_parsefile->basestrpush))
  8807. free(sp);
  8808. INT_ON;
  8809. }
  8810. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8811. //it peeks whether it is &>, and then pushes back both chars.
  8812. //This function needs to save last *next_to_pgetc to buf[0]
  8813. //to make two pungetc() reliable. Currently,
  8814. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8815. static int
  8816. preadfd(void)
  8817. {
  8818. int nr;
  8819. char *buf = g_parsefile->buf;
  8820. g_parsefile->next_to_pgetc = buf;
  8821. #if ENABLE_FEATURE_EDITING
  8822. retry:
  8823. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  8824. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  8825. else {
  8826. int timeout = -1;
  8827. # if ENABLE_ASH_IDLE_TIMEOUT
  8828. if (iflag) {
  8829. const char *tmout_var = lookupvar("TMOUT");
  8830. if (tmout_var) {
  8831. timeout = atoi(tmout_var) * 1000;
  8832. if (timeout <= 0)
  8833. timeout = -1;
  8834. }
  8835. }
  8836. # endif
  8837. # if ENABLE_FEATURE_TAB_COMPLETION
  8838. line_input_state->path_lookup = pathval();
  8839. # endif
  8840. reinit_unicode_for_ash();
  8841. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ, timeout);
  8842. if (nr == 0) {
  8843. /* Ctrl+C pressed */
  8844. if (trap[SIGINT]) {
  8845. buf[0] = '\n';
  8846. buf[1] = '\0';
  8847. raise(SIGINT);
  8848. return 1;
  8849. }
  8850. goto retry;
  8851. }
  8852. if (nr < 0) {
  8853. if (errno == 0) {
  8854. /* Ctrl+D pressed */
  8855. nr = 0;
  8856. }
  8857. # if ENABLE_ASH_IDLE_TIMEOUT
  8858. else if (errno == EAGAIN && timeout > 0) {
  8859. puts("\007timed out waiting for input: auto-logout");
  8860. exitshell();
  8861. }
  8862. # endif
  8863. }
  8864. }
  8865. #else
  8866. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  8867. #endif
  8868. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  8869. if (nr < 0) {
  8870. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8871. int flags = fcntl(0, F_GETFL);
  8872. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8873. flags &= ~O_NONBLOCK;
  8874. if (fcntl(0, F_SETFL, flags) >= 0) {
  8875. out2str("sh: turning off NDELAY mode\n");
  8876. goto retry;
  8877. }
  8878. }
  8879. }
  8880. }
  8881. #endif
  8882. return nr;
  8883. }
  8884. /*
  8885. * Refill the input buffer and return the next input character:
  8886. *
  8887. * 1) If a string was pushed back on the input, pop it;
  8888. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8889. * or we are reading from a string so we can't refill the buffer,
  8890. * return EOF.
  8891. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8892. * 4) Process input up to the next newline, deleting nul characters.
  8893. */
  8894. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8895. #define pgetc_debug(...) ((void)0)
  8896. static int
  8897. preadbuffer(void)
  8898. {
  8899. char *q;
  8900. int more;
  8901. while (g_parsefile->strpush) {
  8902. #if ENABLE_ASH_ALIAS
  8903. if (g_parsefile->left_in_line == -1
  8904. && g_parsefile->strpush->ap
  8905. && g_parsefile->next_to_pgetc[-1] != ' '
  8906. && g_parsefile->next_to_pgetc[-1] != '\t'
  8907. ) {
  8908. pgetc_debug("preadbuffer PEOA");
  8909. return PEOA;
  8910. }
  8911. #endif
  8912. popstring();
  8913. /* try "pgetc" now: */
  8914. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8915. g_parsefile->left_in_line,
  8916. g_parsefile->next_to_pgetc,
  8917. g_parsefile->next_to_pgetc);
  8918. if (--g_parsefile->left_in_line >= 0)
  8919. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8920. }
  8921. /* on both branches above g_parsefile->left_in_line < 0.
  8922. * "pgetc" needs refilling.
  8923. */
  8924. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8925. * pungetc() may increment it a few times.
  8926. * Assuming it won't increment it to less than -90.
  8927. */
  8928. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8929. pgetc_debug("preadbuffer PEOF1");
  8930. /* even in failure keep left_in_line and next_to_pgetc
  8931. * in lock step, for correct multi-layer pungetc.
  8932. * left_in_line was decremented before preadbuffer(),
  8933. * must inc next_to_pgetc: */
  8934. g_parsefile->next_to_pgetc++;
  8935. return PEOF;
  8936. }
  8937. more = g_parsefile->left_in_buffer;
  8938. if (more <= 0) {
  8939. flush_stdout_stderr();
  8940. again:
  8941. more = preadfd();
  8942. if (more <= 0) {
  8943. /* don't try reading again */
  8944. g_parsefile->left_in_line = -99;
  8945. pgetc_debug("preadbuffer PEOF2");
  8946. g_parsefile->next_to_pgetc++;
  8947. return PEOF;
  8948. }
  8949. }
  8950. /* Find out where's the end of line.
  8951. * Set g_parsefile->left_in_line
  8952. * and g_parsefile->left_in_buffer acordingly.
  8953. * NUL chars are deleted.
  8954. */
  8955. q = g_parsefile->next_to_pgetc;
  8956. for (;;) {
  8957. char c;
  8958. more--;
  8959. c = *q;
  8960. if (c == '\0') {
  8961. memmove(q, q + 1, more);
  8962. } else {
  8963. q++;
  8964. if (c == '\n') {
  8965. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8966. break;
  8967. }
  8968. }
  8969. if (more <= 0) {
  8970. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8971. if (g_parsefile->left_in_line < 0)
  8972. goto again;
  8973. break;
  8974. }
  8975. }
  8976. g_parsefile->left_in_buffer = more;
  8977. if (vflag) {
  8978. char save = *q;
  8979. *q = '\0';
  8980. out2str(g_parsefile->next_to_pgetc);
  8981. *q = save;
  8982. }
  8983. pgetc_debug("preadbuffer at %d:%p'%s'",
  8984. g_parsefile->left_in_line,
  8985. g_parsefile->next_to_pgetc,
  8986. g_parsefile->next_to_pgetc);
  8987. return (unsigned char)*g_parsefile->next_to_pgetc++;
  8988. }
  8989. #define pgetc_as_macro() \
  8990. (--g_parsefile->left_in_line >= 0 \
  8991. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  8992. : preadbuffer() \
  8993. )
  8994. static int
  8995. pgetc(void)
  8996. {
  8997. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8998. g_parsefile->left_in_line,
  8999. g_parsefile->next_to_pgetc,
  9000. g_parsefile->next_to_pgetc);
  9001. return pgetc_as_macro();
  9002. }
  9003. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  9004. # define pgetc_fast() pgetc()
  9005. #else
  9006. # define pgetc_fast() pgetc_as_macro()
  9007. #endif
  9008. #if ENABLE_ASH_ALIAS
  9009. static int
  9010. pgetc_without_PEOA(void)
  9011. {
  9012. int c;
  9013. do {
  9014. pgetc_debug("pgetc_fast at %d:%p'%s'",
  9015. g_parsefile->left_in_line,
  9016. g_parsefile->next_to_pgetc,
  9017. g_parsefile->next_to_pgetc);
  9018. c = pgetc_fast();
  9019. } while (c == PEOA);
  9020. return c;
  9021. }
  9022. #else
  9023. # define pgetc_without_PEOA() pgetc()
  9024. #endif
  9025. /*
  9026. * Read a line from the script.
  9027. */
  9028. static char *
  9029. pfgets(char *line, int len)
  9030. {
  9031. char *p = line;
  9032. int nleft = len;
  9033. int c;
  9034. while (--nleft > 0) {
  9035. c = pgetc_without_PEOA();
  9036. if (c == PEOF) {
  9037. if (p == line)
  9038. return NULL;
  9039. break;
  9040. }
  9041. *p++ = c;
  9042. if (c == '\n')
  9043. break;
  9044. }
  9045. *p = '\0';
  9046. return line;
  9047. }
  9048. /*
  9049. * Undo the last call to pgetc. Only one character may be pushed back.
  9050. * PEOF may be pushed back.
  9051. */
  9052. static void
  9053. pungetc(void)
  9054. {
  9055. g_parsefile->left_in_line++;
  9056. g_parsefile->next_to_pgetc--;
  9057. pgetc_debug("pushed back to %d:%p'%s'",
  9058. g_parsefile->left_in_line,
  9059. g_parsefile->next_to_pgetc,
  9060. g_parsefile->next_to_pgetc);
  9061. }
  9062. /*
  9063. * To handle the "." command, a stack of input files is used. Pushfile
  9064. * adds a new entry to the stack and popfile restores the previous level.
  9065. */
  9066. static void
  9067. pushfile(void)
  9068. {
  9069. struct parsefile *pf;
  9070. pf = ckzalloc(sizeof(*pf));
  9071. pf->prev = g_parsefile;
  9072. pf->pf_fd = -1;
  9073. /*pf->strpush = NULL; - ckzalloc did it */
  9074. /*pf->basestrpush.prev = NULL;*/
  9075. g_parsefile = pf;
  9076. }
  9077. static void
  9078. popfile(void)
  9079. {
  9080. struct parsefile *pf = g_parsefile;
  9081. INT_OFF;
  9082. if (pf->pf_fd >= 0)
  9083. close(pf->pf_fd);
  9084. free(pf->buf);
  9085. while (pf->strpush)
  9086. popstring();
  9087. g_parsefile = pf->prev;
  9088. free(pf);
  9089. INT_ON;
  9090. }
  9091. /*
  9092. * Return to top level.
  9093. */
  9094. static void
  9095. popallfiles(void)
  9096. {
  9097. while (g_parsefile != &basepf)
  9098. popfile();
  9099. }
  9100. /*
  9101. * Close the file(s) that the shell is reading commands from. Called
  9102. * after a fork is done.
  9103. */
  9104. static void
  9105. closescript(void)
  9106. {
  9107. popallfiles();
  9108. if (g_parsefile->pf_fd > 0) {
  9109. close(g_parsefile->pf_fd);
  9110. g_parsefile->pf_fd = 0;
  9111. }
  9112. }
  9113. /*
  9114. * Like setinputfile, but takes an open file descriptor. Call this with
  9115. * interrupts off.
  9116. */
  9117. static void
  9118. setinputfd(int fd, int push)
  9119. {
  9120. close_on_exec_on(fd);
  9121. if (push) {
  9122. pushfile();
  9123. g_parsefile->buf = NULL;
  9124. }
  9125. g_parsefile->pf_fd = fd;
  9126. if (g_parsefile->buf == NULL)
  9127. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9128. g_parsefile->left_in_buffer = 0;
  9129. g_parsefile->left_in_line = 0;
  9130. g_parsefile->linno = 1;
  9131. }
  9132. /*
  9133. * Set the input to take input from a file. If push is set, push the
  9134. * old input onto the stack first.
  9135. */
  9136. static int
  9137. setinputfile(const char *fname, int flags)
  9138. {
  9139. int fd;
  9140. int fd2;
  9141. INT_OFF;
  9142. fd = open(fname, O_RDONLY);
  9143. if (fd < 0) {
  9144. if (flags & INPUT_NOFILE_OK)
  9145. goto out;
  9146. ash_msg_and_raise_error("can't open '%s'", fname);
  9147. }
  9148. if (fd < 10) {
  9149. fd2 = copyfd(fd, 10);
  9150. close(fd);
  9151. if (fd2 < 0)
  9152. ash_msg_and_raise_error("out of file descriptors");
  9153. fd = fd2;
  9154. }
  9155. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9156. out:
  9157. INT_ON;
  9158. return fd;
  9159. }
  9160. /*
  9161. * Like setinputfile, but takes input from a string.
  9162. */
  9163. static void
  9164. setinputstring(char *string)
  9165. {
  9166. INT_OFF;
  9167. pushfile();
  9168. g_parsefile->next_to_pgetc = string;
  9169. g_parsefile->left_in_line = strlen(string);
  9170. g_parsefile->buf = NULL;
  9171. g_parsefile->linno = 1;
  9172. INT_ON;
  9173. }
  9174. /* ============ mail.c
  9175. *
  9176. * Routines to check for mail.
  9177. */
  9178. #if ENABLE_ASH_MAIL
  9179. /* Hash of mtimes of mailboxes */
  9180. static unsigned mailtime_hash;
  9181. /* Set if MAIL or MAILPATH is changed. */
  9182. static smallint mail_var_path_changed;
  9183. /*
  9184. * Print appropriate message(s) if mail has arrived.
  9185. * If mail_var_path_changed is set,
  9186. * then the value of MAIL has mail_var_path_changed,
  9187. * so we just update the values.
  9188. */
  9189. static void
  9190. chkmail(void)
  9191. {
  9192. const char *mpath;
  9193. char *p;
  9194. char *q;
  9195. unsigned new_hash;
  9196. struct stackmark smark;
  9197. struct stat statb;
  9198. setstackmark(&smark);
  9199. mpath = mpathset() ? mpathval() : mailval();
  9200. new_hash = 0;
  9201. for (;;) {
  9202. p = path_advance(&mpath, nullstr);
  9203. if (p == NULL)
  9204. break;
  9205. if (*p == '\0')
  9206. continue;
  9207. for (q = p; *q; q++)
  9208. continue;
  9209. #if DEBUG
  9210. if (q[-1] != '/')
  9211. abort();
  9212. #endif
  9213. q[-1] = '\0'; /* delete trailing '/' */
  9214. if (stat(p, &statb) < 0) {
  9215. continue;
  9216. }
  9217. /* Very simplistic "hash": just a sum of all mtimes */
  9218. new_hash += (unsigned)statb.st_mtime;
  9219. }
  9220. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9221. if (mailtime_hash != 0)
  9222. out2str("you have mail\n");
  9223. mailtime_hash = new_hash;
  9224. }
  9225. mail_var_path_changed = 0;
  9226. popstackmark(&smark);
  9227. }
  9228. static void FAST_FUNC
  9229. changemail(const char *val UNUSED_PARAM)
  9230. {
  9231. mail_var_path_changed = 1;
  9232. }
  9233. #endif /* ASH_MAIL */
  9234. /* ============ ??? */
  9235. /*
  9236. * Set the shell parameters.
  9237. */
  9238. static void
  9239. setparam(char **argv)
  9240. {
  9241. char **newparam;
  9242. char **ap;
  9243. int nparam;
  9244. for (nparam = 0; argv[nparam]; nparam++)
  9245. continue;
  9246. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9247. while (*argv) {
  9248. *ap++ = ckstrdup(*argv++);
  9249. }
  9250. *ap = NULL;
  9251. freeparam(&shellparam);
  9252. shellparam.malloced = 1;
  9253. shellparam.nparam = nparam;
  9254. shellparam.p = newparam;
  9255. #if ENABLE_ASH_GETOPTS
  9256. shellparam.optind = 1;
  9257. shellparam.optoff = -1;
  9258. #endif
  9259. }
  9260. /*
  9261. * Process shell options. The global variable argptr contains a pointer
  9262. * to the argument list; we advance it past the options.
  9263. *
  9264. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9265. * For a non-interactive shell, an error condition encountered
  9266. * by a special built-in ... shall cause the shell to write a diagnostic message
  9267. * to standard error and exit as shown in the following table:
  9268. * Error Special Built-In
  9269. * ...
  9270. * Utility syntax error (option or operand error) Shall exit
  9271. * ...
  9272. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9273. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9274. * and shell continues), and people rely on this behavior!
  9275. * Testcase:
  9276. * set -o barfoo 2>/dev/null
  9277. * echo $?
  9278. *
  9279. * Oh well. Let's mimic that.
  9280. */
  9281. static int
  9282. plus_minus_o(char *name, int val)
  9283. {
  9284. int i;
  9285. if (name) {
  9286. for (i = 0; i < NOPTS; i++) {
  9287. if (strcmp(name, optnames(i)) == 0) {
  9288. optlist[i] = val;
  9289. return 0;
  9290. }
  9291. }
  9292. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9293. return 1;
  9294. }
  9295. for (i = 0; i < NOPTS; i++) {
  9296. if (val) {
  9297. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9298. } else {
  9299. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9300. }
  9301. }
  9302. return 0;
  9303. }
  9304. static void
  9305. setoption(int flag, int val)
  9306. {
  9307. int i;
  9308. for (i = 0; i < NOPTS; i++) {
  9309. if (optletters(i) == flag) {
  9310. optlist[i] = val;
  9311. return;
  9312. }
  9313. }
  9314. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9315. /* NOTREACHED */
  9316. }
  9317. static int
  9318. options(int cmdline)
  9319. {
  9320. char *p;
  9321. int val;
  9322. int c;
  9323. if (cmdline)
  9324. minusc = NULL;
  9325. while ((p = *argptr) != NULL) {
  9326. c = *p++;
  9327. if (c != '-' && c != '+')
  9328. break;
  9329. argptr++;
  9330. val = 0; /* val = 0 if c == '+' */
  9331. if (c == '-') {
  9332. val = 1;
  9333. if (p[0] == '\0' || LONE_DASH(p)) {
  9334. if (!cmdline) {
  9335. /* "-" means turn off -x and -v */
  9336. if (p[0] == '\0')
  9337. xflag = vflag = 0;
  9338. /* "--" means reset params */
  9339. else if (*argptr == NULL)
  9340. setparam(argptr);
  9341. }
  9342. break; /* "-" or "--" terminates options */
  9343. }
  9344. }
  9345. /* first char was + or - */
  9346. while ((c = *p++) != '\0') {
  9347. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9348. if (c == 'c' && cmdline) {
  9349. minusc = p; /* command is after shell args */
  9350. } else if (c == 'o') {
  9351. if (plus_minus_o(*argptr, val)) {
  9352. /* it already printed err message */
  9353. return 1; /* error */
  9354. }
  9355. if (*argptr)
  9356. argptr++;
  9357. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9358. isloginsh = 1;
  9359. /* bash does not accept +-login, we also won't */
  9360. } else if (cmdline && val && (c == '-')) { /* long options */
  9361. if (strcmp(p, "login") == 0)
  9362. isloginsh = 1;
  9363. break;
  9364. } else {
  9365. setoption(c, val);
  9366. }
  9367. }
  9368. }
  9369. return 0;
  9370. }
  9371. /*
  9372. * The shift builtin command.
  9373. */
  9374. static int FAST_FUNC
  9375. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9376. {
  9377. int n;
  9378. char **ap1, **ap2;
  9379. n = 1;
  9380. if (argv[1])
  9381. n = number(argv[1]);
  9382. if (n > shellparam.nparam)
  9383. n = 0; /* bash compat, was = shellparam.nparam; */
  9384. INT_OFF;
  9385. shellparam.nparam -= n;
  9386. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9387. if (shellparam.malloced)
  9388. free(*ap1);
  9389. }
  9390. ap2 = shellparam.p;
  9391. while ((*ap2++ = *ap1++) != NULL)
  9392. continue;
  9393. #if ENABLE_ASH_GETOPTS
  9394. shellparam.optind = 1;
  9395. shellparam.optoff = -1;
  9396. #endif
  9397. INT_ON;
  9398. return 0;
  9399. }
  9400. /*
  9401. * POSIX requires that 'set' (but not export or readonly) output the
  9402. * variables in lexicographic order - by the locale's collating order (sigh).
  9403. * Maybe we could keep them in an ordered balanced binary tree
  9404. * instead of hashed lists.
  9405. * For now just roll 'em through qsort for printing...
  9406. */
  9407. static int
  9408. showvars(const char *sep_prefix, int on, int off)
  9409. {
  9410. const char *sep;
  9411. char **ep, **epend;
  9412. ep = listvars(on, off, &epend);
  9413. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9414. sep = *sep_prefix ? " " : sep_prefix;
  9415. for (; ep < epend; ep++) {
  9416. const char *p;
  9417. const char *q;
  9418. p = strchrnul(*ep, '=');
  9419. q = nullstr;
  9420. if (*p)
  9421. q = single_quote(++p);
  9422. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9423. }
  9424. return 0;
  9425. }
  9426. /*
  9427. * The set command builtin.
  9428. */
  9429. static int FAST_FUNC
  9430. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9431. {
  9432. int retval;
  9433. if (!argv[1])
  9434. return showvars(nullstr, 0, VUNSET);
  9435. INT_OFF;
  9436. retval = options(/*cmdline:*/ 0);
  9437. if (retval == 0) { /* if no parse error... */
  9438. optschanged();
  9439. if (*argptr != NULL) {
  9440. setparam(argptr);
  9441. }
  9442. }
  9443. INT_ON;
  9444. return retval;
  9445. }
  9446. #if ENABLE_ASH_RANDOM_SUPPORT
  9447. static void FAST_FUNC
  9448. change_random(const char *value)
  9449. {
  9450. uint32_t t;
  9451. if (value == NULL) {
  9452. /* "get", generate */
  9453. t = next_random(&random_gen);
  9454. /* set without recursion */
  9455. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9456. vrandom.flags &= ~VNOFUNC;
  9457. } else {
  9458. /* set/reset */
  9459. t = strtoul(value, NULL, 10);
  9460. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9461. }
  9462. }
  9463. #endif
  9464. #if ENABLE_ASH_GETOPTS
  9465. static int
  9466. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9467. {
  9468. char *p, *q;
  9469. char c = '?';
  9470. int done = 0;
  9471. int err = 0;
  9472. char sbuf[2];
  9473. char **optnext;
  9474. sbuf[1] = '\0';
  9475. if (*param_optind < 1)
  9476. return 1;
  9477. optnext = optfirst + *param_optind - 1;
  9478. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9479. p = NULL;
  9480. else
  9481. p = optnext[-1] + *optoff;
  9482. if (p == NULL || *p == '\0') {
  9483. /* Current word is done, advance */
  9484. p = *optnext;
  9485. if (p == NULL || *p != '-' || *++p == '\0') {
  9486. atend:
  9487. p = NULL;
  9488. done = 1;
  9489. goto out;
  9490. }
  9491. optnext++;
  9492. if (LONE_DASH(p)) /* check for "--" */
  9493. goto atend;
  9494. }
  9495. c = *p++;
  9496. for (q = optstr; *q != c;) {
  9497. if (*q == '\0') {
  9498. if (optstr[0] == ':') {
  9499. sbuf[0] = c;
  9500. /*sbuf[1] = '\0'; - already is */
  9501. err |= setvarsafe("OPTARG", sbuf, 0);
  9502. } else {
  9503. fprintf(stderr, "Illegal option -%c\n", c);
  9504. unsetvar("OPTARG");
  9505. }
  9506. c = '?';
  9507. goto out;
  9508. }
  9509. if (*++q == ':')
  9510. q++;
  9511. }
  9512. if (*++q == ':') {
  9513. if (*p == '\0' && (p = *optnext) == NULL) {
  9514. if (optstr[0] == ':') {
  9515. sbuf[0] = c;
  9516. /*sbuf[1] = '\0'; - already is */
  9517. err |= setvarsafe("OPTARG", sbuf, 0);
  9518. c = ':';
  9519. } else {
  9520. fprintf(stderr, "No arg for -%c option\n", c);
  9521. unsetvar("OPTARG");
  9522. c = '?';
  9523. }
  9524. goto out;
  9525. }
  9526. if (p == *optnext)
  9527. optnext++;
  9528. err |= setvarsafe("OPTARG", p, 0);
  9529. p = NULL;
  9530. } else
  9531. err |= setvarsafe("OPTARG", nullstr, 0);
  9532. out:
  9533. *optoff = p ? p - *(optnext - 1) : -1;
  9534. *param_optind = optnext - optfirst + 1;
  9535. err |= setvarsafe("OPTIND", itoa(*param_optind), VNOFUNC);
  9536. sbuf[0] = c;
  9537. /*sbuf[1] = '\0'; - already is */
  9538. err |= setvarsafe(optvar, sbuf, 0);
  9539. if (err) {
  9540. *param_optind = 1;
  9541. *optoff = -1;
  9542. flush_stdout_stderr();
  9543. raise_exception(EXERROR);
  9544. }
  9545. return done;
  9546. }
  9547. /*
  9548. * The getopts builtin. Shellparam.optnext points to the next argument
  9549. * to be processed. Shellparam.optptr points to the next character to
  9550. * be processed in the current argument. If shellparam.optnext is NULL,
  9551. * then it's the first time getopts has been called.
  9552. */
  9553. static int FAST_FUNC
  9554. getoptscmd(int argc, char **argv)
  9555. {
  9556. char **optbase;
  9557. if (argc < 3)
  9558. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9559. if (argc == 3) {
  9560. optbase = shellparam.p;
  9561. if (shellparam.optind > shellparam.nparam + 1) {
  9562. shellparam.optind = 1;
  9563. shellparam.optoff = -1;
  9564. }
  9565. } else {
  9566. optbase = &argv[3];
  9567. if (shellparam.optind > argc - 2) {
  9568. shellparam.optind = 1;
  9569. shellparam.optoff = -1;
  9570. }
  9571. }
  9572. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9573. &shellparam.optoff);
  9574. }
  9575. #endif /* ASH_GETOPTS */
  9576. /* ============ Shell parser */
  9577. struct heredoc {
  9578. struct heredoc *next; /* next here document in list */
  9579. union node *here; /* redirection node */
  9580. char *eofmark; /* string indicating end of input */
  9581. smallint striptabs; /* if set, strip leading tabs */
  9582. };
  9583. static smallint tokpushback; /* last token pushed back */
  9584. static smallint quoteflag; /* set if (part of) last token was quoted */
  9585. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9586. static struct heredoc *heredoclist; /* list of here documents to read */
  9587. static char *wordtext; /* text of last word returned by readtoken */
  9588. static struct nodelist *backquotelist;
  9589. static union node *redirnode;
  9590. static struct heredoc *heredoc;
  9591. static const char *
  9592. tokname(char *buf, int tok)
  9593. {
  9594. if (tok < TSEMI)
  9595. return tokname_array[tok] + 1;
  9596. sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  9597. return buf;
  9598. }
  9599. /* raise_error_unexpected_syntax:
  9600. * Called when an unexpected token is read during the parse. The argument
  9601. * is the token that is expected, or -1 if more than one type of token can
  9602. * occur at this point.
  9603. */
  9604. static void raise_error_unexpected_syntax(int) NORETURN;
  9605. static void
  9606. raise_error_unexpected_syntax(int token)
  9607. {
  9608. char msg[64];
  9609. char buf[16];
  9610. int l;
  9611. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  9612. if (token >= 0)
  9613. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  9614. raise_error_syntax(msg);
  9615. /* NOTREACHED */
  9616. }
  9617. #define EOFMARKLEN 79
  9618. /* parsing is heavily cross-recursive, need these forward decls */
  9619. static union node *andor(void);
  9620. static union node *pipeline(void);
  9621. static union node *parse_command(void);
  9622. static void parseheredoc(void);
  9623. static int peektoken(void);
  9624. static int readtoken(void);
  9625. static union node *
  9626. list(int nlflag)
  9627. {
  9628. union node *n1, *n2, *n3;
  9629. int tok;
  9630. n1 = NULL;
  9631. for (;;) {
  9632. switch (peektoken()) {
  9633. case TNL:
  9634. if (!(nlflag & 1))
  9635. break;
  9636. parseheredoc();
  9637. return n1;
  9638. case TEOF:
  9639. if (!n1 && (nlflag & 1))
  9640. n1 = NODE_EOF;
  9641. parseheredoc();
  9642. return n1;
  9643. }
  9644. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9645. if (nlflag == 2 && tokname_array[peektoken()][0])
  9646. return n1;
  9647. nlflag |= 2;
  9648. n2 = andor();
  9649. tok = readtoken();
  9650. if (tok == TBACKGND) {
  9651. if (n2->type == NPIPE) {
  9652. n2->npipe.pipe_backgnd = 1;
  9653. } else {
  9654. if (n2->type != NREDIR) {
  9655. n3 = stzalloc(sizeof(struct nredir));
  9656. n3->nredir.n = n2;
  9657. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9658. n2 = n3;
  9659. }
  9660. n2->type = NBACKGND;
  9661. }
  9662. }
  9663. if (n1 == NULL) {
  9664. n1 = n2;
  9665. } else {
  9666. n3 = stzalloc(sizeof(struct nbinary));
  9667. n3->type = NSEMI;
  9668. n3->nbinary.ch1 = n1;
  9669. n3->nbinary.ch2 = n2;
  9670. n1 = n3;
  9671. }
  9672. switch (tok) {
  9673. case TNL:
  9674. case TEOF:
  9675. tokpushback = 1;
  9676. /* fall through */
  9677. case TBACKGND:
  9678. case TSEMI:
  9679. break;
  9680. default:
  9681. if ((nlflag & 1))
  9682. raise_error_unexpected_syntax(-1);
  9683. tokpushback = 1;
  9684. return n1;
  9685. }
  9686. }
  9687. }
  9688. static union node *
  9689. andor(void)
  9690. {
  9691. union node *n1, *n2, *n3;
  9692. int t;
  9693. n1 = pipeline();
  9694. for (;;) {
  9695. t = readtoken();
  9696. if (t == TAND) {
  9697. t = NAND;
  9698. } else if (t == TOR) {
  9699. t = NOR;
  9700. } else {
  9701. tokpushback = 1;
  9702. return n1;
  9703. }
  9704. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9705. n2 = pipeline();
  9706. n3 = stzalloc(sizeof(struct nbinary));
  9707. n3->type = t;
  9708. n3->nbinary.ch1 = n1;
  9709. n3->nbinary.ch2 = n2;
  9710. n1 = n3;
  9711. }
  9712. }
  9713. static union node *
  9714. pipeline(void)
  9715. {
  9716. union node *n1, *n2, *pipenode;
  9717. struct nodelist *lp, *prev;
  9718. int negate;
  9719. negate = 0;
  9720. TRACE(("pipeline: entered\n"));
  9721. if (readtoken() == TNOT) {
  9722. negate = !negate;
  9723. checkkwd = CHKKWD | CHKALIAS;
  9724. } else
  9725. tokpushback = 1;
  9726. n1 = parse_command();
  9727. if (readtoken() == TPIPE) {
  9728. pipenode = stzalloc(sizeof(struct npipe));
  9729. pipenode->type = NPIPE;
  9730. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9731. lp = stzalloc(sizeof(struct nodelist));
  9732. pipenode->npipe.cmdlist = lp;
  9733. lp->n = n1;
  9734. do {
  9735. prev = lp;
  9736. lp = stzalloc(sizeof(struct nodelist));
  9737. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9738. lp->n = parse_command();
  9739. prev->next = lp;
  9740. } while (readtoken() == TPIPE);
  9741. lp->next = NULL;
  9742. n1 = pipenode;
  9743. }
  9744. tokpushback = 1;
  9745. if (negate) {
  9746. n2 = stzalloc(sizeof(struct nnot));
  9747. n2->type = NNOT;
  9748. n2->nnot.com = n1;
  9749. return n2;
  9750. }
  9751. return n1;
  9752. }
  9753. static union node *
  9754. makename(void)
  9755. {
  9756. union node *n;
  9757. n = stzalloc(sizeof(struct narg));
  9758. n->type = NARG;
  9759. /*n->narg.next = NULL; - stzalloc did it */
  9760. n->narg.text = wordtext;
  9761. n->narg.backquote = backquotelist;
  9762. return n;
  9763. }
  9764. static void
  9765. fixredir(union node *n, const char *text, int err)
  9766. {
  9767. int fd;
  9768. TRACE(("Fix redir %s %d\n", text, err));
  9769. if (!err)
  9770. n->ndup.vname = NULL;
  9771. fd = bb_strtou(text, NULL, 10);
  9772. if (!errno && fd >= 0)
  9773. n->ndup.dupfd = fd;
  9774. else if (LONE_DASH(text))
  9775. n->ndup.dupfd = -1;
  9776. else {
  9777. if (err)
  9778. raise_error_syntax("bad fd number");
  9779. n->ndup.vname = makename();
  9780. }
  9781. }
  9782. /*
  9783. * Returns true if the text contains nothing to expand (no dollar signs
  9784. * or backquotes).
  9785. */
  9786. static int
  9787. noexpand(const char *text)
  9788. {
  9789. unsigned char c;
  9790. while ((c = *text++) != '\0') {
  9791. if (c == CTLQUOTEMARK)
  9792. continue;
  9793. if (c == CTLESC)
  9794. text++;
  9795. else if (SIT(c, BASESYNTAX) == CCTL)
  9796. return 0;
  9797. }
  9798. return 1;
  9799. }
  9800. static void
  9801. parsefname(void)
  9802. {
  9803. union node *n = redirnode;
  9804. if (readtoken() != TWORD)
  9805. raise_error_unexpected_syntax(-1);
  9806. if (n->type == NHERE) {
  9807. struct heredoc *here = heredoc;
  9808. struct heredoc *p;
  9809. int i;
  9810. if (quoteflag == 0)
  9811. n->type = NXHERE;
  9812. TRACE(("Here document %d\n", n->type));
  9813. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9814. raise_error_syntax("illegal eof marker for << redirection");
  9815. rmescapes(wordtext, 0);
  9816. here->eofmark = wordtext;
  9817. here->next = NULL;
  9818. if (heredoclist == NULL)
  9819. heredoclist = here;
  9820. else {
  9821. for (p = heredoclist; p->next; p = p->next)
  9822. continue;
  9823. p->next = here;
  9824. }
  9825. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9826. fixredir(n, wordtext, 0);
  9827. } else {
  9828. n->nfile.fname = makename();
  9829. }
  9830. }
  9831. static union node *
  9832. simplecmd(void)
  9833. {
  9834. union node *args, **app;
  9835. union node *n = NULL;
  9836. union node *vars, **vpp;
  9837. union node **rpp, *redir;
  9838. int savecheckkwd;
  9839. #if ENABLE_ASH_BASH_COMPAT
  9840. smallint double_brackets_flag = 0;
  9841. #endif
  9842. args = NULL;
  9843. app = &args;
  9844. vars = NULL;
  9845. vpp = &vars;
  9846. redir = NULL;
  9847. rpp = &redir;
  9848. savecheckkwd = CHKALIAS;
  9849. for (;;) {
  9850. int t;
  9851. checkkwd = savecheckkwd;
  9852. t = readtoken();
  9853. switch (t) {
  9854. #if ENABLE_ASH_BASH_COMPAT
  9855. case TAND: /* "&&" */
  9856. case TOR: /* "||" */
  9857. if (!double_brackets_flag) {
  9858. tokpushback = 1;
  9859. goto out;
  9860. }
  9861. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9862. #endif
  9863. case TWORD:
  9864. n = stzalloc(sizeof(struct narg));
  9865. n->type = NARG;
  9866. /*n->narg.next = NULL; - stzalloc did it */
  9867. n->narg.text = wordtext;
  9868. #if ENABLE_ASH_BASH_COMPAT
  9869. if (strcmp("[[", wordtext) == 0)
  9870. double_brackets_flag = 1;
  9871. else if (strcmp("]]", wordtext) == 0)
  9872. double_brackets_flag = 0;
  9873. #endif
  9874. n->narg.backquote = backquotelist;
  9875. if (savecheckkwd && isassignment(wordtext)) {
  9876. *vpp = n;
  9877. vpp = &n->narg.next;
  9878. } else {
  9879. *app = n;
  9880. app = &n->narg.next;
  9881. savecheckkwd = 0;
  9882. }
  9883. break;
  9884. case TREDIR:
  9885. *rpp = n = redirnode;
  9886. rpp = &n->nfile.next;
  9887. parsefname(); /* read name of redirection file */
  9888. break;
  9889. case TLP:
  9890. if (args && app == &args->narg.next
  9891. && !vars && !redir
  9892. ) {
  9893. struct builtincmd *bcmd;
  9894. const char *name;
  9895. /* We have a function */
  9896. if (readtoken() != TRP)
  9897. raise_error_unexpected_syntax(TRP);
  9898. name = n->narg.text;
  9899. if (!goodname(name)
  9900. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9901. ) {
  9902. raise_error_syntax("bad function name");
  9903. }
  9904. n->type = NDEFUN;
  9905. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9906. n->narg.next = parse_command();
  9907. return n;
  9908. }
  9909. /* fall through */
  9910. default:
  9911. tokpushback = 1;
  9912. goto out;
  9913. }
  9914. }
  9915. out:
  9916. *app = NULL;
  9917. *vpp = NULL;
  9918. *rpp = NULL;
  9919. n = stzalloc(sizeof(struct ncmd));
  9920. n->type = NCMD;
  9921. n->ncmd.args = args;
  9922. n->ncmd.assign = vars;
  9923. n->ncmd.redirect = redir;
  9924. return n;
  9925. }
  9926. static union node *
  9927. parse_command(void)
  9928. {
  9929. union node *n1, *n2;
  9930. union node *ap, **app;
  9931. union node *cp, **cpp;
  9932. union node *redir, **rpp;
  9933. union node **rpp2;
  9934. int t;
  9935. redir = NULL;
  9936. rpp2 = &redir;
  9937. switch (readtoken()) {
  9938. default:
  9939. raise_error_unexpected_syntax(-1);
  9940. /* NOTREACHED */
  9941. case TIF:
  9942. n1 = stzalloc(sizeof(struct nif));
  9943. n1->type = NIF;
  9944. n1->nif.test = list(0);
  9945. if (readtoken() != TTHEN)
  9946. raise_error_unexpected_syntax(TTHEN);
  9947. n1->nif.ifpart = list(0);
  9948. n2 = n1;
  9949. while (readtoken() == TELIF) {
  9950. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9951. n2 = n2->nif.elsepart;
  9952. n2->type = NIF;
  9953. n2->nif.test = list(0);
  9954. if (readtoken() != TTHEN)
  9955. raise_error_unexpected_syntax(TTHEN);
  9956. n2->nif.ifpart = list(0);
  9957. }
  9958. if (lasttoken == TELSE)
  9959. n2->nif.elsepart = list(0);
  9960. else {
  9961. n2->nif.elsepart = NULL;
  9962. tokpushback = 1;
  9963. }
  9964. t = TFI;
  9965. break;
  9966. case TWHILE:
  9967. case TUNTIL: {
  9968. int got;
  9969. n1 = stzalloc(sizeof(struct nbinary));
  9970. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9971. n1->nbinary.ch1 = list(0);
  9972. got = readtoken();
  9973. if (got != TDO) {
  9974. TRACE(("expecting DO got '%s' %s\n", tokname_array[got] + 1,
  9975. got == TWORD ? wordtext : ""));
  9976. raise_error_unexpected_syntax(TDO);
  9977. }
  9978. n1->nbinary.ch2 = list(0);
  9979. t = TDONE;
  9980. break;
  9981. }
  9982. case TFOR:
  9983. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9984. raise_error_syntax("bad for loop variable");
  9985. n1 = stzalloc(sizeof(struct nfor));
  9986. n1->type = NFOR;
  9987. n1->nfor.var = wordtext;
  9988. checkkwd = CHKKWD | CHKALIAS;
  9989. if (readtoken() == TIN) {
  9990. app = &ap;
  9991. while (readtoken() == TWORD) {
  9992. n2 = stzalloc(sizeof(struct narg));
  9993. n2->type = NARG;
  9994. /*n2->narg.next = NULL; - stzalloc did it */
  9995. n2->narg.text = wordtext;
  9996. n2->narg.backquote = backquotelist;
  9997. *app = n2;
  9998. app = &n2->narg.next;
  9999. }
  10000. *app = NULL;
  10001. n1->nfor.args = ap;
  10002. if (lasttoken != TNL && lasttoken != TSEMI)
  10003. raise_error_unexpected_syntax(-1);
  10004. } else {
  10005. n2 = stzalloc(sizeof(struct narg));
  10006. n2->type = NARG;
  10007. /*n2->narg.next = NULL; - stzalloc did it */
  10008. n2->narg.text = (char *)dolatstr;
  10009. /*n2->narg.backquote = NULL;*/
  10010. n1->nfor.args = n2;
  10011. /*
  10012. * Newline or semicolon here is optional (but note
  10013. * that the original Bourne shell only allowed NL).
  10014. */
  10015. if (lasttoken != TNL && lasttoken != TSEMI)
  10016. tokpushback = 1;
  10017. }
  10018. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10019. if (readtoken() != TDO)
  10020. raise_error_unexpected_syntax(TDO);
  10021. n1->nfor.body = list(0);
  10022. t = TDONE;
  10023. break;
  10024. case TCASE:
  10025. n1 = stzalloc(sizeof(struct ncase));
  10026. n1->type = NCASE;
  10027. if (readtoken() != TWORD)
  10028. raise_error_unexpected_syntax(TWORD);
  10029. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10030. n2->type = NARG;
  10031. /*n2->narg.next = NULL; - stzalloc did it */
  10032. n2->narg.text = wordtext;
  10033. n2->narg.backquote = backquotelist;
  10034. do {
  10035. checkkwd = CHKKWD | CHKALIAS;
  10036. } while (readtoken() == TNL);
  10037. if (lasttoken != TIN)
  10038. raise_error_unexpected_syntax(TIN);
  10039. cpp = &n1->ncase.cases;
  10040. next_case:
  10041. checkkwd = CHKNL | CHKKWD;
  10042. t = readtoken();
  10043. while (t != TESAC) {
  10044. if (lasttoken == TLP)
  10045. readtoken();
  10046. *cpp = cp = stzalloc(sizeof(struct nclist));
  10047. cp->type = NCLIST;
  10048. app = &cp->nclist.pattern;
  10049. for (;;) {
  10050. *app = ap = stzalloc(sizeof(struct narg));
  10051. ap->type = NARG;
  10052. /*ap->narg.next = NULL; - stzalloc did it */
  10053. ap->narg.text = wordtext;
  10054. ap->narg.backquote = backquotelist;
  10055. if (readtoken() != TPIPE)
  10056. break;
  10057. app = &ap->narg.next;
  10058. readtoken();
  10059. }
  10060. //ap->narg.next = NULL;
  10061. if (lasttoken != TRP)
  10062. raise_error_unexpected_syntax(TRP);
  10063. cp->nclist.body = list(2);
  10064. cpp = &cp->nclist.next;
  10065. checkkwd = CHKNL | CHKKWD;
  10066. t = readtoken();
  10067. if (t != TESAC) {
  10068. if (t != TENDCASE)
  10069. raise_error_unexpected_syntax(TENDCASE);
  10070. goto next_case;
  10071. }
  10072. }
  10073. *cpp = NULL;
  10074. goto redir;
  10075. case TLP:
  10076. n1 = stzalloc(sizeof(struct nredir));
  10077. n1->type = NSUBSHELL;
  10078. n1->nredir.n = list(0);
  10079. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10080. t = TRP;
  10081. break;
  10082. case TBEGIN:
  10083. n1 = list(0);
  10084. t = TEND;
  10085. break;
  10086. case TWORD:
  10087. case TREDIR:
  10088. tokpushback = 1;
  10089. return simplecmd();
  10090. }
  10091. if (readtoken() != t)
  10092. raise_error_unexpected_syntax(t);
  10093. redir:
  10094. /* Now check for redirection which may follow command */
  10095. checkkwd = CHKKWD | CHKALIAS;
  10096. rpp = rpp2;
  10097. while (readtoken() == TREDIR) {
  10098. *rpp = n2 = redirnode;
  10099. rpp = &n2->nfile.next;
  10100. parsefname();
  10101. }
  10102. tokpushback = 1;
  10103. *rpp = NULL;
  10104. if (redir) {
  10105. if (n1->type != NSUBSHELL) {
  10106. n2 = stzalloc(sizeof(struct nredir));
  10107. n2->type = NREDIR;
  10108. n2->nredir.n = n1;
  10109. n1 = n2;
  10110. }
  10111. n1->nredir.redirect = redir;
  10112. }
  10113. return n1;
  10114. }
  10115. #if ENABLE_ASH_BASH_COMPAT
  10116. static int decode_dollar_squote(void)
  10117. {
  10118. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10119. int c, cnt;
  10120. char *p;
  10121. char buf[4];
  10122. c = pgetc();
  10123. p = strchr(C_escapes, c);
  10124. if (p) {
  10125. buf[0] = c;
  10126. p = buf;
  10127. cnt = 3;
  10128. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10129. do {
  10130. c = pgetc();
  10131. *++p = c;
  10132. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10133. pungetc();
  10134. } else if (c == 'x') { /* \xHH */
  10135. do {
  10136. c = pgetc();
  10137. *++p = c;
  10138. } while (isxdigit(c) && --cnt);
  10139. pungetc();
  10140. if (cnt == 3) { /* \x but next char is "bad" */
  10141. c = 'x';
  10142. goto unrecognized;
  10143. }
  10144. } else { /* simple seq like \\ or \t */
  10145. p++;
  10146. }
  10147. *p = '\0';
  10148. p = buf;
  10149. c = bb_process_escape_sequence((void*)&p);
  10150. } else { /* unrecognized "\z": print both chars unless ' or " */
  10151. if (c != '\'' && c != '"') {
  10152. unrecognized:
  10153. c |= 0x100; /* "please encode \, then me" */
  10154. }
  10155. }
  10156. return c;
  10157. }
  10158. #endif
  10159. /*
  10160. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10161. * is not NULL, read a here document. In the latter case, eofmark is the
  10162. * word which marks the end of the document and striptabs is true if
  10163. * leading tabs should be stripped from the document. The argument c
  10164. * is the first character of the input token or document.
  10165. *
  10166. * Because C does not have internal subroutines, I have simulated them
  10167. * using goto's to implement the subroutine linkage. The following macros
  10168. * will run code that appears at the end of readtoken1.
  10169. */
  10170. #define CHECKEND() {goto checkend; checkend_return:;}
  10171. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10172. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10173. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10174. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10175. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10176. static int
  10177. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10178. {
  10179. /* NB: syntax parameter fits into smallint */
  10180. /* c parameter is an unsigned char or PEOF or PEOA */
  10181. char *out;
  10182. int len;
  10183. char line[EOFMARKLEN + 1];
  10184. struct nodelist *bqlist;
  10185. smallint quotef;
  10186. smallint dblquote;
  10187. smallint oldstyle;
  10188. smallint prevsyntax; /* syntax before arithmetic */
  10189. #if ENABLE_ASH_EXPAND_PRMT
  10190. smallint pssyntax; /* we are expanding a prompt string */
  10191. #endif
  10192. int varnest; /* levels of variables expansion */
  10193. int arinest; /* levels of arithmetic expansion */
  10194. int parenlevel; /* levels of parens in arithmetic */
  10195. int dqvarnest; /* levels of variables expansion within double quotes */
  10196. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  10197. startlinno = g_parsefile->linno;
  10198. bqlist = NULL;
  10199. quotef = 0;
  10200. prevsyntax = 0;
  10201. #if ENABLE_ASH_EXPAND_PRMT
  10202. pssyntax = (syntax == PSSYNTAX);
  10203. if (pssyntax)
  10204. syntax = DQSYNTAX;
  10205. #endif
  10206. dblquote = (syntax == DQSYNTAX);
  10207. varnest = 0;
  10208. arinest = 0;
  10209. parenlevel = 0;
  10210. dqvarnest = 0;
  10211. STARTSTACKSTR(out);
  10212. loop:
  10213. /* For each line, until end of word */
  10214. CHECKEND(); /* set c to PEOF if at end of here document */
  10215. for (;;) { /* until end of line or end of word */
  10216. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10217. switch (SIT(c, syntax)) {
  10218. case CNL: /* '\n' */
  10219. if (syntax == BASESYNTAX)
  10220. goto endword; /* exit outer loop */
  10221. USTPUTC(c, out);
  10222. g_parsefile->linno++;
  10223. setprompt_if(doprompt, 2);
  10224. c = pgetc();
  10225. goto loop; /* continue outer loop */
  10226. case CWORD:
  10227. USTPUTC(c, out);
  10228. break;
  10229. case CCTL:
  10230. if (eofmark == NULL || dblquote)
  10231. USTPUTC(CTLESC, out);
  10232. #if ENABLE_ASH_BASH_COMPAT
  10233. if (c == '\\' && bash_dollar_squote) {
  10234. c = decode_dollar_squote();
  10235. if (c & 0x100) {
  10236. USTPUTC('\\', out);
  10237. c = (unsigned char)c;
  10238. }
  10239. }
  10240. #endif
  10241. USTPUTC(c, out);
  10242. break;
  10243. case CBACK: /* backslash */
  10244. c = pgetc_without_PEOA();
  10245. if (c == PEOF) {
  10246. USTPUTC(CTLESC, out);
  10247. USTPUTC('\\', out);
  10248. pungetc();
  10249. } else if (c == '\n') {
  10250. setprompt_if(doprompt, 2);
  10251. } else {
  10252. #if ENABLE_ASH_EXPAND_PRMT
  10253. if (c == '$' && pssyntax) {
  10254. USTPUTC(CTLESC, out);
  10255. USTPUTC('\\', out);
  10256. }
  10257. #endif
  10258. /* Backslash is retained if we are in "str" and next char isn't special */
  10259. if (dblquote
  10260. && c != '\\'
  10261. && c != '`'
  10262. && c != '$'
  10263. && (c != '"' || eofmark != NULL)
  10264. ) {
  10265. USTPUTC('\\', out);
  10266. }
  10267. USTPUTC(CTLESC, out);
  10268. USTPUTC(c, out);
  10269. quotef = 1;
  10270. }
  10271. break;
  10272. case CSQUOTE:
  10273. syntax = SQSYNTAX;
  10274. quotemark:
  10275. if (eofmark == NULL) {
  10276. USTPUTC(CTLQUOTEMARK, out);
  10277. }
  10278. break;
  10279. case CDQUOTE:
  10280. syntax = DQSYNTAX;
  10281. dblquote = 1;
  10282. goto quotemark;
  10283. case CENDQUOTE:
  10284. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10285. if (eofmark != NULL && varnest == 0) {
  10286. USTPUTC(c, out);
  10287. } else {
  10288. if (dqvarnest == 0) {
  10289. syntax = BASESYNTAX;
  10290. dblquote = 0;
  10291. }
  10292. quotef = 1;
  10293. goto quotemark;
  10294. }
  10295. break;
  10296. case CVAR: /* '$' */
  10297. PARSESUB(); /* parse substitution */
  10298. break;
  10299. case CENDVAR: /* '}' */
  10300. if (varnest > 0) {
  10301. varnest--;
  10302. if (dqvarnest > 0) {
  10303. dqvarnest--;
  10304. }
  10305. c = CTLENDVAR;
  10306. }
  10307. USTPUTC(c, out);
  10308. break;
  10309. #if ENABLE_SH_MATH_SUPPORT
  10310. case CLP: /* '(' in arithmetic */
  10311. parenlevel++;
  10312. USTPUTC(c, out);
  10313. break;
  10314. case CRP: /* ')' in arithmetic */
  10315. if (parenlevel > 0) {
  10316. parenlevel--;
  10317. } else {
  10318. if (pgetc() == ')') {
  10319. c = CTLENDARI;
  10320. if (--arinest == 0) {
  10321. syntax = prevsyntax;
  10322. }
  10323. } else {
  10324. /*
  10325. * unbalanced parens
  10326. * (don't 2nd guess - no error)
  10327. */
  10328. pungetc();
  10329. }
  10330. }
  10331. USTPUTC(c, out);
  10332. break;
  10333. #endif
  10334. case CBQUOTE: /* '`' */
  10335. PARSEBACKQOLD();
  10336. break;
  10337. case CENDFILE:
  10338. goto endword; /* exit outer loop */
  10339. case CIGN:
  10340. break;
  10341. default:
  10342. if (varnest == 0) {
  10343. #if ENABLE_ASH_BASH_COMPAT
  10344. if (c == '&') {
  10345. if (pgetc() == '>')
  10346. c = 0x100 + '>'; /* flag &> */
  10347. pungetc();
  10348. }
  10349. #endif
  10350. goto endword; /* exit outer loop */
  10351. }
  10352. IF_ASH_ALIAS(if (c != PEOA))
  10353. USTPUTC(c, out);
  10354. }
  10355. c = pgetc_fast();
  10356. } /* for (;;) */
  10357. endword:
  10358. #if ENABLE_SH_MATH_SUPPORT
  10359. if (syntax == ARISYNTAX)
  10360. raise_error_syntax("missing '))'");
  10361. #endif
  10362. if (syntax != BASESYNTAX && eofmark == NULL)
  10363. raise_error_syntax("unterminated quoted string");
  10364. if (varnest != 0) {
  10365. startlinno = g_parsefile->linno;
  10366. /* { */
  10367. raise_error_syntax("missing '}'");
  10368. }
  10369. USTPUTC('\0', out);
  10370. len = out - (char *)stackblock();
  10371. out = stackblock();
  10372. if (eofmark == NULL) {
  10373. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10374. && quotef == 0
  10375. ) {
  10376. if (isdigit_str9(out)) {
  10377. PARSEREDIR(); /* passed as params: out, c */
  10378. lasttoken = TREDIR;
  10379. return lasttoken;
  10380. }
  10381. /* else: non-number X seen, interpret it
  10382. * as "NNNX>file" = "NNNX >file" */
  10383. }
  10384. pungetc();
  10385. }
  10386. quoteflag = quotef;
  10387. backquotelist = bqlist;
  10388. grabstackblock(len);
  10389. wordtext = out;
  10390. lasttoken = TWORD;
  10391. return lasttoken;
  10392. /* end of readtoken routine */
  10393. /*
  10394. * Check to see whether we are at the end of the here document. When this
  10395. * is called, c is set to the first character of the next input line. If
  10396. * we are at the end of the here document, this routine sets the c to PEOF.
  10397. */
  10398. checkend: {
  10399. if (eofmark) {
  10400. #if ENABLE_ASH_ALIAS
  10401. if (c == PEOA)
  10402. c = pgetc_without_PEOA();
  10403. #endif
  10404. if (striptabs) {
  10405. while (c == '\t') {
  10406. c = pgetc_without_PEOA();
  10407. }
  10408. }
  10409. if (c == *eofmark) {
  10410. if (pfgets(line, sizeof(line)) != NULL) {
  10411. char *p, *q;
  10412. p = line;
  10413. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10414. continue;
  10415. if (*p == '\n' && *q == '\0') {
  10416. c = PEOF;
  10417. g_parsefile->linno++;
  10418. needprompt = doprompt;
  10419. } else {
  10420. pushstring(line, NULL);
  10421. }
  10422. }
  10423. }
  10424. }
  10425. goto checkend_return;
  10426. }
  10427. /*
  10428. * Parse a redirection operator. The variable "out" points to a string
  10429. * specifying the fd to be redirected. The variable "c" contains the
  10430. * first character of the redirection operator.
  10431. */
  10432. parseredir: {
  10433. /* out is already checked to be a valid number or "" */
  10434. int fd = (*out == '\0' ? -1 : atoi(out));
  10435. union node *np;
  10436. np = stzalloc(sizeof(struct nfile));
  10437. if (c == '>') {
  10438. np->nfile.fd = 1;
  10439. c = pgetc();
  10440. if (c == '>')
  10441. np->type = NAPPEND;
  10442. else if (c == '|')
  10443. np->type = NCLOBBER;
  10444. else if (c == '&')
  10445. np->type = NTOFD;
  10446. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10447. else {
  10448. np->type = NTO;
  10449. pungetc();
  10450. }
  10451. }
  10452. #if ENABLE_ASH_BASH_COMPAT
  10453. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10454. np->nfile.fd = 1;
  10455. pgetc(); /* this is '>', no need to check */
  10456. np->type = NTO2;
  10457. }
  10458. #endif
  10459. else { /* c == '<' */
  10460. /*np->nfile.fd = 0; - stzalloc did it */
  10461. c = pgetc();
  10462. switch (c) {
  10463. case '<':
  10464. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10465. np = stzalloc(sizeof(struct nhere));
  10466. /*np->nfile.fd = 0; - stzalloc did it */
  10467. }
  10468. np->type = NHERE;
  10469. heredoc = stzalloc(sizeof(struct heredoc));
  10470. heredoc->here = np;
  10471. c = pgetc();
  10472. if (c == '-') {
  10473. heredoc->striptabs = 1;
  10474. } else {
  10475. /*heredoc->striptabs = 0; - stzalloc did it */
  10476. pungetc();
  10477. }
  10478. break;
  10479. case '&':
  10480. np->type = NFROMFD;
  10481. break;
  10482. case '>':
  10483. np->type = NFROMTO;
  10484. break;
  10485. default:
  10486. np->type = NFROM;
  10487. pungetc();
  10488. break;
  10489. }
  10490. }
  10491. if (fd >= 0)
  10492. np->nfile.fd = fd;
  10493. redirnode = np;
  10494. goto parseredir_return;
  10495. }
  10496. /*
  10497. * Parse a substitution. At this point, we have read the dollar sign
  10498. * and nothing else.
  10499. */
  10500. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10501. * (assuming ascii char codes, as the original implementation did) */
  10502. #define is_special(c) \
  10503. (((unsigned)(c) - 33 < 32) \
  10504. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10505. parsesub: {
  10506. unsigned char subtype;
  10507. int typeloc;
  10508. int flags;
  10509. c = pgetc();
  10510. if (c > 255 /* PEOA or PEOF */
  10511. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10512. ) {
  10513. #if ENABLE_ASH_BASH_COMPAT
  10514. if (c == '\'')
  10515. bash_dollar_squote = 1;
  10516. else
  10517. #endif
  10518. USTPUTC('$', out);
  10519. pungetc();
  10520. } else if (c == '(') {
  10521. /* $(command) or $((arith)) */
  10522. if (pgetc() == '(') {
  10523. #if ENABLE_SH_MATH_SUPPORT
  10524. PARSEARITH();
  10525. #else
  10526. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10527. #endif
  10528. } else {
  10529. pungetc();
  10530. PARSEBACKQNEW();
  10531. }
  10532. } else {
  10533. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  10534. USTPUTC(CTLVAR, out);
  10535. typeloc = out - (char *)stackblock();
  10536. USTPUTC(VSNORMAL, out);
  10537. subtype = VSNORMAL;
  10538. if (c == '{') {
  10539. c = pgetc();
  10540. if (c == '#') {
  10541. c = pgetc();
  10542. if (c == '}')
  10543. c = '#'; /* ${#} - same as $# */
  10544. else
  10545. subtype = VSLENGTH; /* ${#VAR} */
  10546. } else {
  10547. subtype = 0;
  10548. }
  10549. }
  10550. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10551. /* $[{[#]]NAME[}] */
  10552. do {
  10553. STPUTC(c, out);
  10554. c = pgetc();
  10555. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10556. } else if (isdigit(c)) {
  10557. /* $[{[#]]NUM[}] */
  10558. do {
  10559. STPUTC(c, out);
  10560. c = pgetc();
  10561. } while (isdigit(c));
  10562. } else if (is_special(c)) {
  10563. /* $[{[#]]<specialchar>[}] */
  10564. USTPUTC(c, out);
  10565. c = pgetc();
  10566. } else {
  10567. badsub:
  10568. raise_error_syntax("bad substitution");
  10569. }
  10570. if (c != '}' && subtype == VSLENGTH) {
  10571. /* ${#VAR didn't end with } */
  10572. goto badsub;
  10573. }
  10574. STPUTC('=', out);
  10575. flags = 0;
  10576. if (subtype == 0) {
  10577. /* ${VAR...} but not $VAR or ${#VAR} */
  10578. /* c == first char after VAR */
  10579. switch (c) {
  10580. case ':':
  10581. c = pgetc();
  10582. #if ENABLE_ASH_BASH_COMPAT
  10583. if (c == ':' || c == '$' || isdigit(c)) {
  10584. //TODO: support more general format ${v:EXPR:EXPR},
  10585. // where EXPR follows $(()) rules
  10586. subtype = VSSUBSTR;
  10587. pungetc();
  10588. break; /* "goto do_pungetc" is bigger (!) */
  10589. }
  10590. #endif
  10591. flags = VSNUL;
  10592. /*FALLTHROUGH*/
  10593. default: {
  10594. static const char types[] ALIGN1 = "}-+?=";
  10595. const char *p = strchr(types, c);
  10596. if (p == NULL)
  10597. goto badsub;
  10598. subtype = p - types + VSNORMAL;
  10599. break;
  10600. }
  10601. case '%':
  10602. case '#': {
  10603. int cc = c;
  10604. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  10605. c = pgetc();
  10606. if (c != cc)
  10607. goto do_pungetc;
  10608. subtype++;
  10609. break;
  10610. }
  10611. #if ENABLE_ASH_BASH_COMPAT
  10612. case '/':
  10613. /* ${v/[/]pattern/repl} */
  10614. //TODO: encode pattern and repl separately.
  10615. // Currently ${v/$var_with_slash/repl} is horribly broken
  10616. subtype = VSREPLACE;
  10617. c = pgetc();
  10618. if (c != '/')
  10619. goto do_pungetc;
  10620. subtype++; /* VSREPLACEALL */
  10621. break;
  10622. #endif
  10623. }
  10624. } else {
  10625. do_pungetc:
  10626. pungetc();
  10627. }
  10628. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10629. if (subtype != VSNORMAL) {
  10630. varnest++;
  10631. if (dblquote) {
  10632. dqvarnest++;
  10633. }
  10634. }
  10635. }
  10636. goto parsesub_return;
  10637. }
  10638. /*
  10639. * Called to parse command substitutions. Newstyle is set if the command
  10640. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10641. * list of commands (passed by reference), and savelen is the number of
  10642. * characters on the top of the stack which must be preserved.
  10643. */
  10644. parsebackq: {
  10645. struct nodelist **nlpp;
  10646. union node *n;
  10647. char *str;
  10648. size_t savelen;
  10649. smallint saveprompt = 0;
  10650. str = NULL;
  10651. savelen = out - (char *)stackblock();
  10652. if (savelen > 0) {
  10653. str = alloca(savelen);
  10654. memcpy(str, stackblock(), savelen);
  10655. }
  10656. if (oldstyle) {
  10657. /* We must read until the closing backquote, giving special
  10658. * treatment to some slashes, and then push the string and
  10659. * reread it as input, interpreting it normally.
  10660. */
  10661. char *pout;
  10662. size_t psavelen;
  10663. char *pstr;
  10664. STARTSTACKSTR(pout);
  10665. for (;;) {
  10666. int pc;
  10667. setprompt_if(needprompt, 2);
  10668. pc = pgetc();
  10669. switch (pc) {
  10670. case '`':
  10671. goto done;
  10672. case '\\':
  10673. pc = pgetc();
  10674. if (pc == '\n') {
  10675. g_parsefile->linno++;
  10676. setprompt_if(doprompt, 2);
  10677. /*
  10678. * If eating a newline, avoid putting
  10679. * the newline into the new character
  10680. * stream (via the STPUTC after the
  10681. * switch).
  10682. */
  10683. continue;
  10684. }
  10685. if (pc != '\\' && pc != '`' && pc != '$'
  10686. && (!dblquote || pc != '"')
  10687. ) {
  10688. STPUTC('\\', pout);
  10689. }
  10690. if (pc <= 255 /* not PEOA or PEOF */) {
  10691. break;
  10692. }
  10693. /* fall through */
  10694. case PEOF:
  10695. IF_ASH_ALIAS(case PEOA:)
  10696. startlinno = g_parsefile->linno;
  10697. raise_error_syntax("EOF in backquote substitution");
  10698. case '\n':
  10699. g_parsefile->linno++;
  10700. needprompt = doprompt;
  10701. break;
  10702. default:
  10703. break;
  10704. }
  10705. STPUTC(pc, pout);
  10706. }
  10707. done:
  10708. STPUTC('\0', pout);
  10709. psavelen = pout - (char *)stackblock();
  10710. if (psavelen > 0) {
  10711. pstr = grabstackstr(pout);
  10712. setinputstring(pstr);
  10713. }
  10714. }
  10715. nlpp = &bqlist;
  10716. while (*nlpp)
  10717. nlpp = &(*nlpp)->next;
  10718. *nlpp = stzalloc(sizeof(**nlpp));
  10719. /* (*nlpp)->next = NULL; - stzalloc did it */
  10720. if (oldstyle) {
  10721. saveprompt = doprompt;
  10722. doprompt = 0;
  10723. }
  10724. n = list(2);
  10725. if (oldstyle)
  10726. doprompt = saveprompt;
  10727. else if (readtoken() != TRP)
  10728. raise_error_unexpected_syntax(TRP);
  10729. (*nlpp)->n = n;
  10730. if (oldstyle) {
  10731. /*
  10732. * Start reading from old file again, ignoring any pushed back
  10733. * tokens left from the backquote parsing
  10734. */
  10735. popfile();
  10736. tokpushback = 0;
  10737. }
  10738. while (stackblocksize() <= savelen)
  10739. growstackblock();
  10740. STARTSTACKSTR(out);
  10741. if (str) {
  10742. memcpy(out, str, savelen);
  10743. STADJUST(savelen, out);
  10744. }
  10745. USTPUTC(CTLBACKQ, out);
  10746. if (oldstyle)
  10747. goto parsebackq_oldreturn;
  10748. goto parsebackq_newreturn;
  10749. }
  10750. #if ENABLE_SH_MATH_SUPPORT
  10751. /*
  10752. * Parse an arithmetic expansion (indicate start of one and set state)
  10753. */
  10754. parsearith: {
  10755. if (++arinest == 1) {
  10756. prevsyntax = syntax;
  10757. syntax = ARISYNTAX;
  10758. }
  10759. USTPUTC(CTLARI, out);
  10760. goto parsearith_return;
  10761. }
  10762. #endif
  10763. } /* end of readtoken */
  10764. /*
  10765. * Read the next input token.
  10766. * If the token is a word, we set backquotelist to the list of cmds in
  10767. * backquotes. We set quoteflag to true if any part of the word was
  10768. * quoted.
  10769. * If the token is TREDIR, then we set redirnode to a structure containing
  10770. * the redirection.
  10771. * In all cases, the variable startlinno is set to the number of the line
  10772. * on which the token starts.
  10773. *
  10774. * [Change comment: here documents and internal procedures]
  10775. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10776. * word parsing code into a separate routine. In this case, readtoken
  10777. * doesn't need to have any internal procedures, but parseword does.
  10778. * We could also make parseoperator in essence the main routine, and
  10779. * have parseword (readtoken1?) handle both words and redirection.]
  10780. */
  10781. #define NEW_xxreadtoken
  10782. #ifdef NEW_xxreadtoken
  10783. /* singles must be first! */
  10784. static const char xxreadtoken_chars[7] ALIGN1 = {
  10785. '\n', '(', ')', /* singles */
  10786. '&', '|', ';', /* doubles */
  10787. 0
  10788. };
  10789. #define xxreadtoken_singles 3
  10790. #define xxreadtoken_doubles 3
  10791. static const char xxreadtoken_tokens[] ALIGN1 = {
  10792. TNL, TLP, TRP, /* only single occurrence allowed */
  10793. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10794. TEOF, /* corresponds to trailing nul */
  10795. TAND, TOR, TENDCASE /* if double occurrence */
  10796. };
  10797. static int
  10798. xxreadtoken(void)
  10799. {
  10800. int c;
  10801. if (tokpushback) {
  10802. tokpushback = 0;
  10803. return lasttoken;
  10804. }
  10805. setprompt_if(needprompt, 2);
  10806. startlinno = g_parsefile->linno;
  10807. for (;;) { /* until token or start of word found */
  10808. c = pgetc_fast();
  10809. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10810. continue;
  10811. if (c == '#') {
  10812. while ((c = pgetc()) != '\n' && c != PEOF)
  10813. continue;
  10814. pungetc();
  10815. } else if (c == '\\') {
  10816. if (pgetc() != '\n') {
  10817. pungetc();
  10818. break; /* return readtoken1(...) */
  10819. }
  10820. startlinno = ++g_parsefile->linno;
  10821. setprompt_if(doprompt, 2);
  10822. } else {
  10823. const char *p;
  10824. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10825. if (c != PEOF) {
  10826. if (c == '\n') {
  10827. g_parsefile->linno++;
  10828. needprompt = doprompt;
  10829. }
  10830. p = strchr(xxreadtoken_chars, c);
  10831. if (p == NULL)
  10832. break; /* return readtoken1(...) */
  10833. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10834. int cc = pgetc();
  10835. if (cc == c) { /* double occurrence? */
  10836. p += xxreadtoken_doubles + 1;
  10837. } else {
  10838. pungetc();
  10839. #if ENABLE_ASH_BASH_COMPAT
  10840. if (c == '&' && cc == '>') /* &> */
  10841. break; /* return readtoken1(...) */
  10842. #endif
  10843. }
  10844. }
  10845. }
  10846. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10847. return lasttoken;
  10848. }
  10849. } /* for (;;) */
  10850. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10851. }
  10852. #else /* old xxreadtoken */
  10853. #define RETURN(token) return lasttoken = token
  10854. static int
  10855. xxreadtoken(void)
  10856. {
  10857. int c;
  10858. if (tokpushback) {
  10859. tokpushback = 0;
  10860. return lasttoken;
  10861. }
  10862. setprompt_if(needprompt, 2);
  10863. startlinno = g_parsefile->linno;
  10864. for (;;) { /* until token or start of word found */
  10865. c = pgetc_fast();
  10866. switch (c) {
  10867. case ' ': case '\t':
  10868. IF_ASH_ALIAS(case PEOA:)
  10869. continue;
  10870. case '#':
  10871. while ((c = pgetc()) != '\n' && c != PEOF)
  10872. continue;
  10873. pungetc();
  10874. continue;
  10875. case '\\':
  10876. if (pgetc() == '\n') {
  10877. startlinno = ++g_parsefile->linno;
  10878. setprompt_if(doprompt, 2);
  10879. continue;
  10880. }
  10881. pungetc();
  10882. goto breakloop;
  10883. case '\n':
  10884. g_parsefile->linno++;
  10885. needprompt = doprompt;
  10886. RETURN(TNL);
  10887. case PEOF:
  10888. RETURN(TEOF);
  10889. case '&':
  10890. if (pgetc() == '&')
  10891. RETURN(TAND);
  10892. pungetc();
  10893. RETURN(TBACKGND);
  10894. case '|':
  10895. if (pgetc() == '|')
  10896. RETURN(TOR);
  10897. pungetc();
  10898. RETURN(TPIPE);
  10899. case ';':
  10900. if (pgetc() == ';')
  10901. RETURN(TENDCASE);
  10902. pungetc();
  10903. RETURN(TSEMI);
  10904. case '(':
  10905. RETURN(TLP);
  10906. case ')':
  10907. RETURN(TRP);
  10908. default:
  10909. goto breakloop;
  10910. }
  10911. }
  10912. breakloop:
  10913. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10914. #undef RETURN
  10915. }
  10916. #endif /* old xxreadtoken */
  10917. static int
  10918. readtoken(void)
  10919. {
  10920. int t;
  10921. int kwd = checkkwd;
  10922. #if DEBUG
  10923. smallint alreadyseen = tokpushback;
  10924. #endif
  10925. #if ENABLE_ASH_ALIAS
  10926. top:
  10927. #endif
  10928. t = xxreadtoken();
  10929. /*
  10930. * eat newlines
  10931. */
  10932. if (kwd & CHKNL) {
  10933. while (t == TNL) {
  10934. parseheredoc();
  10935. t = xxreadtoken();
  10936. }
  10937. }
  10938. if (t != TWORD || quoteflag) {
  10939. goto out;
  10940. }
  10941. /*
  10942. * check for keywords
  10943. */
  10944. if (kwd & CHKKWD) {
  10945. const char *const *pp;
  10946. pp = findkwd(wordtext);
  10947. if (pp) {
  10948. lasttoken = t = pp - tokname_array;
  10949. TRACE(("keyword '%s' recognized\n", tokname_array[t] + 1));
  10950. goto out;
  10951. }
  10952. }
  10953. if (checkkwd & CHKALIAS) {
  10954. #if ENABLE_ASH_ALIAS
  10955. struct alias *ap;
  10956. ap = lookupalias(wordtext, 1);
  10957. if (ap != NULL) {
  10958. if (*ap->val) {
  10959. pushstring(ap->val, ap);
  10960. }
  10961. goto top;
  10962. }
  10963. #endif
  10964. }
  10965. out:
  10966. checkkwd = 0;
  10967. #if DEBUG
  10968. if (!alreadyseen)
  10969. TRACE(("token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  10970. else
  10971. TRACE(("reread token '%s' %s\n", tokname_array[t] + 1, t == TWORD ? wordtext : ""));
  10972. #endif
  10973. return t;
  10974. }
  10975. static int
  10976. peektoken(void)
  10977. {
  10978. int t;
  10979. t = readtoken();
  10980. tokpushback = 1;
  10981. return t;
  10982. }
  10983. /*
  10984. * Read and parse a command. Returns NODE_EOF on end of file.
  10985. * (NULL is a valid parse tree indicating a blank line.)
  10986. */
  10987. static union node *
  10988. parsecmd(int interact)
  10989. {
  10990. tokpushback = 0;
  10991. checkkwd = 0;
  10992. heredoclist = 0;
  10993. doprompt = interact;
  10994. setprompt_if(doprompt, doprompt);
  10995. needprompt = 0;
  10996. return list(1);
  10997. }
  10998. /*
  10999. * Input any here documents.
  11000. */
  11001. static void
  11002. parseheredoc(void)
  11003. {
  11004. struct heredoc *here;
  11005. union node *n;
  11006. here = heredoclist;
  11007. heredoclist = NULL;
  11008. while (here) {
  11009. setprompt_if(needprompt, 2);
  11010. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11011. here->eofmark, here->striptabs);
  11012. n = stzalloc(sizeof(struct narg));
  11013. n->narg.type = NARG;
  11014. /*n->narg.next = NULL; - stzalloc did it */
  11015. n->narg.text = wordtext;
  11016. n->narg.backquote = backquotelist;
  11017. here->here->nhere.doc = n;
  11018. here = here->next;
  11019. }
  11020. }
  11021. /*
  11022. * called by editline -- any expansions to the prompt should be added here.
  11023. */
  11024. #if ENABLE_ASH_EXPAND_PRMT
  11025. static const char *
  11026. expandstr(const char *ps)
  11027. {
  11028. union node n;
  11029. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  11030. * and token processing _can_ alter it (delete NULs etc). */
  11031. setinputstring((char *)ps);
  11032. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  11033. popfile();
  11034. n.narg.type = NARG;
  11035. n.narg.next = NULL;
  11036. n.narg.text = wordtext;
  11037. n.narg.backquote = backquotelist;
  11038. expandarg(&n, NULL, EXP_QUOTED);
  11039. return stackblock();
  11040. }
  11041. #endif
  11042. /*
  11043. * Execute a command or commands contained in a string.
  11044. */
  11045. static int
  11046. evalstring(char *s, int mask)
  11047. {
  11048. union node *n;
  11049. struct stackmark smark;
  11050. int skip;
  11051. setinputstring(s);
  11052. setstackmark(&smark);
  11053. skip = 0;
  11054. while ((n = parsecmd(0)) != NODE_EOF) {
  11055. evaltree(n, 0);
  11056. popstackmark(&smark);
  11057. skip = evalskip;
  11058. if (skip)
  11059. break;
  11060. }
  11061. popfile();
  11062. skip &= mask;
  11063. evalskip = skip;
  11064. return skip;
  11065. }
  11066. /*
  11067. * The eval command.
  11068. */
  11069. static int FAST_FUNC
  11070. evalcmd(int argc UNUSED_PARAM, char **argv)
  11071. {
  11072. char *p;
  11073. char *concat;
  11074. if (argv[1]) {
  11075. p = argv[1];
  11076. argv += 2;
  11077. if (argv[0]) {
  11078. STARTSTACKSTR(concat);
  11079. for (;;) {
  11080. concat = stack_putstr(p, concat);
  11081. p = *argv++;
  11082. if (p == NULL)
  11083. break;
  11084. STPUTC(' ', concat);
  11085. }
  11086. STPUTC('\0', concat);
  11087. p = grabstackstr(concat);
  11088. }
  11089. evalstring(p, ~SKIPEVAL);
  11090. }
  11091. return exitstatus;
  11092. }
  11093. /*
  11094. * Read and execute commands.
  11095. * "Top" is nonzero for the top level command loop;
  11096. * it turns on prompting if the shell is interactive.
  11097. */
  11098. static int
  11099. cmdloop(int top)
  11100. {
  11101. union node *n;
  11102. struct stackmark smark;
  11103. int inter;
  11104. int numeof = 0;
  11105. TRACE(("cmdloop(%d) called\n", top));
  11106. for (;;) {
  11107. int skip;
  11108. setstackmark(&smark);
  11109. #if JOBS
  11110. if (doing_jobctl)
  11111. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11112. #endif
  11113. inter = 0;
  11114. if (iflag && top) {
  11115. inter++;
  11116. chkmail();
  11117. }
  11118. n = parsecmd(inter);
  11119. #if DEBUG
  11120. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11121. showtree(n);
  11122. #endif
  11123. if (n == NODE_EOF) {
  11124. if (!top || numeof >= 50)
  11125. break;
  11126. if (!stoppedjobs()) {
  11127. if (!Iflag)
  11128. break;
  11129. out2str("\nUse \"exit\" to leave shell.\n");
  11130. }
  11131. numeof++;
  11132. } else if (nflag == 0) {
  11133. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11134. job_warning >>= 1;
  11135. numeof = 0;
  11136. evaltree(n, 0);
  11137. }
  11138. popstackmark(&smark);
  11139. skip = evalskip;
  11140. if (skip) {
  11141. evalskip = 0;
  11142. return skip & SKIPEVAL;
  11143. }
  11144. }
  11145. return 0;
  11146. }
  11147. /*
  11148. * Take commands from a file. To be compatible we should do a path
  11149. * search for the file, which is necessary to find sub-commands.
  11150. */
  11151. static char *
  11152. find_dot_file(char *name)
  11153. {
  11154. char *fullname;
  11155. const char *path = pathval();
  11156. struct stat statb;
  11157. /* don't try this for absolute or relative paths */
  11158. if (strchr(name, '/'))
  11159. return name;
  11160. /* IIRC standards do not say whether . is to be searched.
  11161. * And it is even smaller this way, making it unconditional for now:
  11162. */
  11163. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  11164. fullname = name;
  11165. goto try_cur_dir;
  11166. }
  11167. while ((fullname = path_advance(&path, name)) != NULL) {
  11168. try_cur_dir:
  11169. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11170. /*
  11171. * Don't bother freeing here, since it will
  11172. * be freed by the caller.
  11173. */
  11174. return fullname;
  11175. }
  11176. if (fullname != name)
  11177. stunalloc(fullname);
  11178. }
  11179. /* not found in the PATH */
  11180. ash_msg_and_raise_error("%s: not found", name);
  11181. /* NOTREACHED */
  11182. }
  11183. static int FAST_FUNC
  11184. dotcmd(int argc, char **argv)
  11185. {
  11186. char *fullname;
  11187. struct strlist *sp;
  11188. volatile struct shparam saveparam;
  11189. for (sp = cmdenviron; sp; sp = sp->next)
  11190. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11191. if (!argv[1]) {
  11192. /* bash says: "bash: .: filename argument required" */
  11193. return 2; /* bash compat */
  11194. }
  11195. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11196. exitstatus = 0;
  11197. /* This aborts if file isn't found, which is POSIXly correct.
  11198. * bash returns exitcode 1 instead.
  11199. */
  11200. fullname = find_dot_file(argv[1]);
  11201. argv += 2;
  11202. argc -= 2;
  11203. if (argc) { /* argc > 0, argv[0] != NULL */
  11204. saveparam = shellparam;
  11205. shellparam.malloced = 0;
  11206. shellparam.nparam = argc;
  11207. shellparam.p = argv;
  11208. };
  11209. /* This aborts if file can't be opened, which is POSIXly correct.
  11210. * bash returns exitcode 1 instead.
  11211. */
  11212. setinputfile(fullname, INPUT_PUSH_FILE);
  11213. commandname = fullname;
  11214. cmdloop(0);
  11215. popfile();
  11216. if (argc) {
  11217. freeparam(&shellparam);
  11218. shellparam = saveparam;
  11219. };
  11220. return exitstatus;
  11221. }
  11222. static int FAST_FUNC
  11223. exitcmd(int argc UNUSED_PARAM, char **argv)
  11224. {
  11225. if (stoppedjobs())
  11226. return 0;
  11227. if (argv[1])
  11228. exitstatus = number(argv[1]);
  11229. raise_exception(EXEXIT);
  11230. /* NOTREACHED */
  11231. }
  11232. /*
  11233. * Read a file containing shell functions.
  11234. */
  11235. static void
  11236. readcmdfile(char *name)
  11237. {
  11238. setinputfile(name, INPUT_PUSH_FILE);
  11239. cmdloop(0);
  11240. popfile();
  11241. }
  11242. /* ============ find_command inplementation */
  11243. /*
  11244. * Resolve a command name. If you change this routine, you may have to
  11245. * change the shellexec routine as well.
  11246. */
  11247. static void
  11248. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11249. {
  11250. struct tblentry *cmdp;
  11251. int idx;
  11252. int prev;
  11253. char *fullname;
  11254. struct stat statb;
  11255. int e;
  11256. int updatetbl;
  11257. struct builtincmd *bcmd;
  11258. /* If name contains a slash, don't use PATH or hash table */
  11259. if (strchr(name, '/') != NULL) {
  11260. entry->u.index = -1;
  11261. if (act & DO_ABS) {
  11262. while (stat(name, &statb) < 0) {
  11263. #ifdef SYSV
  11264. if (errno == EINTR)
  11265. continue;
  11266. #endif
  11267. entry->cmdtype = CMDUNKNOWN;
  11268. return;
  11269. }
  11270. }
  11271. entry->cmdtype = CMDNORMAL;
  11272. return;
  11273. }
  11274. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11275. updatetbl = (path == pathval());
  11276. if (!updatetbl) {
  11277. act |= DO_ALTPATH;
  11278. if (strstr(path, "%builtin") != NULL)
  11279. act |= DO_ALTBLTIN;
  11280. }
  11281. /* If name is in the table, check answer will be ok */
  11282. cmdp = cmdlookup(name, 0);
  11283. if (cmdp != NULL) {
  11284. int bit;
  11285. switch (cmdp->cmdtype) {
  11286. default:
  11287. #if DEBUG
  11288. abort();
  11289. #endif
  11290. case CMDNORMAL:
  11291. bit = DO_ALTPATH;
  11292. break;
  11293. case CMDFUNCTION:
  11294. bit = DO_NOFUNC;
  11295. break;
  11296. case CMDBUILTIN:
  11297. bit = DO_ALTBLTIN;
  11298. break;
  11299. }
  11300. if (act & bit) {
  11301. updatetbl = 0;
  11302. cmdp = NULL;
  11303. } else if (cmdp->rehash == 0)
  11304. /* if not invalidated by cd, we're done */
  11305. goto success;
  11306. }
  11307. /* If %builtin not in path, check for builtin next */
  11308. bcmd = find_builtin(name);
  11309. if (bcmd) {
  11310. if (IS_BUILTIN_REGULAR(bcmd))
  11311. goto builtin_success;
  11312. if (act & DO_ALTPATH) {
  11313. if (!(act & DO_ALTBLTIN))
  11314. goto builtin_success;
  11315. } else if (builtinloc <= 0) {
  11316. goto builtin_success;
  11317. }
  11318. }
  11319. #if ENABLE_FEATURE_SH_STANDALONE
  11320. {
  11321. int applet_no = find_applet_by_name(name);
  11322. if (applet_no >= 0) {
  11323. entry->cmdtype = CMDNORMAL;
  11324. entry->u.index = -2 - applet_no;
  11325. return;
  11326. }
  11327. }
  11328. #endif
  11329. /* We have to search path. */
  11330. prev = -1; /* where to start */
  11331. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11332. if (cmdp->cmdtype == CMDBUILTIN)
  11333. prev = builtinloc;
  11334. else
  11335. prev = cmdp->param.index;
  11336. }
  11337. e = ENOENT;
  11338. idx = -1;
  11339. loop:
  11340. while ((fullname = path_advance(&path, name)) != NULL) {
  11341. stunalloc(fullname);
  11342. /* NB: code below will still use fullname
  11343. * despite it being "unallocated" */
  11344. idx++;
  11345. if (pathopt) {
  11346. if (prefix(pathopt, "builtin")) {
  11347. if (bcmd)
  11348. goto builtin_success;
  11349. continue;
  11350. }
  11351. if ((act & DO_NOFUNC)
  11352. || !prefix(pathopt, "func")
  11353. ) { /* ignore unimplemented options */
  11354. continue;
  11355. }
  11356. }
  11357. /* if rehash, don't redo absolute path names */
  11358. if (fullname[0] == '/' && idx <= prev) {
  11359. if (idx < prev)
  11360. continue;
  11361. TRACE(("searchexec \"%s\": no change\n", name));
  11362. goto success;
  11363. }
  11364. while (stat(fullname, &statb) < 0) {
  11365. #ifdef SYSV
  11366. if (errno == EINTR)
  11367. continue;
  11368. #endif
  11369. if (errno != ENOENT && errno != ENOTDIR)
  11370. e = errno;
  11371. goto loop;
  11372. }
  11373. e = EACCES; /* if we fail, this will be the error */
  11374. if (!S_ISREG(statb.st_mode))
  11375. continue;
  11376. if (pathopt) { /* this is a %func directory */
  11377. stalloc(strlen(fullname) + 1);
  11378. /* NB: stalloc will return space pointed by fullname
  11379. * (because we don't have any intervening allocations
  11380. * between stunalloc above and this stalloc) */
  11381. readcmdfile(fullname);
  11382. cmdp = cmdlookup(name, 0);
  11383. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11384. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11385. stunalloc(fullname);
  11386. goto success;
  11387. }
  11388. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11389. if (!updatetbl) {
  11390. entry->cmdtype = CMDNORMAL;
  11391. entry->u.index = idx;
  11392. return;
  11393. }
  11394. INT_OFF;
  11395. cmdp = cmdlookup(name, 1);
  11396. cmdp->cmdtype = CMDNORMAL;
  11397. cmdp->param.index = idx;
  11398. INT_ON;
  11399. goto success;
  11400. }
  11401. /* We failed. If there was an entry for this command, delete it */
  11402. if (cmdp && updatetbl)
  11403. delete_cmd_entry();
  11404. if (act & DO_ERR)
  11405. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11406. entry->cmdtype = CMDUNKNOWN;
  11407. return;
  11408. builtin_success:
  11409. if (!updatetbl) {
  11410. entry->cmdtype = CMDBUILTIN;
  11411. entry->u.cmd = bcmd;
  11412. return;
  11413. }
  11414. INT_OFF;
  11415. cmdp = cmdlookup(name, 1);
  11416. cmdp->cmdtype = CMDBUILTIN;
  11417. cmdp->param.cmd = bcmd;
  11418. INT_ON;
  11419. success:
  11420. cmdp->rehash = 0;
  11421. entry->cmdtype = cmdp->cmdtype;
  11422. entry->u = cmdp->param;
  11423. }
  11424. /* ============ trap.c */
  11425. /*
  11426. * The trap builtin.
  11427. */
  11428. static int FAST_FUNC
  11429. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11430. {
  11431. char *action;
  11432. char **ap;
  11433. int signo, exitcode;
  11434. nextopt(nullstr);
  11435. ap = argptr;
  11436. if (!*ap) {
  11437. for (signo = 0; signo < NSIG; signo++) {
  11438. char *tr = trap_ptr[signo];
  11439. if (tr) {
  11440. /* note: bash adds "SIG", but only if invoked
  11441. * as "bash". If called as "sh", or if set -o posix,
  11442. * then it prints short signal names.
  11443. * We are printing short names: */
  11444. out1fmt("trap -- %s %s\n",
  11445. single_quote(tr),
  11446. get_signame(signo));
  11447. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11448. * In this case, we will exit very soon, no need to free(). */
  11449. /* if (trap_ptr != trap && tp[0]) */
  11450. /* free(tr); */
  11451. }
  11452. }
  11453. /*
  11454. if (trap_ptr != trap) {
  11455. free(trap_ptr);
  11456. trap_ptr = trap;
  11457. }
  11458. */
  11459. return 0;
  11460. }
  11461. action = NULL;
  11462. if (ap[1])
  11463. action = *ap++;
  11464. exitcode = 0;
  11465. while (*ap) {
  11466. signo = get_signum(*ap);
  11467. if (signo < 0) {
  11468. /* Mimic bash message exactly */
  11469. ash_msg("%s: invalid signal specification", *ap);
  11470. exitcode = 1;
  11471. goto next;
  11472. }
  11473. INT_OFF;
  11474. if (action) {
  11475. if (LONE_DASH(action))
  11476. action = NULL;
  11477. else
  11478. action = ckstrdup(action);
  11479. }
  11480. free(trap[signo]);
  11481. if (action)
  11482. may_have_traps = 1;
  11483. trap[signo] = action;
  11484. if (signo != 0)
  11485. setsignal(signo);
  11486. INT_ON;
  11487. next:
  11488. ap++;
  11489. }
  11490. return exitcode;
  11491. }
  11492. /* ============ Builtins */
  11493. #if ENABLE_ASH_HELP
  11494. static int FAST_FUNC
  11495. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11496. {
  11497. unsigned col;
  11498. unsigned i;
  11499. out1fmt(
  11500. "Built-in commands:\n"
  11501. "------------------\n");
  11502. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11503. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11504. builtintab[i].name + 1);
  11505. if (col > 60) {
  11506. out1fmt("\n");
  11507. col = 0;
  11508. }
  11509. }
  11510. # if ENABLE_FEATURE_SH_STANDALONE
  11511. {
  11512. const char *a = applet_names;
  11513. while (*a) {
  11514. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11515. if (col > 60) {
  11516. out1fmt("\n");
  11517. col = 0;
  11518. }
  11519. a += strlen(a) + 1;
  11520. }
  11521. }
  11522. # endif
  11523. out1fmt("\n\n");
  11524. return EXIT_SUCCESS;
  11525. }
  11526. #endif
  11527. #if MAX_HISTORY
  11528. static int FAST_FUNC
  11529. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11530. {
  11531. show_history(line_input_state);
  11532. return EXIT_SUCCESS;
  11533. }
  11534. #endif
  11535. /*
  11536. * The export and readonly commands.
  11537. */
  11538. static int FAST_FUNC
  11539. exportcmd(int argc UNUSED_PARAM, char **argv)
  11540. {
  11541. struct var *vp;
  11542. char *name;
  11543. const char *p;
  11544. char **aptr;
  11545. char opt;
  11546. int flag;
  11547. int flag_off;
  11548. /* "readonly" in bash accepts, but ignores -n.
  11549. * We do the same: it saves a conditional in nextopt's param.
  11550. */
  11551. flag_off = 0;
  11552. while ((opt = nextopt("np")) != '\0') {
  11553. if (opt == 'n')
  11554. flag_off = VEXPORT;
  11555. }
  11556. flag = VEXPORT;
  11557. if (argv[0][0] == 'r') {
  11558. flag = VREADONLY;
  11559. flag_off = 0; /* readonly ignores -n */
  11560. }
  11561. flag_off = ~flag_off;
  11562. /*if (opt_p_not_specified) - bash doesnt check this. Try "export -p NAME" */
  11563. {
  11564. aptr = argptr;
  11565. name = *aptr;
  11566. if (name) {
  11567. do {
  11568. p = strchr(name, '=');
  11569. if (p != NULL) {
  11570. p++;
  11571. } else {
  11572. vp = *findvar(hashvar(name), name);
  11573. if (vp) {
  11574. vp->flags = ((vp->flags | flag) & flag_off);
  11575. continue;
  11576. }
  11577. }
  11578. setvar(name, p, (flag & flag_off));
  11579. } while ((name = *++aptr) != NULL);
  11580. return 0;
  11581. }
  11582. }
  11583. /* No arguments. Show the list of exported or readonly vars.
  11584. * -n is ignored.
  11585. */
  11586. showvars(argv[0], flag, 0);
  11587. return 0;
  11588. }
  11589. /*
  11590. * Delete a function if it exists.
  11591. */
  11592. static void
  11593. unsetfunc(const char *name)
  11594. {
  11595. struct tblentry *cmdp;
  11596. cmdp = cmdlookup(name, 0);
  11597. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  11598. delete_cmd_entry();
  11599. }
  11600. /*
  11601. * The unset builtin command. We unset the function before we unset the
  11602. * variable to allow a function to be unset when there is a readonly variable
  11603. * with the same name.
  11604. */
  11605. static int FAST_FUNC
  11606. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11607. {
  11608. char **ap;
  11609. int i;
  11610. int flag = 0;
  11611. int ret = 0;
  11612. while ((i = nextopt("vf")) != 0) {
  11613. flag = i;
  11614. }
  11615. for (ap = argptr; *ap; ap++) {
  11616. if (flag != 'f') {
  11617. i = unsetvar(*ap);
  11618. ret |= i;
  11619. if (!(i & 2))
  11620. continue;
  11621. }
  11622. if (flag != 'v')
  11623. unsetfunc(*ap);
  11624. }
  11625. return ret & 1;
  11626. }
  11627. static const unsigned char timescmd_str[] ALIGN1 = {
  11628. ' ', offsetof(struct tms, tms_utime),
  11629. '\n', offsetof(struct tms, tms_stime),
  11630. ' ', offsetof(struct tms, tms_cutime),
  11631. '\n', offsetof(struct tms, tms_cstime),
  11632. 0
  11633. };
  11634. static int FAST_FUNC
  11635. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11636. {
  11637. unsigned long clk_tck, s, t;
  11638. const unsigned char *p;
  11639. struct tms buf;
  11640. clk_tck = bb_clk_tck();
  11641. times(&buf);
  11642. p = timescmd_str;
  11643. do {
  11644. t = *(clock_t *)(((char *) &buf) + p[1]);
  11645. s = t / clk_tck;
  11646. t = t % clk_tck;
  11647. out1fmt("%lum%lu.%03lus%c",
  11648. s / 60, s % 60,
  11649. (t * 1000) / clk_tck,
  11650. p[0]);
  11651. p += 2;
  11652. } while (*p);
  11653. return 0;
  11654. }
  11655. #if ENABLE_SH_MATH_SUPPORT
  11656. /*
  11657. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  11658. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11659. *
  11660. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11661. */
  11662. static int FAST_FUNC
  11663. letcmd(int argc UNUSED_PARAM, char **argv)
  11664. {
  11665. arith_t i;
  11666. argv++;
  11667. if (!*argv)
  11668. ash_msg_and_raise_error("expression expected");
  11669. do {
  11670. i = ash_arith(*argv);
  11671. } while (*++argv);
  11672. return !i;
  11673. }
  11674. #endif
  11675. /*
  11676. * The read builtin. Options:
  11677. * -r Do not interpret '\' specially
  11678. * -s Turn off echo (tty only)
  11679. * -n NCHARS Read NCHARS max
  11680. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11681. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11682. * -u FD Read from given FD instead of fd 0
  11683. * This uses unbuffered input, which may be avoidable in some cases.
  11684. * TODO: bash also has:
  11685. * -a ARRAY Read into array[0],[1],etc
  11686. * -d DELIM End on DELIM char, not newline
  11687. * -e Use line editing (tty only)
  11688. */
  11689. static int FAST_FUNC
  11690. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11691. {
  11692. char *opt_n = NULL;
  11693. char *opt_p = NULL;
  11694. char *opt_t = NULL;
  11695. char *opt_u = NULL;
  11696. int read_flags = 0;
  11697. const char *r;
  11698. int i;
  11699. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11700. switch (i) {
  11701. case 'p':
  11702. opt_p = optionarg;
  11703. break;
  11704. case 'n':
  11705. opt_n = optionarg;
  11706. break;
  11707. case 's':
  11708. read_flags |= BUILTIN_READ_SILENT;
  11709. break;
  11710. case 't':
  11711. opt_t = optionarg;
  11712. break;
  11713. case 'r':
  11714. read_flags |= BUILTIN_READ_RAW;
  11715. break;
  11716. case 'u':
  11717. opt_u = optionarg;
  11718. break;
  11719. default:
  11720. break;
  11721. }
  11722. }
  11723. /* "read -s" needs to save/restore termios, can't allow ^C
  11724. * to jump out of it.
  11725. */
  11726. INT_OFF;
  11727. r = shell_builtin_read(setvar0,
  11728. argptr,
  11729. bltinlookup("IFS"), /* can be NULL */
  11730. read_flags,
  11731. opt_n,
  11732. opt_p,
  11733. opt_t,
  11734. opt_u
  11735. );
  11736. INT_ON;
  11737. if ((uintptr_t)r > 1)
  11738. ash_msg_and_raise_error(r);
  11739. return (uintptr_t)r;
  11740. }
  11741. static int FAST_FUNC
  11742. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11743. {
  11744. static const char permuser[3] ALIGN1 = "ogu";
  11745. mode_t mask;
  11746. int symbolic_mode = 0;
  11747. while (nextopt("S") != '\0') {
  11748. symbolic_mode = 1;
  11749. }
  11750. INT_OFF;
  11751. mask = umask(0);
  11752. umask(mask);
  11753. INT_ON;
  11754. if (*argptr == NULL) {
  11755. if (symbolic_mode) {
  11756. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  11757. char *p = buf;
  11758. int i;
  11759. i = 2;
  11760. for (;;) {
  11761. *p++ = ',';
  11762. *p++ = permuser[i];
  11763. *p++ = '=';
  11764. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  11765. if (!(mask & 0400)) *p++ = 'r';
  11766. if (!(mask & 0200)) *p++ = 'w';
  11767. if (!(mask & 0100)) *p++ = 'x';
  11768. mask <<= 3;
  11769. if (--i < 0)
  11770. break;
  11771. }
  11772. *p = '\0';
  11773. puts(buf + 1);
  11774. } else {
  11775. out1fmt("%04o\n", mask);
  11776. }
  11777. } else {
  11778. char *modestr = *argptr;
  11779. /* numeric umasks are taken as-is */
  11780. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  11781. if (!isdigit(modestr[0]))
  11782. mask ^= 0777;
  11783. mask = bb_parse_mode(modestr, mask);
  11784. if ((unsigned)mask > 0777) {
  11785. ash_msg_and_raise_error("illegal mode: %s", modestr);
  11786. }
  11787. if (!isdigit(modestr[0]))
  11788. mask ^= 0777;
  11789. umask(mask);
  11790. }
  11791. return 0;
  11792. }
  11793. static int FAST_FUNC
  11794. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  11795. {
  11796. return shell_builtin_ulimit(argv);
  11797. }
  11798. /* ============ main() and helpers */
  11799. /*
  11800. * Called to exit the shell.
  11801. */
  11802. static void
  11803. exitshell(void)
  11804. {
  11805. struct jmploc loc;
  11806. char *p;
  11807. int status;
  11808. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  11809. save_history(line_input_state);
  11810. #endif
  11811. status = exitstatus;
  11812. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11813. if (setjmp(loc.loc)) {
  11814. if (exception_type == EXEXIT)
  11815. /* dash bug: it just does _exit(exitstatus) here
  11816. * but we have to do setjobctl(0) first!
  11817. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11818. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11819. status = exitstatus;
  11820. goto out;
  11821. }
  11822. exception_handler = &loc;
  11823. p = trap[0];
  11824. if (p) {
  11825. trap[0] = NULL;
  11826. evalstring(p, 0);
  11827. free(p);
  11828. }
  11829. flush_stdout_stderr();
  11830. out:
  11831. setjobctl(0);
  11832. _exit(status);
  11833. /* NOTREACHED */
  11834. }
  11835. static void
  11836. init(void)
  11837. {
  11838. /* from input.c: */
  11839. /* we will never free this */
  11840. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  11841. /* from trap.c: */
  11842. signal(SIGCHLD, SIG_DFL);
  11843. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11844. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11845. */
  11846. signal(SIGHUP, SIG_DFL);
  11847. /* from var.c: */
  11848. {
  11849. char **envp;
  11850. const char *p;
  11851. struct stat st1, st2;
  11852. initvar();
  11853. for (envp = environ; envp && *envp; envp++) {
  11854. if (strchr(*envp, '=')) {
  11855. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11856. }
  11857. }
  11858. setvar0("PPID", utoa(getppid()));
  11859. #if ENABLE_ASH_BASH_COMPAT
  11860. p = lookupvar("SHLVL");
  11861. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  11862. if (!lookupvar("HOSTNAME")) {
  11863. struct utsname uts;
  11864. uname(&uts);
  11865. setvar0("HOSTNAME", uts.nodename);
  11866. }
  11867. #endif
  11868. p = lookupvar("PWD");
  11869. if (p) {
  11870. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11871. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  11872. ) {
  11873. p = '\0';
  11874. }
  11875. }
  11876. setpwd(p, 0);
  11877. }
  11878. }
  11879. //usage:#define ash_trivial_usage
  11880. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  11881. //usage:#define ash_full_usage "\n\n"
  11882. //usage: "Unix shell interpreter"
  11883. //usage:#if ENABLE_FEATURE_SH_IS_ASH
  11884. //usage:# define sh_trivial_usage ash_trivial_usage
  11885. //usage:# define sh_full_usage ash_full_usage
  11886. //usage:#endif
  11887. //usage:#if ENABLE_FEATURE_BASH_IS_ASH
  11888. //usage:# define bash_trivial_usage ash_trivial_usage
  11889. //usage:# define bash_full_usage ash_full_usage
  11890. //usage:#endif
  11891. /*
  11892. * Process the shell command line arguments.
  11893. */
  11894. static void
  11895. procargs(char **argv)
  11896. {
  11897. int i;
  11898. const char *xminusc;
  11899. char **xargv;
  11900. xargv = argv;
  11901. arg0 = xargv[0];
  11902. /* if (xargv[0]) - mmm, this is always true! */
  11903. xargv++;
  11904. for (i = 0; i < NOPTS; i++)
  11905. optlist[i] = 2;
  11906. argptr = xargv;
  11907. if (options(/*cmdline:*/ 1)) {
  11908. /* it already printed err message */
  11909. raise_exception(EXERROR);
  11910. }
  11911. xargv = argptr;
  11912. xminusc = minusc;
  11913. if (*xargv == NULL) {
  11914. if (xminusc)
  11915. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11916. sflag = 1;
  11917. }
  11918. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11919. iflag = 1;
  11920. if (mflag == 2)
  11921. mflag = iflag;
  11922. for (i = 0; i < NOPTS; i++)
  11923. if (optlist[i] == 2)
  11924. optlist[i] = 0;
  11925. #if DEBUG == 2
  11926. debug = 1;
  11927. #endif
  11928. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11929. if (xminusc) {
  11930. minusc = *xargv++;
  11931. if (*xargv)
  11932. goto setarg0;
  11933. } else if (!sflag) {
  11934. setinputfile(*xargv, 0);
  11935. setarg0:
  11936. arg0 = *xargv++;
  11937. commandname = arg0;
  11938. }
  11939. shellparam.p = xargv;
  11940. #if ENABLE_ASH_GETOPTS
  11941. shellparam.optind = 1;
  11942. shellparam.optoff = -1;
  11943. #endif
  11944. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11945. while (*xargv) {
  11946. shellparam.nparam++;
  11947. xargv++;
  11948. }
  11949. optschanged();
  11950. }
  11951. /*
  11952. * Read /etc/profile or .profile.
  11953. */
  11954. static void
  11955. read_profile(const char *name)
  11956. {
  11957. int skip;
  11958. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11959. return;
  11960. skip = cmdloop(0);
  11961. popfile();
  11962. if (skip)
  11963. exitshell();
  11964. }
  11965. /*
  11966. * This routine is called when an error or an interrupt occurs in an
  11967. * interactive shell and control is returned to the main command loop.
  11968. */
  11969. static void
  11970. reset(void)
  11971. {
  11972. /* from eval.c: */
  11973. evalskip = 0;
  11974. loopnest = 0;
  11975. /* from input.c: */
  11976. g_parsefile->left_in_buffer = 0;
  11977. g_parsefile->left_in_line = 0; /* clear input buffer */
  11978. popallfiles();
  11979. /* from parser.c: */
  11980. tokpushback = 0;
  11981. checkkwd = 0;
  11982. /* from redir.c: */
  11983. clearredir(/*drop:*/ 0);
  11984. }
  11985. #if PROFILE
  11986. static short profile_buf[16384];
  11987. extern int etext();
  11988. #endif
  11989. /*
  11990. * Main routine. We initialize things, parse the arguments, execute
  11991. * profiles if we're a login shell, and then call cmdloop to execute
  11992. * commands. The setjmp call sets up the location to jump to when an
  11993. * exception occurs. When an exception occurs the variable "state"
  11994. * is used to figure out how far we had gotten.
  11995. */
  11996. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  11997. int ash_main(int argc UNUSED_PARAM, char **argv)
  11998. {
  11999. const char *shinit;
  12000. volatile smallint state;
  12001. struct jmploc jmploc;
  12002. struct stackmark smark;
  12003. /* Initialize global data */
  12004. INIT_G_misc();
  12005. INIT_G_memstack();
  12006. INIT_G_var();
  12007. #if ENABLE_ASH_ALIAS
  12008. INIT_G_alias();
  12009. #endif
  12010. INIT_G_cmdtable();
  12011. #if PROFILE
  12012. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12013. #endif
  12014. #if ENABLE_FEATURE_EDITING
  12015. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12016. #endif
  12017. state = 0;
  12018. if (setjmp(jmploc.loc)) {
  12019. smallint e;
  12020. smallint s;
  12021. reset();
  12022. e = exception_type;
  12023. if (e == EXERROR)
  12024. exitstatus = 2;
  12025. s = state;
  12026. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12027. exitshell();
  12028. }
  12029. if (e == EXINT) {
  12030. newline_and_flush(stderr);
  12031. }
  12032. popstackmark(&smark);
  12033. FORCE_INT_ON; /* enable interrupts */
  12034. if (s == 1)
  12035. goto state1;
  12036. if (s == 2)
  12037. goto state2;
  12038. if (s == 3)
  12039. goto state3;
  12040. goto state4;
  12041. }
  12042. exception_handler = &jmploc;
  12043. #if DEBUG
  12044. opentrace();
  12045. TRACE(("Shell args: "));
  12046. trace_puts_args(argv);
  12047. #endif
  12048. rootpid = getpid();
  12049. init();
  12050. setstackmark(&smark);
  12051. procargs(argv);
  12052. if (argv[0] && argv[0][0] == '-')
  12053. isloginsh = 1;
  12054. if (isloginsh) {
  12055. const char *hp;
  12056. state = 1;
  12057. read_profile("/etc/profile");
  12058. state1:
  12059. state = 2;
  12060. hp = lookupvar("HOME");
  12061. if (hp) {
  12062. hp = concat_path_file(hp, ".profile");
  12063. read_profile(hp);
  12064. free((char*)hp);
  12065. }
  12066. }
  12067. state2:
  12068. state = 3;
  12069. if (
  12070. #ifndef linux
  12071. getuid() == geteuid() && getgid() == getegid() &&
  12072. #endif
  12073. iflag
  12074. ) {
  12075. shinit = lookupvar("ENV");
  12076. if (shinit != NULL && *shinit != '\0') {
  12077. read_profile(shinit);
  12078. }
  12079. }
  12080. state3:
  12081. state = 4;
  12082. if (minusc) {
  12083. /* evalstring pushes parsefile stack.
  12084. * Ensure we don't falsely claim that 0 (stdin)
  12085. * is one of stacked source fds.
  12086. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12087. // if (!sflag) g_parsefile->pf_fd = -1;
  12088. // ^^ not necessary since now we special-case fd 0
  12089. // in is_hidden_fd() to not be considered "hidden fd"
  12090. evalstring(minusc, 0);
  12091. }
  12092. if (sflag || minusc == NULL) {
  12093. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12094. if (iflag) {
  12095. const char *hp = lookupvar("HISTFILE");
  12096. if (!hp) {
  12097. hp = lookupvar("HOME");
  12098. if (hp) {
  12099. hp = concat_path_file(hp, ".ash_history");
  12100. setvar0("HISTFILE", hp);
  12101. free((char*)hp);
  12102. hp = lookupvar("HISTFILE");
  12103. }
  12104. }
  12105. if (hp)
  12106. line_input_state->hist_file = hp;
  12107. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12108. hp = lookupvar("HISTFILESIZE");
  12109. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12110. # endif
  12111. }
  12112. #endif
  12113. state4: /* XXX ??? - why isn't this before the "if" statement */
  12114. cmdloop(1);
  12115. }
  12116. #if PROFILE
  12117. monitor(0);
  12118. #endif
  12119. #ifdef GPROF
  12120. {
  12121. extern void _mcleanup(void);
  12122. _mcleanup();
  12123. }
  12124. #endif
  12125. TRACE(("End of main reached\n"));
  12126. exitshell();
  12127. /* NOTREACHED */
  12128. }
  12129. /*-
  12130. * Copyright (c) 1989, 1991, 1993, 1994
  12131. * The Regents of the University of California. All rights reserved.
  12132. *
  12133. * This code is derived from software contributed to Berkeley by
  12134. * Kenneth Almquist.
  12135. *
  12136. * Redistribution and use in source and binary forms, with or without
  12137. * modification, are permitted provided that the following conditions
  12138. * are met:
  12139. * 1. Redistributions of source code must retain the above copyright
  12140. * notice, this list of conditions and the following disclaimer.
  12141. * 2. Redistributions in binary form must reproduce the above copyright
  12142. * notice, this list of conditions and the following disclaimer in the
  12143. * documentation and/or other materials provided with the distribution.
  12144. * 3. Neither the name of the University nor the names of its contributors
  12145. * may be used to endorse or promote products derived from this software
  12146. * without specific prior written permission.
  12147. *
  12148. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12149. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12150. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12151. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12152. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12153. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12154. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12155. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12156. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12157. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12158. * SUCH DAMAGE.
  12159. */