ash.c 330 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733
  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. //config:config SHELL_ASH
  19. //config: bool #hidden option
  20. //config: depends on !NOMMU
  21. //config:
  22. //config:config ASH
  23. //config: bool "ash (78 kb)"
  24. //config: default y
  25. //config: depends on !NOMMU
  26. //config: select SHELL_ASH
  27. //config: help
  28. //config: The most complete and most pedantically correct shell included with
  29. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  30. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  31. //config: (written by Kenneth Almquist) from NetBSD.
  32. //config:
  33. //config:# ash options
  34. //config:# note: Don't remove !NOMMU part in the next line; it would break
  35. //config:# menuconfig's indenting.
  36. //config:if !NOMMU && (SHELL_ASH || ASH || SH_IS_ASH || BASH_IS_ASH)
  37. //config:
  38. //config:config ASH_OPTIMIZE_FOR_SIZE
  39. //config: bool "Optimize for size instead of speed"
  40. //config: default y
  41. //config: depends on SHELL_ASH
  42. //config:
  43. //config:config ASH_INTERNAL_GLOB
  44. //config: bool "Use internal glob() implementation"
  45. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  46. //config: depends on SHELL_ASH
  47. //config: help
  48. //config: Do not use glob() function from libc, use internal implementation.
  49. //config: Use this if you are getting "glob.h: No such file or directory"
  50. //config: or similar build errors.
  51. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  52. //config: which would break ash if you select N here.
  53. //config:
  54. //config:config ASH_BASH_COMPAT
  55. //config: bool "bash-compatible extensions"
  56. //config: default y
  57. //config: depends on SHELL_ASH
  58. //config:
  59. //config:config ASH_BASH_SOURCE_CURDIR
  60. //config: bool "'source' and '.' builtins search current directory after $PATH"
  61. //config: default n # do not encourage non-standard behavior
  62. //config: depends on ASH_BASH_COMPAT
  63. //config: help
  64. //config: This is not compliant with standards. Avoid if possible.
  65. //config:
  66. //config:config ASH_BASH_NOT_FOUND_HOOK
  67. //config: bool "command_not_found_handle hook support"
  68. //config: default y
  69. //config: depends on ASH_BASH_COMPAT
  70. //config: help
  71. //config: Enable support for the 'command_not_found_handle' hook function,
  72. //config: from GNU bash, which allows for alternative command not found
  73. //config: handling.
  74. //config:
  75. //config:config ASH_JOB_CONTROL
  76. //config: bool "Job control"
  77. //config: default y
  78. //config: depends on SHELL_ASH
  79. //config:
  80. //config:config ASH_ALIAS
  81. //config: bool "Alias support"
  82. //config: default y
  83. //config: depends on SHELL_ASH
  84. //config:
  85. //config:config ASH_RANDOM_SUPPORT
  86. //config: bool "Pseudorandom generator and $RANDOM variable"
  87. //config: default y
  88. //config: depends on SHELL_ASH
  89. //config: help
  90. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  91. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  92. //config: You can reset the generator by using a specified start value.
  93. //config: After "unset RANDOM" the generator will switch off and this
  94. //config: variable will no longer have special treatment.
  95. //config:
  96. //config:config ASH_EXPAND_PRMT
  97. //config: bool "Expand prompt string"
  98. //config: default y
  99. //config: depends on SHELL_ASH
  100. //config: help
  101. //config: $PS# may contain volatile content, such as backquote commands.
  102. //config: This option recreates the prompt string from the environment
  103. //config: variable each time it is displayed.
  104. //config:
  105. //config:config ASH_IDLE_TIMEOUT
  106. //config: bool "Idle timeout variable $TMOUT"
  107. //config: default y
  108. //config: depends on SHELL_ASH
  109. //config: help
  110. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  111. //config:
  112. //config:config ASH_MAIL
  113. //config: bool "Check for new mail in interactive shell"
  114. //config: default y
  115. //config: depends on SHELL_ASH
  116. //config: help
  117. //config: Enable "check for new mail" function:
  118. //config: if set, $MAIL file and $MAILPATH list of files
  119. //config: are checked for mtime changes, and "you have mail"
  120. //config: message is printed if change is detected.
  121. //config:
  122. //config:config ASH_ECHO
  123. //config: bool "echo builtin"
  124. //config: default y
  125. //config: depends on SHELL_ASH
  126. //config:
  127. //config:config ASH_PRINTF
  128. //config: bool "printf builtin"
  129. //config: default y
  130. //config: depends on SHELL_ASH
  131. //config:
  132. //config:config ASH_TEST
  133. //config: bool "test builtin"
  134. //config: default y
  135. //config: depends on SHELL_ASH
  136. //config:
  137. //config:config ASH_HELP
  138. //config: bool "help builtin"
  139. //config: default y
  140. //config: depends on SHELL_ASH
  141. //config:
  142. //config:config ASH_GETOPTS
  143. //config: bool "getopts builtin"
  144. //config: default y
  145. //config: depends on SHELL_ASH
  146. //config:
  147. //config:config ASH_CMDCMD
  148. //config: bool "command builtin"
  149. //config: default y
  150. //config: depends on SHELL_ASH
  151. //config: help
  152. //config: Enable support for the 'command' builtin, which allows
  153. //config: you to run the specified command or builtin,
  154. //config: even when there is a function with the same name.
  155. //config:
  156. //config:endif # ash options
  157. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  158. // APPLET_ODDNAME:name main location suid_type help
  159. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  160. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  161. //kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
  162. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  163. /*
  164. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  165. * DEBUG=2 to compile in and turn on debugging.
  166. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  167. * debugging info is written to ./trace, quit signal generates core dump.
  168. */
  169. #define DEBUG 0
  170. /* Tweak debug output verbosity here */
  171. #define DEBUG_TIME 0
  172. #define DEBUG_PID 1
  173. #define DEBUG_SIG 1
  174. #define DEBUG_INTONOFF 0
  175. #define PROFILE 0
  176. #define JOBS ENABLE_ASH_JOB_CONTROL
  177. #include <fnmatch.h>
  178. #include <sys/times.h>
  179. #include <sys/utsname.h> /* for setting $HOSTNAME */
  180. #include "busybox.h" /* for applet_names */
  181. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  182. # include "embedded_scripts.h"
  183. #else
  184. # define NUM_SCRIPTS 0
  185. #endif
  186. /* So far, all bash compat is controlled by one config option */
  187. /* Separate defines document which part of code implements what */
  188. /* function keyword */
  189. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  191. /* &>file */
  192. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  194. /* $'...' */
  195. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  196. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  197. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  198. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  199. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  200. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  201. /* BASH_TEST2: [[ EXPR ]]
  202. * Status of [[ support:
  203. * && and || work as they should
  204. * = is glob match operator, not equality operator: STR = GLOB
  205. * == same as =
  206. * =~ is regex match operator: STR =~ REGEX
  207. * TODO:
  208. * singleword+noglob expansion:
  209. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  210. * [[ /bin/n* ]]; echo 0:$?
  211. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  212. * ( ) < > should not have special meaning (IOW: should not require quoting)
  213. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  214. */
  215. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  216. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  217. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  218. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  219. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  220. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  221. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  222. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  223. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  224. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  225. /* <(...) and >(...) */
  226. #if HAVE_DEV_FD
  227. # define BASH_PROCESS_SUBST ENABLE_ASH_BASH_COMPAT
  228. # define IF_BASH_PROCESS_SUBST IF_ASH_BASH_COMPAT
  229. #else
  230. # define BASH_PROCESS_SUBST 0
  231. # define IF_BASH_PROCESS_SUBST(...)
  232. #endif
  233. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  234. /* Bionic at least up to version 24 has no glob() */
  235. # undef ENABLE_ASH_INTERNAL_GLOB
  236. # define ENABLE_ASH_INTERNAL_GLOB 1
  237. #endif
  238. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  239. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  240. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  241. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  242. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  243. # error fails to match dirname, subsequently not expanding <pattern> in it.
  244. // Testcase:
  245. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  246. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  247. #endif
  248. #if !ENABLE_ASH_INTERNAL_GLOB
  249. # include <glob.h>
  250. #endif
  251. #include "unicode.h"
  252. #include "shell_common.h"
  253. #if ENABLE_FEATURE_SH_MATH
  254. # include "math.h"
  255. #else
  256. typedef long arith_t;
  257. # define ARITH_FMT "%ld"
  258. #endif
  259. #if ENABLE_ASH_RANDOM_SUPPORT
  260. # include "random.h"
  261. #else
  262. # define CLEAR_RANDOM_T(rnd) ((void)0)
  263. #endif
  264. #include "NUM_APPLETS.h"
  265. #if NUM_APPLETS == 1
  266. /* STANDALONE does not make sense, and won't compile */
  267. # undef CONFIG_FEATURE_SH_STANDALONE
  268. # undef ENABLE_FEATURE_SH_STANDALONE
  269. # undef IF_FEATURE_SH_STANDALONE
  270. # undef IF_NOT_FEATURE_SH_STANDALONE
  271. # define ENABLE_FEATURE_SH_STANDALONE 0
  272. # define IF_FEATURE_SH_STANDALONE(...)
  273. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  274. #endif
  275. #ifndef F_DUPFD_CLOEXEC
  276. # define F_DUPFD_CLOEXEC F_DUPFD
  277. #endif
  278. #ifndef O_CLOEXEC
  279. # define O_CLOEXEC 0
  280. #endif
  281. #ifndef PIPE_BUF
  282. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  283. #endif
  284. #if !BB_MMU
  285. # error "Do not even bother, ash will not run on NOMMU machine"
  286. #endif
  287. /* We use a trick to have more optimized code (fewer pointer reloads):
  288. * ash.c: extern struct globals *const ash_ptr_to_globals;
  289. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  290. * This way, compiler in ash.c knows the pointer can not change.
  291. *
  292. * However, this may break on weird arches or toolchains. In this case,
  293. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  294. * this optimization.
  295. */
  296. #ifndef BB_GLOBAL_CONST
  297. # define BB_GLOBAL_CONST const
  298. #endif
  299. /* ============ Hash table sizes. Configurable. */
  300. #define VTABSIZE 39
  301. #define ATABSIZE 39
  302. #define CMDTABLESIZE 31 /* should be prime */
  303. /* ============ Shell options */
  304. /* If you add/change options hare, update --help text too */
  305. static const char *const optletters_optnames[] = {
  306. "e" "errexit",
  307. "f" "noglob",
  308. /* bash has '-o ignoreeof', but no short synonym -I for it */
  309. /* (in bash, set -I disables invisible variables (what's that?)) */
  310. "I" "ignoreeof",
  311. /* The below allowed this invocation:
  312. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  313. * to be ^C-ed and get to interactive ash prompt.
  314. * bash does not support such "set -i".
  315. * In our code, this is denoted by empty long name:
  316. */
  317. "i" "",
  318. /* (removing "i" altogether would remove it from "$-", not good) */
  319. "m" "monitor",
  320. "n" "noexec",
  321. /* Ditto: bash has no "set -s", "set -c" */
  322. "s" "",
  323. "c" "",
  324. "x" "xtrace",
  325. "v" "verbose",
  326. "C" "noclobber",
  327. "a" "allexport",
  328. "b" "notify",
  329. "u" "nounset",
  330. "\0" "vi"
  331. #if BASH_PIPEFAIL
  332. ,"\0" "pipefail"
  333. #endif
  334. #if DEBUG
  335. ,"\0" "nolog"
  336. ,"\0" "debug"
  337. #endif
  338. };
  339. //bash 4.4.23 also has these opts (with these defaults):
  340. //braceexpand on
  341. //emacs on
  342. //errtrace off
  343. //functrace off
  344. //hashall on
  345. //histexpand off
  346. //history on
  347. //interactive-comments on
  348. //keyword off
  349. //onecmd off
  350. //physical off
  351. //posix off
  352. //privileged off
  353. #define optletters(n) optletters_optnames[n][0]
  354. #define optnames(n) (optletters_optnames[n] + 1)
  355. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  356. /* ============ Misc data */
  357. #define msg_illnum "Illegal number: %s"
  358. /*
  359. * We enclose jmp_buf in a structure so that we can declare pointers to
  360. * jump locations. The global variable handler contains the location to
  361. * jump to when an exception occurs, and the global variable exception_type
  362. * contains a code identifying the exception. To implement nested
  363. * exception handlers, the user should save the value of handler on entry
  364. * to an inner scope, set handler to point to a jmploc structure for the
  365. * inner scope, and restore handler on exit from the scope.
  366. */
  367. struct jmploc {
  368. jmp_buf loc;
  369. };
  370. struct globals_misc {
  371. uint8_t exitstatus; /* exit status of last command */
  372. uint8_t back_exitstatus;/* exit status of backquoted command */
  373. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  374. int savestatus; /* exit status of last command outside traps */
  375. int rootpid; /* pid of main shell */
  376. /* shell level: 0 for the main shell, 1 for its children, and so on */
  377. int shlvl;
  378. #define rootshell (!shlvl)
  379. int errlinno;
  380. char *minusc; /* argument to -c option */
  381. char *curdir; // = nullstr; /* current working directory */
  382. char *physdir; // = nullstr; /* physical working directory */
  383. char *arg0; /* value of $0 */
  384. struct jmploc *exception_handler;
  385. volatile int suppress_int; /* counter */
  386. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  387. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  388. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  389. smallint exception_type; /* kind of exception: */
  390. #define EXINT 0 /* SIGINT received */
  391. #define EXERROR 1 /* a generic error */
  392. #define EXEND 3 /* exit the shell */
  393. #define EXEXIT 4 /* exit the shell via exitcmd */
  394. char nullstr[1]; /* zero length string */
  395. char optlist[NOPTS];
  396. #define eflag optlist[0]
  397. #define fflag optlist[1]
  398. #define Iflag optlist[2]
  399. #define iflag optlist[3]
  400. #define mflag optlist[4]
  401. #define nflag optlist[5]
  402. #define sflag optlist[6]
  403. #define cflag optlist[7]
  404. #define xflag optlist[8]
  405. #define vflag optlist[9]
  406. #define Cflag optlist[10]
  407. #define aflag optlist[11]
  408. #define bflag optlist[12]
  409. #define uflag optlist[13]
  410. #define viflag optlist[14]
  411. #if BASH_PIPEFAIL
  412. # define pipefail optlist[15]
  413. #else
  414. # define pipefail 0
  415. #endif
  416. #if DEBUG
  417. # define nolog optlist[15 + BASH_PIPEFAIL]
  418. # define debug optlist[16 + BASH_PIPEFAIL]
  419. #endif
  420. /* trap handler commands */
  421. /*
  422. * Sigmode records the current value of the signal handlers for the various
  423. * modes. A value of zero means that the current handler is not known.
  424. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  425. */
  426. char sigmode[NSIG - 1];
  427. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  428. #define S_CATCH 2 /* signal is caught */
  429. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  430. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  431. /* indicates specified signal received */
  432. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  433. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  434. char *trap[NSIG];
  435. char **trap_ptr; /* used only by "trap hack" */
  436. /* Rarely referenced stuff */
  437. #if ENABLE_ASH_RANDOM_SUPPORT
  438. random_t random_gen;
  439. #endif
  440. pid_t backgndpid; /* pid of last background process */
  441. };
  442. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  443. #define G_misc (*ash_ptr_to_globals_misc)
  444. #define exitstatus (G_misc.exitstatus )
  445. #define back_exitstatus (G_misc.back_exitstatus )
  446. #define job_warning (G_misc.job_warning)
  447. #define savestatus (G_misc.savestatus )
  448. #define rootpid (G_misc.rootpid )
  449. #define shlvl (G_misc.shlvl )
  450. #define errlinno (G_misc.errlinno )
  451. #define minusc (G_misc.minusc )
  452. #define curdir (G_misc.curdir )
  453. #define physdir (G_misc.physdir )
  454. #define arg0 (G_misc.arg0 )
  455. #define exception_handler (G_misc.exception_handler)
  456. #define exception_type (G_misc.exception_type )
  457. #define suppress_int (G_misc.suppress_int )
  458. #define pending_int (G_misc.pending_int )
  459. #define got_sigchld (G_misc.got_sigchld )
  460. #define pending_sig (G_misc.pending_sig )
  461. #define nullstr (G_misc.nullstr )
  462. #define optlist (G_misc.optlist )
  463. #define sigmode (G_misc.sigmode )
  464. #define gotsig (G_misc.gotsig )
  465. #define may_have_traps (G_misc.may_have_traps )
  466. #define trap (G_misc.trap )
  467. #define trap_ptr (G_misc.trap_ptr )
  468. #define random_gen (G_misc.random_gen )
  469. #define backgndpid (G_misc.backgndpid )
  470. #define INIT_G_misc() do { \
  471. (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
  472. barrier(); \
  473. savestatus = -1; \
  474. curdir = nullstr; \
  475. physdir = nullstr; \
  476. trap_ptr = trap; \
  477. } while (0)
  478. /* ============ DEBUG */
  479. #if DEBUG
  480. static void trace_printf(const char *fmt, ...);
  481. static void trace_vprintf(const char *fmt, va_list va);
  482. # define TRACE(param) trace_printf param
  483. # define TRACEV(param) trace_vprintf param
  484. # define close(fd) do { \
  485. int dfd = (fd); \
  486. if (close(dfd) < 0) \
  487. bb_error_msg("bug on %d: closing %d(0x%x)", \
  488. __LINE__, dfd, dfd); \
  489. } while (0)
  490. #else
  491. # define TRACE(param)
  492. # define TRACEV(param)
  493. #endif
  494. /* ============ Utility functions */
  495. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  496. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  497. static int
  498. isdigit_str9(const char *str)
  499. {
  500. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  501. while (--maxlen && isdigit(*str))
  502. str++;
  503. return (*str == '\0');
  504. }
  505. static const char *
  506. var_end(const char *var)
  507. {
  508. while (*var)
  509. if (*var++ == '=')
  510. break;
  511. return var;
  512. }
  513. /* ============ Parser data */
  514. /*
  515. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  516. */
  517. struct strlist {
  518. struct strlist *next;
  519. char *text;
  520. };
  521. struct alias;
  522. struct strpush {
  523. struct strpush *prev; /* preceding string on stack */
  524. char *prev_string;
  525. int prev_left_in_line;
  526. #if ENABLE_ASH_ALIAS
  527. struct alias *ap; /* if push was associated with an alias */
  528. #endif
  529. char *string; /* remember the string since it may change */
  530. /* Remember last two characters for pungetc. */
  531. int lastc[2];
  532. /* Number of outstanding calls to pungetc. */
  533. int unget;
  534. };
  535. /*
  536. * The parsefile structure pointed to by the global variable parsefile
  537. * contains information about the current file being read.
  538. */
  539. struct parsefile {
  540. struct parsefile *prev; /* preceding file on stack */
  541. int linno; /* current line */
  542. int pf_fd; /* file descriptor (or -1 if string) */
  543. int left_in_line; /* number of chars left in this line */
  544. int left_in_buffer; /* number of chars left in this buffer past the line */
  545. char *next_to_pgetc; /* next char in buffer */
  546. char *buf; /* input buffer */
  547. struct strpush *strpush; /* for pushing strings at this level */
  548. struct strpush basestrpush; /* so pushing one is fast */
  549. /* Remember last two characters for pungetc. */
  550. int lastc[2];
  551. /* Number of outstanding calls to pungetc. */
  552. int unget;
  553. };
  554. static struct parsefile basepf; /* top level input file */
  555. static struct parsefile *g_parsefile = &basepf; /* current input file */
  556. static char *commandname; /* currently executing command */
  557. /* ============ Interrupts / exceptions */
  558. static void exitshell(void) NORETURN;
  559. /*
  560. * These macros allow the user to suspend the handling of interrupt signals
  561. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  562. * much more efficient and portable. (But hacking the kernel is so much
  563. * more fun than worrying about efficiency and portability. :-))
  564. */
  565. #if DEBUG_INTONOFF
  566. # define INT_OFF do { \
  567. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  568. suppress_int++; \
  569. barrier(); \
  570. } while (0)
  571. #else
  572. # define INT_OFF do { \
  573. suppress_int++; \
  574. barrier(); \
  575. } while (0)
  576. #endif
  577. /*
  578. * Called to raise an exception. Since C doesn't include exceptions, we
  579. * just do a longjmp to the exception handler. The type of exception is
  580. * stored in the global variable "exception_type".
  581. */
  582. static void raise_exception(int) NORETURN;
  583. static void
  584. raise_exception(int e)
  585. {
  586. #if DEBUG
  587. if (exception_handler == NULL)
  588. abort();
  589. #endif
  590. INT_OFF;
  591. exception_type = e;
  592. longjmp(exception_handler->loc, 1);
  593. }
  594. #if DEBUG
  595. #define raise_exception(e) do { \
  596. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  597. raise_exception(e); \
  598. } while (0)
  599. #endif
  600. /*
  601. * Called when a SIGINT is received. (If the user specifies
  602. * that SIGINT is to be trapped or ignored using the trap builtin, then
  603. * this routine is not called.) Suppressint is nonzero when interrupts
  604. * are held using the INT_OFF macro. (The test for iflag is just
  605. * defensive programming.)
  606. */
  607. static void raise_interrupt(void) NORETURN;
  608. static void
  609. raise_interrupt(void)
  610. {
  611. pending_int = 0;
  612. /* Signal is not automatically unmasked after it is raised,
  613. * do it ourself - unmask all signals */
  614. sigprocmask_allsigs(SIG_UNBLOCK);
  615. /* pending_sig = 0; - now done in signal_handler() */
  616. if (!(rootshell && iflag)) {
  617. /* Kill ourself with SIGINT */
  618. signal(SIGINT, SIG_DFL);
  619. raise(SIGINT);
  620. }
  621. /* bash: ^C even on empty command line sets $? */
  622. exitstatus = SIGINT + 128;
  623. raise_exception(EXINT);
  624. /* NOTREACHED */
  625. }
  626. #if DEBUG
  627. #define raise_interrupt() do { \
  628. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  629. raise_interrupt(); \
  630. } while (0)
  631. #endif
  632. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  633. int_on(void)
  634. {
  635. barrier();
  636. if (--suppress_int == 0 && pending_int) {
  637. raise_interrupt();
  638. }
  639. }
  640. #if DEBUG_INTONOFF
  641. # define INT_ON do { \
  642. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  643. int_on(); \
  644. } while (0)
  645. #else
  646. # define INT_ON int_on()
  647. #endif
  648. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  649. force_int_on(void)
  650. {
  651. barrier();
  652. suppress_int = 0;
  653. if (pending_int)
  654. raise_interrupt();
  655. }
  656. #define FORCE_INT_ON force_int_on()
  657. #define SAVE_INT(v) ((v) = suppress_int)
  658. #define RESTORE_INT(v) do { \
  659. barrier(); \
  660. suppress_int = (v); \
  661. if (suppress_int == 0 && pending_int) \
  662. raise_interrupt(); \
  663. } while (0)
  664. /* ============ Stdout/stderr output */
  665. static void
  666. outstr(const char *p, FILE *file)
  667. {
  668. INT_OFF;
  669. fputs(p, file);
  670. INT_ON;
  671. }
  672. static void
  673. flush_stdout_stderr(void)
  674. {
  675. INT_OFF;
  676. fflush_all();
  677. INT_ON;
  678. }
  679. /* Was called outcslow(c,FILE*), but c was always '\n' */
  680. static void
  681. newline_and_flush(FILE *dest)
  682. {
  683. INT_OFF;
  684. putc('\n', dest);
  685. fflush(dest);
  686. INT_ON;
  687. }
  688. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  689. static int
  690. out1fmt(const char *fmt, ...)
  691. {
  692. va_list ap;
  693. int r;
  694. INT_OFF;
  695. va_start(ap, fmt);
  696. r = vprintf(fmt, ap);
  697. va_end(ap);
  698. INT_ON;
  699. return r;
  700. }
  701. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  702. static int
  703. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  704. {
  705. va_list ap;
  706. int ret;
  707. INT_OFF;
  708. va_start(ap, fmt);
  709. ret = vsnprintf(outbuf, length, fmt, ap);
  710. va_end(ap);
  711. INT_ON;
  712. return ret > (int)length ? length : ret;
  713. }
  714. static void
  715. out1str(const char *p)
  716. {
  717. outstr(p, stdout);
  718. }
  719. static void
  720. out2str(const char *p)
  721. {
  722. outstr(p, stderr);
  723. flush_stdout_stderr();
  724. }
  725. /* ============ Parser structures */
  726. /* control characters in argument strings */
  727. #define CTL_FIRST CTLESC
  728. #define CTLESC ((unsigned char)'\201') /* escape next character */
  729. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  730. #define CTLENDVAR ((unsigned char)'\203')
  731. #define CTLBACKQ ((unsigned char)'\204')
  732. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  733. #define CTLENDARI ((unsigned char)'\207')
  734. #define CTLQUOTEMARK ((unsigned char)'\210')
  735. #define CTL_LAST CTLQUOTEMARK
  736. #if BASH_PROCESS_SUBST
  737. # define CTLTOPROC ((unsigned char)'\211')
  738. # define CTLFROMPROC ((unsigned char)'\212')
  739. # undef CTL_LAST
  740. # define CTL_LAST CTLFROMPROC
  741. #endif
  742. /* variable substitution byte (follows CTLVAR) */
  743. #define VSTYPE 0x0f /* type of variable substitution */
  744. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  745. /* values of VSTYPE field */
  746. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  747. #define VSMINUS 0x2 /* ${var-text} */
  748. #define VSPLUS 0x3 /* ${var+text} */
  749. #define VSQUESTION 0x4 /* ${var?message} */
  750. #define VSASSIGN 0x5 /* ${var=text} */
  751. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  752. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  753. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  754. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  755. #define VSLENGTH 0xa /* ${#var} */
  756. #if BASH_SUBSTR
  757. #define VSSUBSTR 0xc /* ${var:position:length} */
  758. #endif
  759. #if BASH_PATTERN_SUBST
  760. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  761. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  762. #endif
  763. static const char dolatstr[] ALIGN1 = {
  764. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  765. };
  766. #define DOLATSTRLEN 6
  767. #define NCMD 0
  768. #define NPIPE 1
  769. #define NREDIR 2
  770. #define NBACKGND 3
  771. #define NSUBSHELL 4
  772. #define NAND 5
  773. #define NOR 6
  774. #define NSEMI 7
  775. #define NIF 8
  776. #define NWHILE 9
  777. #define NUNTIL 10
  778. #define NFOR 11
  779. #define NCASE 12
  780. #define NCLIST 13
  781. #define NDEFUN 14
  782. #define NARG 15
  783. #define NTO 16
  784. #if BASH_REDIR_OUTPUT
  785. #define NTO2 17
  786. #endif
  787. #define NCLOBBER 18
  788. #define NFROM 19
  789. #define NFROMTO 20
  790. #define NAPPEND 21
  791. #define NTOFD 22
  792. #define NFROMFD 23
  793. #define NHERE 24
  794. #define NXHERE 25
  795. #define NNOT 26
  796. #define N_NUMBER 27
  797. union node;
  798. struct ncmd {
  799. smallint type; /* Nxxxx */
  800. int linno;
  801. union node *assign;
  802. union node *args;
  803. union node *redirect;
  804. };
  805. struct npipe {
  806. smallint type;
  807. smallint pipe_backgnd;
  808. struct nodelist *cmdlist;
  809. };
  810. struct nredir {
  811. smallint type;
  812. int linno;
  813. union node *n;
  814. union node *redirect;
  815. };
  816. struct nbinary {
  817. smallint type;
  818. union node *ch1;
  819. union node *ch2;
  820. };
  821. struct nif {
  822. smallint type;
  823. union node *test;
  824. union node *ifpart;
  825. union node *elsepart;
  826. };
  827. struct nfor {
  828. smallint type;
  829. int linno;
  830. union node *args;
  831. union node *body;
  832. char *var;
  833. };
  834. struct ncase {
  835. smallint type;
  836. int linno;
  837. union node *expr;
  838. union node *cases;
  839. };
  840. struct nclist {
  841. smallint type;
  842. union node *next;
  843. union node *pattern;
  844. union node *body;
  845. };
  846. struct ndefun {
  847. smallint type;
  848. int linno;
  849. char *text;
  850. union node *body;
  851. };
  852. struct narg {
  853. smallint type;
  854. union node *next;
  855. char *text;
  856. struct nodelist *backquote;
  857. };
  858. /* nfile and ndup layout must match!
  859. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  860. * that it is actually NTO2 (>&file), and change its type.
  861. */
  862. struct nfile {
  863. smallint type;
  864. union node *next;
  865. int fd;
  866. int _unused_dupfd;
  867. union node *fname;
  868. char *expfname;
  869. };
  870. struct ndup {
  871. smallint type;
  872. union node *next;
  873. int fd;
  874. int dupfd;
  875. union node *vname;
  876. char *_unused_expfname;
  877. };
  878. struct nhere {
  879. smallint type;
  880. union node *next;
  881. int fd;
  882. union node *doc;
  883. };
  884. struct nnot {
  885. smallint type;
  886. union node *com;
  887. };
  888. union node {
  889. smallint type;
  890. struct ncmd ncmd;
  891. struct npipe npipe;
  892. struct nredir nredir;
  893. struct nbinary nbinary;
  894. struct nif nif;
  895. struct nfor nfor;
  896. struct ncase ncase;
  897. struct nclist nclist;
  898. struct ndefun ndefun;
  899. struct narg narg;
  900. struct nfile nfile;
  901. struct ndup ndup;
  902. struct nhere nhere;
  903. struct nnot nnot;
  904. };
  905. /*
  906. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  907. * It must be distinct from NULL.
  908. */
  909. #define NODE_EOF ((union node *) -1L)
  910. struct nodelist {
  911. struct nodelist *next;
  912. union node *n;
  913. };
  914. struct funcnode {
  915. int count;
  916. union node n;
  917. };
  918. /*
  919. * Free a parse tree.
  920. */
  921. static void
  922. freefunc(struct funcnode *f)
  923. {
  924. if (f && --f->count < 0)
  925. free(f);
  926. }
  927. /* ============ Debugging output */
  928. #if DEBUG
  929. static FILE *tracefile;
  930. static void
  931. trace_printf(const char *fmt, ...)
  932. {
  933. va_list va;
  934. if (debug != 1)
  935. return;
  936. if (DEBUG_TIME)
  937. fprintf(tracefile, "%u ", (int) time(NULL));
  938. if (DEBUG_PID)
  939. fprintf(tracefile, "[%u] ", (int) getpid());
  940. if (DEBUG_SIG)
  941. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  942. va_start(va, fmt);
  943. vfprintf(tracefile, fmt, va);
  944. va_end(va);
  945. }
  946. static void
  947. trace_vprintf(const char *fmt, va_list va)
  948. {
  949. if (debug != 1)
  950. return;
  951. vfprintf(tracefile, fmt, va);
  952. fprintf(tracefile, "\n");
  953. }
  954. static void
  955. trace_puts(const char *s)
  956. {
  957. if (debug != 1)
  958. return;
  959. fputs(s, tracefile);
  960. }
  961. static void
  962. trace_puts_quoted(char *s)
  963. {
  964. char *p;
  965. char c;
  966. if (debug != 1)
  967. return;
  968. putc('"', tracefile);
  969. for (p = s; *p; p++) {
  970. switch ((unsigned char)*p) {
  971. case '\n': c = 'n'; goto backslash;
  972. case '\t': c = 't'; goto backslash;
  973. case '\r': c = 'r'; goto backslash;
  974. case '\"': c = '\"'; goto backslash;
  975. case '\\': c = '\\'; goto backslash;
  976. case CTLESC: c = 'e'; goto backslash;
  977. case CTLVAR: c = 'v'; goto backslash;
  978. case CTLBACKQ: c = 'q'; goto backslash;
  979. #if BASH_PROCESS_SUBST
  980. case CTLTOPROC: c = 'p'; goto backslash;
  981. case CTLFROMPROC: c = 'P'; goto backslash;
  982. #endif
  983. backslash:
  984. putc('\\', tracefile);
  985. putc(c, tracefile);
  986. break;
  987. default:
  988. if (*p >= ' ' && *p <= '~')
  989. putc(*p, tracefile);
  990. else {
  991. putc('\\', tracefile);
  992. putc((*p >> 6) & 03, tracefile);
  993. putc((*p >> 3) & 07, tracefile);
  994. putc(*p & 07, tracefile);
  995. }
  996. break;
  997. }
  998. }
  999. putc('"', tracefile);
  1000. }
  1001. static void
  1002. trace_puts_args(char **ap)
  1003. {
  1004. if (debug != 1)
  1005. return;
  1006. if (!*ap)
  1007. return;
  1008. while (1) {
  1009. trace_puts_quoted(*ap);
  1010. if (!*++ap) {
  1011. putc('\n', tracefile);
  1012. break;
  1013. }
  1014. putc(' ', tracefile);
  1015. }
  1016. }
  1017. static void
  1018. opentrace(void)
  1019. {
  1020. char s[100];
  1021. #ifdef O_APPEND
  1022. int flags;
  1023. #endif
  1024. if (debug != 1) {
  1025. if (tracefile)
  1026. fflush(tracefile);
  1027. /* leave open because libedit might be using it */
  1028. return;
  1029. }
  1030. strcpy(s, "./trace");
  1031. if (tracefile) {
  1032. if (!freopen(s, "a", tracefile)) {
  1033. fprintf(stderr, "Can't re-open %s\n", s);
  1034. debug = 0;
  1035. return;
  1036. }
  1037. } else {
  1038. tracefile = fopen(s, "a");
  1039. if (tracefile == NULL) {
  1040. fprintf(stderr, "Can't open %s\n", s);
  1041. debug = 0;
  1042. return;
  1043. }
  1044. }
  1045. #ifdef O_APPEND
  1046. flags = fcntl(fileno(tracefile), F_GETFL);
  1047. if (flags >= 0)
  1048. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1049. #endif
  1050. setlinebuf(tracefile);
  1051. fputs("\nTracing started.\n", tracefile);
  1052. }
  1053. static void
  1054. indent(int amount, char *pfx, FILE *fp)
  1055. {
  1056. int i;
  1057. for (i = 0; i < amount; i++) {
  1058. if (pfx && i == amount - 1)
  1059. fputs(pfx, fp);
  1060. putc('\t', fp);
  1061. }
  1062. }
  1063. /* little circular references here... */
  1064. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1065. static void
  1066. sharg(union node *arg, FILE *fp)
  1067. {
  1068. char *p;
  1069. struct nodelist *bqlist;
  1070. unsigned char subtype;
  1071. if (arg->type != NARG) {
  1072. out1fmt("<node type %d>\n", arg->type);
  1073. abort();
  1074. }
  1075. bqlist = arg->narg.backquote;
  1076. for (p = arg->narg.text; *p; p++) {
  1077. switch ((unsigned char)*p) {
  1078. case CTLESC:
  1079. p++;
  1080. putc(*p, fp);
  1081. break;
  1082. case CTLVAR:
  1083. putc('$', fp);
  1084. putc('{', fp);
  1085. subtype = *++p;
  1086. if (subtype == VSLENGTH)
  1087. putc('#', fp);
  1088. while (*p != '=') {
  1089. putc(*p, fp);
  1090. p++;
  1091. }
  1092. if (subtype & VSNUL)
  1093. putc(':', fp);
  1094. switch (subtype & VSTYPE) {
  1095. case VSNORMAL:
  1096. putc('}', fp);
  1097. break;
  1098. case VSMINUS:
  1099. putc('-', fp);
  1100. break;
  1101. case VSPLUS:
  1102. putc('+', fp);
  1103. break;
  1104. case VSQUESTION:
  1105. putc('?', fp);
  1106. break;
  1107. case VSASSIGN:
  1108. putc('=', fp);
  1109. break;
  1110. case VSTRIMLEFT:
  1111. putc('#', fp);
  1112. break;
  1113. case VSTRIMLEFTMAX:
  1114. putc('#', fp);
  1115. putc('#', fp);
  1116. break;
  1117. case VSTRIMRIGHT:
  1118. putc('%', fp);
  1119. break;
  1120. case VSTRIMRIGHTMAX:
  1121. putc('%', fp);
  1122. putc('%', fp);
  1123. break;
  1124. case VSLENGTH:
  1125. break;
  1126. default:
  1127. out1fmt("<subtype %d>", subtype);
  1128. }
  1129. break;
  1130. case CTLENDVAR:
  1131. putc('}', fp);
  1132. break;
  1133. #if BASH_PROCESS_SUBST
  1134. case CTLTOPROC:
  1135. putc('>', fp);
  1136. goto backq;
  1137. case CTLFROMPROC:
  1138. putc('<', fp);
  1139. goto backq;
  1140. #endif
  1141. case CTLBACKQ:
  1142. putc('$', fp);
  1143. IF_BASH_PROCESS_SUBST(backq:)
  1144. putc('(', fp);
  1145. shtree(bqlist->n, -1, NULL, fp);
  1146. putc(')', fp);
  1147. break;
  1148. default:
  1149. putc(*p, fp);
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. static void
  1155. shcmd(union node *cmd, FILE *fp)
  1156. {
  1157. union node *np;
  1158. int first;
  1159. const char *s;
  1160. int dftfd;
  1161. first = 1;
  1162. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1163. if (!first)
  1164. putc(' ', fp);
  1165. sharg(np, fp);
  1166. first = 0;
  1167. }
  1168. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1169. if (!first)
  1170. putc(' ', fp);
  1171. dftfd = 0;
  1172. switch (np->nfile.type) {
  1173. case NTO: s = ">>"+1; dftfd = 1; break;
  1174. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1175. case NAPPEND: s = ">>"; dftfd = 1; break;
  1176. #if BASH_REDIR_OUTPUT
  1177. case NTO2:
  1178. #endif
  1179. case NTOFD: s = ">&"; dftfd = 1; break;
  1180. case NFROM: s = "<"; break;
  1181. case NFROMFD: s = "<&"; break;
  1182. case NFROMTO: s = "<>"; break;
  1183. default: s = "*error*"; break;
  1184. }
  1185. if (np->nfile.fd != dftfd)
  1186. fprintf(fp, "%d", np->nfile.fd);
  1187. fputs(s, fp);
  1188. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1189. fprintf(fp, "%d", np->ndup.dupfd);
  1190. } else {
  1191. sharg(np->nfile.fname, fp);
  1192. }
  1193. first = 0;
  1194. }
  1195. }
  1196. static void
  1197. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1198. {
  1199. struct nodelist *lp;
  1200. const char *s;
  1201. if (n == NULL)
  1202. return;
  1203. indent(ind, pfx, fp);
  1204. if (n == NODE_EOF) {
  1205. fputs("<EOF>", fp);
  1206. return;
  1207. }
  1208. switch (n->type) {
  1209. case NSEMI:
  1210. s = "; ";
  1211. goto binop;
  1212. case NAND:
  1213. s = " && ";
  1214. goto binop;
  1215. case NOR:
  1216. s = " || ";
  1217. binop:
  1218. shtree(n->nbinary.ch1, ind, NULL, fp);
  1219. /* if (ind < 0) */
  1220. fputs(s, fp);
  1221. shtree(n->nbinary.ch2, ind, NULL, fp);
  1222. break;
  1223. case NCMD:
  1224. shcmd(n, fp);
  1225. if (ind >= 0)
  1226. putc('\n', fp);
  1227. break;
  1228. case NPIPE:
  1229. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1230. shtree(lp->n, 0, NULL, fp);
  1231. if (lp->next)
  1232. fputs(" | ", fp);
  1233. }
  1234. if (n->npipe.pipe_backgnd)
  1235. fputs(" &", fp);
  1236. if (ind >= 0)
  1237. putc('\n', fp);
  1238. break;
  1239. default:
  1240. fprintf(fp, "<node type %d>", n->type);
  1241. if (ind >= 0)
  1242. putc('\n', fp);
  1243. break;
  1244. }
  1245. }
  1246. static void
  1247. showtree(union node *n)
  1248. {
  1249. trace_puts("showtree called\n");
  1250. shtree(n, 1, NULL, stderr);
  1251. }
  1252. #endif /* DEBUG */
  1253. /* ============ Message printing */
  1254. static void
  1255. ash_vmsg(const char *msg, va_list ap)
  1256. {
  1257. fprintf(stderr, "%s: ", arg0);
  1258. if (commandname) {
  1259. if (strcmp(arg0, commandname))
  1260. fprintf(stderr, "%s: ", commandname);
  1261. if (!iflag || g_parsefile->pf_fd > 0)
  1262. fprintf(stderr, "line %d: ", errlinno);
  1263. }
  1264. vfprintf(stderr, msg, ap);
  1265. newline_and_flush(stderr);
  1266. }
  1267. /*
  1268. * Exverror is called to raise the error exception. If the second argument
  1269. * is not NULL then error prints an error message using printf style
  1270. * formatting. It then raises the error exception.
  1271. */
  1272. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1273. static void
  1274. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1275. {
  1276. #if DEBUG
  1277. if (msg) {
  1278. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1279. TRACEV((msg, ap));
  1280. } else
  1281. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1282. if (msg)
  1283. #endif
  1284. ash_vmsg(msg, ap);
  1285. flush_stdout_stderr();
  1286. raise_exception(cond);
  1287. /* NOTREACHED */
  1288. }
  1289. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1290. static void
  1291. ash_msg_and_raise_error(const char *msg, ...)
  1292. {
  1293. va_list ap;
  1294. exitstatus = 2;
  1295. va_start(ap, msg);
  1296. ash_vmsg_and_raise(EXERROR, msg, ap);
  1297. /* NOTREACHED */
  1298. va_end(ap);
  1299. }
  1300. /*
  1301. * 'fmt' must be a string literal.
  1302. */
  1303. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1304. static void raise_error_syntax(const char *) NORETURN;
  1305. static void
  1306. raise_error_syntax(const char *msg)
  1307. {
  1308. errlinno = g_parsefile->linno;
  1309. ash_msg_and_raise_error("syntax error: %s", msg);
  1310. /* NOTREACHED */
  1311. }
  1312. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1313. static void
  1314. ash_msg_and_raise(int cond, const char *msg, ...)
  1315. {
  1316. va_list ap;
  1317. va_start(ap, msg);
  1318. ash_vmsg_and_raise(cond, msg, ap);
  1319. /* NOTREACHED */
  1320. va_end(ap);
  1321. }
  1322. /*
  1323. * error/warning routines for external builtins
  1324. */
  1325. static void
  1326. ash_msg(const char *fmt, ...)
  1327. {
  1328. va_list ap;
  1329. va_start(ap, fmt);
  1330. ash_vmsg(fmt, ap);
  1331. va_end(ap);
  1332. }
  1333. /*
  1334. * Return a string describing an error. The returned string may be a
  1335. * pointer to a static buffer that will be overwritten on the next call.
  1336. * Action describes the operation that got the error.
  1337. */
  1338. static const char *
  1339. errmsg(int e, const char *em)
  1340. {
  1341. if (e == ENOENT || e == ENOTDIR) {
  1342. return em;
  1343. }
  1344. return strerror(e);
  1345. }
  1346. /* ============ Memory allocation */
  1347. #if 0
  1348. /* I consider these wrappers nearly useless:
  1349. * ok, they return you to nearest exception handler, but
  1350. * how much memory do you leak in the process, making
  1351. * memory starvation worse?
  1352. */
  1353. static void *
  1354. ckrealloc(void * p, size_t nbytes)
  1355. {
  1356. p = realloc(p, nbytes);
  1357. if (!p)
  1358. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1359. return p;
  1360. }
  1361. static void *
  1362. ckmalloc(size_t nbytes)
  1363. {
  1364. return ckrealloc(NULL, nbytes);
  1365. }
  1366. static void *
  1367. ckzalloc(size_t nbytes)
  1368. {
  1369. return memset(ckmalloc(nbytes), 0, nbytes);
  1370. }
  1371. static char *
  1372. ckstrdup(const char *s)
  1373. {
  1374. char *p = strdup(s);
  1375. if (!p)
  1376. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1377. return p;
  1378. }
  1379. #else
  1380. /* Using bbox equivalents. They exit if out of memory */
  1381. # define ckrealloc xrealloc
  1382. # define ckmalloc xmalloc
  1383. # define ckzalloc xzalloc
  1384. # define ckstrdup xstrdup
  1385. #endif
  1386. /*
  1387. * It appears that grabstackstr() will barf with such alignments
  1388. * because stalloc() will return a string allocated in a new stackblock.
  1389. */
  1390. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1391. enum {
  1392. /* Most machines require the value returned from malloc to be aligned
  1393. * in some way. The following macro will get this right
  1394. * on many machines. */
  1395. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1396. /* Minimum size of a block */
  1397. MINSIZE = SHELL_ALIGN(504),
  1398. };
  1399. struct stack_block {
  1400. struct stack_block *prev;
  1401. char space[MINSIZE];
  1402. };
  1403. struct stackmark {
  1404. struct stack_block *stackp;
  1405. char *stacknxt;
  1406. size_t stacknleft;
  1407. };
  1408. struct globals_memstack {
  1409. struct stack_block *g_stackp; // = &stackbase;
  1410. char *g_stacknxt; // = stackbase.space;
  1411. char *sstrend; // = stackbase.space + MINSIZE;
  1412. size_t g_stacknleft; // = MINSIZE;
  1413. struct stack_block stackbase;
  1414. };
  1415. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1416. #define G_memstack (*ash_ptr_to_globals_memstack)
  1417. #define g_stackp (G_memstack.g_stackp )
  1418. #define g_stacknxt (G_memstack.g_stacknxt )
  1419. #define sstrend (G_memstack.sstrend )
  1420. #define g_stacknleft (G_memstack.g_stacknleft)
  1421. #define stackbase (G_memstack.stackbase )
  1422. #define INIT_G_memstack() do { \
  1423. (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
  1424. barrier(); \
  1425. g_stackp = &stackbase; \
  1426. g_stacknxt = stackbase.space; \
  1427. g_stacknleft = MINSIZE; \
  1428. sstrend = stackbase.space + MINSIZE; \
  1429. } while (0)
  1430. #define stackblock() ((void *)g_stacknxt)
  1431. #define stackblocksize() g_stacknleft
  1432. /*
  1433. * Parse trees for commands are allocated in lifo order, so we use a stack
  1434. * to make this more efficient, and also to avoid all sorts of exception
  1435. * handling code to handle interrupts in the middle of a parse.
  1436. *
  1437. * The size 504 was chosen because the Ultrix malloc handles that size
  1438. * well.
  1439. */
  1440. static void *
  1441. stalloc(size_t nbytes)
  1442. {
  1443. char *p;
  1444. size_t aligned;
  1445. aligned = SHELL_ALIGN(nbytes);
  1446. if (aligned > g_stacknleft) {
  1447. size_t len;
  1448. size_t blocksize;
  1449. struct stack_block *sp;
  1450. blocksize = aligned;
  1451. if (blocksize < MINSIZE)
  1452. blocksize = MINSIZE;
  1453. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1454. if (len < blocksize)
  1455. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1456. INT_OFF;
  1457. sp = ckmalloc(len);
  1458. sp->prev = g_stackp;
  1459. g_stacknxt = sp->space;
  1460. g_stacknleft = blocksize;
  1461. sstrend = g_stacknxt + blocksize;
  1462. g_stackp = sp;
  1463. INT_ON;
  1464. }
  1465. p = g_stacknxt;
  1466. g_stacknxt += aligned;
  1467. g_stacknleft -= aligned;
  1468. return p;
  1469. }
  1470. static void *
  1471. stzalloc(size_t nbytes)
  1472. {
  1473. return memset(stalloc(nbytes), 0, nbytes);
  1474. }
  1475. static void
  1476. stunalloc(void *p)
  1477. {
  1478. #if DEBUG
  1479. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1480. write(STDERR_FILENO, "stunalloc\n", 10);
  1481. abort();
  1482. }
  1483. #endif
  1484. g_stacknleft += g_stacknxt - (char *)p;
  1485. g_stacknxt = p;
  1486. }
  1487. /*
  1488. * Like strdup but works with the ash stack.
  1489. */
  1490. static char *
  1491. sstrdup(const char *p)
  1492. {
  1493. size_t len = strlen(p) + 1;
  1494. return memcpy(stalloc(len), p, len);
  1495. }
  1496. static ALWAYS_INLINE void
  1497. grabstackblock(size_t len)
  1498. {
  1499. stalloc(len);
  1500. }
  1501. static void
  1502. pushstackmark(struct stackmark *mark, size_t len)
  1503. {
  1504. mark->stackp = g_stackp;
  1505. mark->stacknxt = g_stacknxt;
  1506. mark->stacknleft = g_stacknleft;
  1507. grabstackblock(len);
  1508. }
  1509. static void
  1510. setstackmark(struct stackmark *mark)
  1511. {
  1512. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1513. }
  1514. static void
  1515. popstackmark(struct stackmark *mark)
  1516. {
  1517. struct stack_block *sp;
  1518. if (!mark->stackp)
  1519. return;
  1520. INT_OFF;
  1521. while (g_stackp != mark->stackp) {
  1522. sp = g_stackp;
  1523. g_stackp = sp->prev;
  1524. free(sp);
  1525. }
  1526. g_stacknxt = mark->stacknxt;
  1527. g_stacknleft = mark->stacknleft;
  1528. sstrend = mark->stacknxt + mark->stacknleft;
  1529. INT_ON;
  1530. }
  1531. /*
  1532. * When the parser reads in a string, it wants to stick the string on the
  1533. * stack and only adjust the stack pointer when it knows how big the
  1534. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1535. * of space on top of the stack and stackblocklen returns the length of
  1536. * this block. Growstackblock will grow this space by at least one byte,
  1537. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1538. * part of the block that has been used.
  1539. */
  1540. static void
  1541. growstackblock(size_t min)
  1542. {
  1543. size_t newlen;
  1544. newlen = g_stacknleft * 2;
  1545. if (newlen < g_stacknleft)
  1546. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1547. min = SHELL_ALIGN(min | 128);
  1548. if (newlen < min)
  1549. newlen += min;
  1550. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1551. struct stack_block *sp;
  1552. struct stack_block *prevstackp;
  1553. size_t grosslen;
  1554. INT_OFF;
  1555. sp = g_stackp;
  1556. prevstackp = sp->prev;
  1557. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1558. sp = ckrealloc(sp, grosslen);
  1559. sp->prev = prevstackp;
  1560. g_stackp = sp;
  1561. g_stacknxt = sp->space;
  1562. g_stacknleft = newlen;
  1563. sstrend = sp->space + newlen;
  1564. INT_ON;
  1565. } else {
  1566. char *oldspace = g_stacknxt;
  1567. size_t oldlen = g_stacknleft;
  1568. char *p = stalloc(newlen);
  1569. /* free the space we just allocated */
  1570. g_stacknxt = memcpy(p, oldspace, oldlen);
  1571. g_stacknleft += newlen;
  1572. }
  1573. }
  1574. /*
  1575. * The following routines are somewhat easier to use than the above.
  1576. * The user declares a variable of type STACKSTR, which may be declared
  1577. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1578. * the user uses the macro STPUTC to add characters to the string. In
  1579. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1580. * grown as necessary. When the user is done, she can just leave the
  1581. * string there and refer to it using stackblock(). Or she can allocate
  1582. * the space for it using grabstackstr(). If it is necessary to allow
  1583. * someone else to use the stack temporarily and then continue to grow
  1584. * the string, the user should use grabstack to allocate the space, and
  1585. * then call ungrabstr(p) to return to the previous mode of operation.
  1586. *
  1587. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1588. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1589. * is space for at least one character.
  1590. */
  1591. static void *
  1592. growstackstr(void)
  1593. {
  1594. size_t len = stackblocksize();
  1595. growstackblock(0);
  1596. return (char *)stackblock() + len;
  1597. }
  1598. static char *
  1599. growstackto(size_t len)
  1600. {
  1601. if (stackblocksize() < len)
  1602. growstackblock(len);
  1603. return stackblock();
  1604. }
  1605. /*
  1606. * Called from CHECKSTRSPACE.
  1607. */
  1608. static char *
  1609. makestrspace(size_t newlen, char *p)
  1610. {
  1611. size_t len = p - g_stacknxt;
  1612. return growstackto(len + newlen) + len;
  1613. }
  1614. static char *
  1615. stnputs(const char *s, size_t n, char *p)
  1616. {
  1617. p = makestrspace(n, p);
  1618. p = (char *)mempcpy(p, s, n);
  1619. return p;
  1620. }
  1621. static char *
  1622. stack_putstr(const char *s, char *p)
  1623. {
  1624. return stnputs(s, strlen(s), p);
  1625. }
  1626. static char *
  1627. _STPUTC(int c, char *p)
  1628. {
  1629. if (p == sstrend)
  1630. p = growstackstr();
  1631. *p++ = c;
  1632. return p;
  1633. }
  1634. #define STARTSTACKSTR(p) ((p) = stackblock())
  1635. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1636. #define CHECKSTRSPACE(n, p) do { \
  1637. char *q = (p); \
  1638. size_t l = (n); \
  1639. size_t m = sstrend - q; \
  1640. if (l > m) \
  1641. (p) = makestrspace(l, q); \
  1642. } while (0)
  1643. #define USTPUTC(c, p) (*(p)++ = (c))
  1644. #define STACKSTRNUL(p) do { \
  1645. if ((p) == sstrend) \
  1646. (p) = growstackstr(); \
  1647. *(p) = '\0'; \
  1648. } while (0)
  1649. #define STUNPUTC(p) (--(p))
  1650. #define STTOPC(p) ((p)[-1])
  1651. #define STADJUST(amount, p) ((p) += (amount))
  1652. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1653. #define ungrabstackstr(s, p) stunalloc(s)
  1654. #define stackstrend() ((void *)sstrend)
  1655. /* ============ String helpers */
  1656. /*
  1657. * prefix -- see if pfx is a prefix of string.
  1658. */
  1659. static char *
  1660. prefix(const char *string, const char *pfx)
  1661. {
  1662. while (*pfx) {
  1663. if (*pfx++ != *string++)
  1664. return NULL;
  1665. }
  1666. return (char *) string;
  1667. }
  1668. /*
  1669. * Check for a valid number. This should be elsewhere.
  1670. */
  1671. static int
  1672. is_number(const char *p)
  1673. {
  1674. do {
  1675. if (!isdigit(*p))
  1676. return 0;
  1677. } while (*++p != '\0');
  1678. return 1;
  1679. }
  1680. /*
  1681. * Convert a string of digits to an integer, printing an error message on
  1682. * failure.
  1683. */
  1684. static int
  1685. number(const char *s)
  1686. {
  1687. if (!is_number(s))
  1688. ash_msg_and_raise_error(msg_illnum, s);
  1689. return atoi(s);
  1690. }
  1691. /*
  1692. * Produce a single quoted string suitable as input to the shell.
  1693. * The return string is allocated on the stack.
  1694. */
  1695. static char *
  1696. single_quote(const char *s)
  1697. {
  1698. char *p;
  1699. STARTSTACKSTR(p);
  1700. do {
  1701. char *q;
  1702. size_t len;
  1703. len = strchrnul(s, '\'') - s;
  1704. q = p = makestrspace(len + 3, p);
  1705. *q++ = '\'';
  1706. q = (char *)mempcpy(q, s, len);
  1707. *q++ = '\'';
  1708. s += len;
  1709. STADJUST(q - p, p);
  1710. if (*s != '\'')
  1711. break;
  1712. len = 0;
  1713. do len++; while (*++s == '\'');
  1714. q = p = makestrspace(len + 3, p);
  1715. *q++ = '"';
  1716. q = (char *)mempcpy(q, s - len, len);
  1717. *q++ = '"';
  1718. STADJUST(q - p, p);
  1719. } while (*s);
  1720. USTPUTC('\0', p);
  1721. return stackblock();
  1722. }
  1723. /*
  1724. * Produce a possibly single quoted string suitable as input to the shell.
  1725. * If quoting was done, the return string is allocated on the stack,
  1726. * otherwise a pointer to the original string is returned.
  1727. */
  1728. static const char *
  1729. maybe_single_quote(const char *s)
  1730. {
  1731. const char *p = s;
  1732. while (*p) {
  1733. /* Assuming ACSII */
  1734. /* quote ctrl_chars space !"#$%&'()* */
  1735. if (*p < '+')
  1736. goto need_quoting;
  1737. /* quote ;<=>? */
  1738. if (*p >= ';' && *p <= '?')
  1739. goto need_quoting;
  1740. /* quote `[\ */
  1741. if (*p == '`')
  1742. goto need_quoting;
  1743. if (*p == '[')
  1744. goto need_quoting;
  1745. if (*p == '\\')
  1746. goto need_quoting;
  1747. /* quote {|}~ DEL and high bytes */
  1748. if (*p > 'z')
  1749. goto need_quoting;
  1750. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1751. /* TODO: maybe avoid quoting % */
  1752. p++;
  1753. }
  1754. return s;
  1755. need_quoting:
  1756. return single_quote(s);
  1757. }
  1758. /* ============ nextopt */
  1759. static char **argptr; /* argument list for builtin commands */
  1760. static char *optionarg; /* set by nextopt (like getopt) */
  1761. static char *optptr; /* used by nextopt */
  1762. /*
  1763. * XXX - should get rid of. Have all builtins use getopt(3).
  1764. * The library getopt must have the BSD extension static variable
  1765. * "optreset", otherwise it can't be used within the shell safely.
  1766. *
  1767. * Standard option processing (a la getopt) for builtin routines.
  1768. * The only argument that is passed to nextopt is the option string;
  1769. * the other arguments are unnecessary. It returns the character,
  1770. * or '\0' on end of input.
  1771. */
  1772. static int
  1773. nextopt(const char *optstring)
  1774. {
  1775. char *p;
  1776. const char *q;
  1777. char c;
  1778. p = optptr;
  1779. if (p == NULL || *p == '\0') {
  1780. /* We ate entire "-param", take next one */
  1781. p = *argptr;
  1782. if (p == NULL)
  1783. return '\0';
  1784. if (*p != '-')
  1785. return '\0';
  1786. if (*++p == '\0') /* just "-" ? */
  1787. return '\0';
  1788. argptr++;
  1789. if (LONE_DASH(p)) /* "--" ? */
  1790. return '\0';
  1791. /* p => next "-param" */
  1792. }
  1793. /* p => some option char in the middle of a "-param" */
  1794. c = *p++;
  1795. for (q = optstring; *q != c;) {
  1796. if (*q == '\0')
  1797. ash_msg_and_raise_error("illegal option -%c", c);
  1798. if (*++q == ':')
  1799. q++;
  1800. }
  1801. if (*++q == ':') {
  1802. if (*p == '\0') {
  1803. p = *argptr++;
  1804. if (p == NULL)
  1805. ash_msg_and_raise_error("no arg for -%c option", c);
  1806. }
  1807. optionarg = p;
  1808. p = NULL;
  1809. }
  1810. optptr = p;
  1811. return c;
  1812. }
  1813. /* ============ Shell variables */
  1814. struct shparam {
  1815. int nparam; /* # of positional parameters (without $0) */
  1816. #if ENABLE_ASH_GETOPTS
  1817. int optind; /* next parameter to be processed by getopts */
  1818. int optoff; /* used by getopts */
  1819. #endif
  1820. unsigned char malloced; /* if parameter list dynamically allocated */
  1821. char **p; /* parameter list */
  1822. };
  1823. /*
  1824. * Free the list of positional parameters.
  1825. */
  1826. static void
  1827. freeparam(volatile struct shparam *param)
  1828. {
  1829. if (param->malloced) {
  1830. char **ap, **ap1;
  1831. ap = ap1 = param->p;
  1832. while (*ap)
  1833. free(*ap++);
  1834. free(ap1);
  1835. }
  1836. }
  1837. #if ENABLE_ASH_GETOPTS
  1838. static void FAST_FUNC getoptsreset(const char *value);
  1839. #endif
  1840. struct var {
  1841. struct var *next; /* next entry in hash list */
  1842. int flags; /* flags are defined above */
  1843. const char *var_text; /* name=value */
  1844. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1845. /* the variable gets set/unset */
  1846. };
  1847. struct localvar {
  1848. struct localvar *next; /* next local variable in list */
  1849. struct var *vp; /* the variable that was made local */
  1850. int flags; /* saved flags */
  1851. const char *text; /* saved text */
  1852. };
  1853. /* flags */
  1854. #define VEXPORT 0x01 /* variable is exported */
  1855. #define VREADONLY 0x02 /* variable cannot be modified */
  1856. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1857. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1858. #define VSTACK 0x10 /* text is allocated on the stack */
  1859. #define VUNSET 0x20 /* the variable is not set */
  1860. #define VNOFUNC 0x40 /* don't call the callback function */
  1861. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1862. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1863. #if ENABLE_ASH_RANDOM_SUPPORT
  1864. # define VDYNAMIC 0x200 /* dynamic variable */
  1865. #else
  1866. # define VDYNAMIC 0
  1867. #endif
  1868. /* Need to be before varinit_data[] */
  1869. #if ENABLE_LOCALE_SUPPORT
  1870. static void FAST_FUNC
  1871. change_lc_all(const char *value)
  1872. {
  1873. if (value && *value != '\0')
  1874. setlocale(LC_ALL, value);
  1875. }
  1876. static void FAST_FUNC
  1877. change_lc_ctype(const char *value)
  1878. {
  1879. if (value && *value != '\0')
  1880. setlocale(LC_CTYPE, value);
  1881. }
  1882. #endif
  1883. #if ENABLE_ASH_MAIL
  1884. static void chkmail(void);
  1885. static void changemail(const char *var_value) FAST_FUNC;
  1886. #else
  1887. # define chkmail() ((void)0)
  1888. #endif
  1889. static void changepath(const char *) FAST_FUNC;
  1890. #if ENABLE_ASH_RANDOM_SUPPORT
  1891. static void change_random(const char *) FAST_FUNC;
  1892. #endif
  1893. #if BASH_EPOCH_VARS
  1894. static void change_seconds(const char *) FAST_FUNC;
  1895. static void change_realtime(const char *) FAST_FUNC;
  1896. #endif
  1897. static const struct {
  1898. int flags;
  1899. const char *var_text;
  1900. void (*var_func)(const char *) FAST_FUNC;
  1901. } varinit_data[] ALIGN_PTR = {
  1902. /*
  1903. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1904. * some environment strings may be constant.
  1905. */
  1906. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1907. #if ENABLE_ASH_MAIL
  1908. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1909. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1910. #endif
  1911. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1912. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1913. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1914. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1915. #if ENABLE_ASH_GETOPTS
  1916. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1917. #endif
  1918. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1919. #if ENABLE_ASH_RANDOM_SUPPORT
  1920. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1921. #endif
  1922. #if BASH_EPOCH_VARS
  1923. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1924. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1925. #endif
  1926. #if ENABLE_LOCALE_SUPPORT
  1927. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1928. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1929. #endif
  1930. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1931. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1932. #endif
  1933. };
  1934. struct redirtab;
  1935. struct globals_var {
  1936. struct shparam shellparam; /* $@ current positional parameters */
  1937. struct redirtab *redirlist;
  1938. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1939. struct var *vartab[VTABSIZE];
  1940. struct var varinit[ARRAY_SIZE(varinit_data)];
  1941. int lineno;
  1942. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1943. };
  1944. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1945. #define G_var (*ash_ptr_to_globals_var)
  1946. #define shellparam (G_var.shellparam )
  1947. //#define redirlist (G_var.redirlist )
  1948. #define preverrout_fd (G_var.preverrout_fd)
  1949. #define vartab (G_var.vartab )
  1950. #define varinit (G_var.varinit )
  1951. #define lineno (G_var.lineno )
  1952. #define linenovar (G_var.linenovar )
  1953. #define vifs varinit[0]
  1954. #if ENABLE_ASH_MAIL
  1955. # define vmail varinit[1]
  1956. # define vmpath varinit[2]
  1957. #endif
  1958. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1959. #define vpath varinit[VAR_OFFSET1 + 1]
  1960. #define vps1 varinit[VAR_OFFSET1 + 2]
  1961. #define vps2 varinit[VAR_OFFSET1 + 3]
  1962. #define vps4 varinit[VAR_OFFSET1 + 4]
  1963. #if ENABLE_ASH_GETOPTS
  1964. # define voptind varinit[VAR_OFFSET1 + 5]
  1965. #endif
  1966. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1967. #define vlineno varinit[VAR_OFFSET2 + 5]
  1968. #if ENABLE_ASH_RANDOM_SUPPORT
  1969. # define vrandom varinit[VAR_OFFSET2 + 6]
  1970. #endif
  1971. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1972. #if BASH_EPOCH_VARS
  1973. # define vepochs varinit[VAR_OFFSET3 + 6]
  1974. # define vepochr varinit[VAR_OFFSET3 + 7]
  1975. #endif
  1976. #define INIT_G_var() do { \
  1977. unsigned i; \
  1978. (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
  1979. barrier(); \
  1980. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1981. varinit[i].flags = varinit_data[i].flags; \
  1982. varinit[i].var_text = varinit_data[i].var_text; \
  1983. varinit[i].var_func = varinit_data[i].var_func; \
  1984. } \
  1985. strcpy(linenovar, "LINENO="); \
  1986. vlineno.var_text = linenovar; \
  1987. } while (0)
  1988. /*
  1989. * The following macros access the values of the above variables.
  1990. * They have to skip over the name. They return the null string
  1991. * for unset variables.
  1992. */
  1993. #define ifsval() (vifs.var_text + 4)
  1994. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1995. #if ENABLE_ASH_MAIL
  1996. # define mailval() (vmail.var_text + 5)
  1997. # define mpathval() (vmpath.var_text + 9)
  1998. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1999. #endif
  2000. #define pathval() (vpath.var_text + 5)
  2001. #define ps1val() (vps1.var_text + 4)
  2002. #define ps2val() (vps2.var_text + 4)
  2003. #define ps4val() (vps4.var_text + 4)
  2004. #if ENABLE_ASH_GETOPTS
  2005. # define optindval() (voptind.var_text + 7)
  2006. #endif
  2007. #if ENABLE_ASH_GETOPTS
  2008. static void FAST_FUNC
  2009. getoptsreset(const char *value)
  2010. {
  2011. shellparam.optind = 1;
  2012. if (is_number(value))
  2013. shellparam.optind = number(value) ?: 1;
  2014. shellparam.optoff = -1;
  2015. }
  2016. #endif
  2017. /*
  2018. * Compares two strings up to the first = or '\0'. The first
  2019. * string must be terminated by '='; the second may be terminated by
  2020. * either '=' or '\0'.
  2021. */
  2022. static int
  2023. varcmp(const char *p, const char *q)
  2024. {
  2025. int c, d;
  2026. while ((c = *p) == (d = *q)) {
  2027. if (c == '\0' || c == '=')
  2028. goto out;
  2029. p++;
  2030. q++;
  2031. }
  2032. if (c == '=')
  2033. c = '\0';
  2034. if (d == '=')
  2035. d = '\0';
  2036. out:
  2037. return c - d;
  2038. }
  2039. /*
  2040. * Find the appropriate entry in the hash table from the name.
  2041. */
  2042. static struct var **
  2043. hashvar(const char *p)
  2044. {
  2045. unsigned hashval;
  2046. hashval = ((unsigned char) *p) << 4;
  2047. while (*p && *p != '=')
  2048. hashval += (unsigned char) *p++;
  2049. return &vartab[hashval % VTABSIZE];
  2050. }
  2051. static int
  2052. vpcmp(const void *a, const void *b)
  2053. {
  2054. return varcmp(*(const char **)a, *(const char **)b);
  2055. }
  2056. /*
  2057. * This routine initializes the builtin variables.
  2058. */
  2059. static void
  2060. initvar(void)
  2061. {
  2062. struct var *vp;
  2063. struct var *end;
  2064. struct var **vpp;
  2065. /*
  2066. * PS1 depends on uid
  2067. */
  2068. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2069. vps1.var_text = "PS1=\\w \\$ ";
  2070. #else
  2071. if (!geteuid())
  2072. vps1.var_text = "PS1=# ";
  2073. #endif
  2074. vp = varinit;
  2075. end = vp + ARRAY_SIZE(varinit);
  2076. do {
  2077. vpp = hashvar(vp->var_text);
  2078. vp->next = *vpp;
  2079. *vpp = vp;
  2080. } while (++vp < end);
  2081. }
  2082. static struct var **
  2083. findvar(struct var **vpp, const char *name)
  2084. {
  2085. for (; *vpp; vpp = &(*vpp)->next) {
  2086. if (varcmp((*vpp)->var_text, name) == 0) {
  2087. break;
  2088. }
  2089. }
  2090. return vpp;
  2091. }
  2092. /*
  2093. * Find the value of a variable. Returns NULL if not set.
  2094. */
  2095. static const char* FAST_FUNC
  2096. lookupvar(const char *name)
  2097. {
  2098. struct var *v;
  2099. v = *findvar(hashvar(name), name);
  2100. if (v) {
  2101. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2102. /*
  2103. * Dynamic variables are implemented roughly the same way they are
  2104. * in bash. Namely, they're "special" so long as they aren't unset.
  2105. * As soon as they're unset, they're no longer dynamic, and dynamic
  2106. * lookup will no longer happen at that point. -- PFM.
  2107. */
  2108. if (v->flags & VDYNAMIC)
  2109. v->var_func(NULL);
  2110. #endif
  2111. if (!(v->flags & VUNSET)) {
  2112. if (v == &vlineno && v->var_text == linenovar) {
  2113. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2114. }
  2115. return var_end(v->var_text);
  2116. }
  2117. }
  2118. return NULL;
  2119. }
  2120. #if ENABLE_UNICODE_SUPPORT
  2121. static void
  2122. reinit_unicode_for_ash(void)
  2123. {
  2124. /* Unicode support should be activated even if LANG is set
  2125. * _during_ shell execution, not only if it was set when
  2126. * shell was started. Therefore, re-check LANG every time:
  2127. */
  2128. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2129. || ENABLE_UNICODE_USING_LOCALE
  2130. ) {
  2131. const char *s = lookupvar("LC_ALL");
  2132. if (!s) s = lookupvar("LC_CTYPE");
  2133. if (!s) s = lookupvar("LANG");
  2134. reinit_unicode(s);
  2135. }
  2136. }
  2137. #else
  2138. # define reinit_unicode_for_ash() ((void)0)
  2139. #endif
  2140. /*
  2141. * Search the environment of a builtin command.
  2142. */
  2143. static ALWAYS_INLINE const char *
  2144. bltinlookup(const char *name)
  2145. {
  2146. return lookupvar(name);
  2147. }
  2148. /*
  2149. * Same as setvar except that the variable and value are passed in
  2150. * the first argument as name=value. Since the first argument will
  2151. * be actually stored in the table, it should not be a string that
  2152. * will go away.
  2153. * Called with interrupts off.
  2154. */
  2155. static struct var *
  2156. setvareq(char *s, int flags)
  2157. {
  2158. struct var *vp, **vpp;
  2159. vpp = hashvar(s);
  2160. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2161. vpp = findvar(vpp, s);
  2162. vp = *vpp;
  2163. if (vp) {
  2164. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2165. const char *n;
  2166. if (flags & VNOSAVE)
  2167. free(s);
  2168. n = vp->var_text;
  2169. exitstatus = 1;
  2170. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2171. }
  2172. if (flags & VNOSET)
  2173. goto out;
  2174. if (vp->var_func && !(flags & VNOFUNC))
  2175. vp->var_func(var_end(s));
  2176. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2177. free((char*)vp->var_text);
  2178. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2179. *vpp = vp->next;
  2180. free(vp);
  2181. out_free:
  2182. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2183. free(s);
  2184. goto out;
  2185. }
  2186. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2187. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2188. if (flags & VUNSET)
  2189. flags &= ~VDYNAMIC;
  2190. #endif
  2191. } else {
  2192. /* variable s is not found */
  2193. if (flags & VNOSET)
  2194. goto out;
  2195. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2196. goto out_free;
  2197. vp = ckzalloc(sizeof(*vp));
  2198. vp->next = *vpp;
  2199. /*vp->func = NULL; - ckzalloc did it */
  2200. *vpp = vp;
  2201. }
  2202. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2203. s = ckstrdup(s);
  2204. vp->var_text = s;
  2205. vp->flags = flags;
  2206. out:
  2207. return vp;
  2208. }
  2209. /*
  2210. * Set the value of a variable. The flags argument is ored with the
  2211. * flags of the variable. If val is NULL, the variable is unset.
  2212. */
  2213. static struct var *
  2214. setvar(const char *name, const char *val, int flags)
  2215. {
  2216. const char *q;
  2217. char *p;
  2218. char *nameeq;
  2219. size_t namelen;
  2220. size_t vallen;
  2221. struct var *vp;
  2222. q = endofname(name);
  2223. p = strchrnul(q, '=');
  2224. namelen = p - name;
  2225. if (!namelen || p != q)
  2226. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2227. vallen = 0;
  2228. if (val == NULL) {
  2229. flags |= VUNSET;
  2230. } else {
  2231. vallen = strlen(val);
  2232. }
  2233. INT_OFF;
  2234. nameeq = ckzalloc(namelen + vallen + 2);
  2235. p = mempcpy(nameeq, name, namelen);
  2236. if (val) {
  2237. *p++ = '=';
  2238. memcpy(p, val, vallen);
  2239. }
  2240. vp = setvareq(nameeq, flags | VNOSAVE);
  2241. INT_ON;
  2242. return vp;
  2243. }
  2244. static void FAST_FUNC
  2245. setvar0(const char *name, const char *val)
  2246. {
  2247. setvar(name, val, 0);
  2248. }
  2249. /*
  2250. * Unset the specified variable.
  2251. */
  2252. static void
  2253. unsetvar(const char *s)
  2254. {
  2255. setvar(s, NULL, 0);
  2256. }
  2257. /*
  2258. * Generate a list of variables satisfying the given conditions.
  2259. */
  2260. #if !ENABLE_FEATURE_SH_NOFORK
  2261. # define listvars(on, off, lp, end) listvars(on, off, end)
  2262. #endif
  2263. static char **
  2264. listvars(int on, int off, struct strlist *lp, char ***end)
  2265. {
  2266. struct var **vpp;
  2267. struct var *vp;
  2268. char **ep;
  2269. int mask;
  2270. STARTSTACKSTR(ep);
  2271. vpp = vartab;
  2272. mask = on | off;
  2273. do {
  2274. for (vp = *vpp; vp; vp = vp->next) {
  2275. if ((vp->flags & mask) == on) {
  2276. #if ENABLE_FEATURE_SH_NOFORK
  2277. /* If variable with the same name is both
  2278. * exported and temporarily set for a command:
  2279. * export ZVAR=5
  2280. * ZVAR=6 printenv
  2281. * then "ZVAR=6" will be both in vartab and
  2282. * lp lists. Do not pass it twice to printenv.
  2283. */
  2284. struct strlist *lp1 = lp;
  2285. while (lp1) {
  2286. if (strcmp(lp1->text, vp->var_text) == 0)
  2287. goto skip;
  2288. lp1 = lp1->next;
  2289. }
  2290. #endif
  2291. if (ep == stackstrend())
  2292. ep = growstackstr();
  2293. *ep++ = (char*)vp->var_text;
  2294. #if ENABLE_FEATURE_SH_NOFORK
  2295. skip: ;
  2296. #endif
  2297. }
  2298. }
  2299. } while (++vpp < vartab + VTABSIZE);
  2300. #if ENABLE_FEATURE_SH_NOFORK
  2301. while (lp) {
  2302. if (ep == stackstrend())
  2303. ep = growstackstr();
  2304. *ep++ = lp->text;
  2305. lp = lp->next;
  2306. }
  2307. #endif
  2308. if (ep == stackstrend())
  2309. ep = growstackstr();
  2310. if (end)
  2311. *end = ep;
  2312. *ep++ = NULL;
  2313. return grabstackstr(ep);
  2314. }
  2315. /* ============ Path search helper */
  2316. static const char *
  2317. legal_pathopt(const char *opt, const char *term, int magic)
  2318. {
  2319. switch (magic) {
  2320. case 0:
  2321. opt = NULL;
  2322. break;
  2323. case 1:
  2324. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2325. break;
  2326. default:
  2327. opt += strcspn(opt, term);
  2328. break;
  2329. }
  2330. if (opt && *opt == '%')
  2331. opt++;
  2332. return opt;
  2333. }
  2334. /*
  2335. * The variable path (passed by reference) should be set to the start
  2336. * of the path before the first call; padvance will update
  2337. * this value as it proceeds. Successive calls to padvance will return
  2338. * the possible path expansions in sequence. If an option (indicated by
  2339. * a percent sign) appears in the path entry then the global variable
  2340. * pathopt will be set to point to it; otherwise pathopt will be set to
  2341. * NULL.
  2342. *
  2343. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2344. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2345. * pathopt.
  2346. */
  2347. static const char *pathopt; /* set by padvance */
  2348. static int
  2349. padvance_magic(const char **path, const char *name, int magic)
  2350. {
  2351. const char *term = "%:";
  2352. const char *lpathopt;
  2353. const char *p;
  2354. char *q;
  2355. const char *start;
  2356. size_t qlen;
  2357. size_t len;
  2358. if (*path == NULL)
  2359. return -1;
  2360. lpathopt = NULL;
  2361. start = *path;
  2362. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2363. lpathopt = start + 1;
  2364. start = p;
  2365. term = ":";
  2366. }
  2367. len = strcspn(start, term);
  2368. p = start + len;
  2369. if (*p == '%') {
  2370. size_t extra = strchrnul(p, ':') - p;
  2371. if (legal_pathopt(p + 1, term, magic))
  2372. lpathopt = p + 1;
  2373. else
  2374. len += extra;
  2375. p += extra;
  2376. }
  2377. pathopt = lpathopt;
  2378. *path = *p == ':' ? p + 1 : NULL;
  2379. /* "2" is for '/' and '\0' */
  2380. qlen = len + strlen(name) + 2;
  2381. q = growstackto(qlen);
  2382. if (len) {
  2383. q = mempcpy(q, start, len);
  2384. *q++ = '/';
  2385. }
  2386. strcpy(q, name);
  2387. return qlen;
  2388. }
  2389. static int
  2390. padvance(const char **path, const char *name)
  2391. {
  2392. return padvance_magic(path, name, 1);
  2393. }
  2394. /* ============ Prompt */
  2395. static smallint doprompt; /* if set, prompt the user */
  2396. static smallint needprompt; /* true if interactive and at start of line */
  2397. #if ENABLE_FEATURE_EDITING
  2398. static line_input_t *line_input_state;
  2399. static const char *cmdedit_prompt;
  2400. static void
  2401. putprompt(const char *s)
  2402. {
  2403. if (ENABLE_ASH_EXPAND_PRMT) {
  2404. free((char*)cmdedit_prompt);
  2405. cmdedit_prompt = ckstrdup(s);
  2406. return;
  2407. }
  2408. cmdedit_prompt = s;
  2409. }
  2410. #else
  2411. static void
  2412. putprompt(const char *s)
  2413. {
  2414. out2str(s);
  2415. }
  2416. #endif
  2417. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2418. static const char *expandstr(const char *ps, int syntax_type);
  2419. /* Values for syntax param */
  2420. #define BASESYNTAX 0 /* not in quotes */
  2421. #define DQSYNTAX 1 /* in double quotes */
  2422. #define SQSYNTAX 2 /* in single quotes */
  2423. #define ARISYNTAX 3 /* in arithmetic */
  2424. #if ENABLE_ASH_EXPAND_PRMT
  2425. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2426. #endif
  2427. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2428. /*
  2429. * called by editline -- any expansions to the prompt should be added here.
  2430. */
  2431. static void
  2432. setprompt_if(smallint do_set, int whichprompt)
  2433. {
  2434. const char *prompt;
  2435. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2436. if (!do_set)
  2437. return;
  2438. needprompt = 0;
  2439. switch (whichprompt) {
  2440. case 1:
  2441. prompt = ps1val();
  2442. break;
  2443. case 2:
  2444. prompt = ps2val();
  2445. break;
  2446. default: /* 0 */
  2447. prompt = nullstr;
  2448. }
  2449. #if ENABLE_ASH_EXPAND_PRMT
  2450. pushstackmark(&smark, stackblocksize());
  2451. putprompt(expandstr(prompt, PSSYNTAX));
  2452. popstackmark(&smark);
  2453. #else
  2454. putprompt(prompt);
  2455. #endif
  2456. }
  2457. /* ============ The cd and pwd commands */
  2458. #define CD_PHYSICAL 1
  2459. #define CD_PRINT 2
  2460. static int
  2461. cdopt(void)
  2462. {
  2463. int flags = 0;
  2464. int i, j;
  2465. j = 'L';
  2466. while ((i = nextopt("LP")) != '\0') {
  2467. if (i != j) {
  2468. flags ^= CD_PHYSICAL;
  2469. j = i;
  2470. }
  2471. }
  2472. return flags;
  2473. }
  2474. /*
  2475. * Update curdir (the name of the current directory) in response to a
  2476. * cd command.
  2477. */
  2478. static const char *
  2479. updatepwd(const char *dir)
  2480. {
  2481. char *new;
  2482. char *p;
  2483. char *cdcomppath;
  2484. const char *lim;
  2485. cdcomppath = sstrdup(dir);
  2486. STARTSTACKSTR(new);
  2487. if (*dir != '/') {
  2488. if (curdir == nullstr)
  2489. return 0;
  2490. new = stack_putstr(curdir, new);
  2491. }
  2492. new = makestrspace(strlen(dir) + 2, new);
  2493. lim = (char *)stackblock() + 1;
  2494. if (*dir != '/') {
  2495. if (new[-1] != '/')
  2496. USTPUTC('/', new);
  2497. if (new > lim && *lim == '/')
  2498. lim++;
  2499. } else {
  2500. USTPUTC('/', new);
  2501. cdcomppath++;
  2502. if (dir[1] == '/' && dir[2] != '/') {
  2503. USTPUTC('/', new);
  2504. cdcomppath++;
  2505. lim++;
  2506. }
  2507. }
  2508. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2509. while (p) {
  2510. switch (*p) {
  2511. case '.':
  2512. if (p[1] == '.' && p[2] == '\0') {
  2513. while (new > lim) {
  2514. STUNPUTC(new);
  2515. if (new[-1] == '/')
  2516. break;
  2517. }
  2518. break;
  2519. }
  2520. if (p[1] == '\0')
  2521. break;
  2522. /* fall through */
  2523. default:
  2524. new = stack_putstr(p, new);
  2525. USTPUTC('/', new);
  2526. }
  2527. p = strtok_r(NULL, "/", &cdcomppath);
  2528. }
  2529. if (new > lim)
  2530. STUNPUTC(new);
  2531. *new = 0;
  2532. return stackblock();
  2533. }
  2534. /*
  2535. * Find out what the current directory is. If we already know the current
  2536. * directory, this routine returns immediately.
  2537. */
  2538. static char *
  2539. getpwd(void)
  2540. {
  2541. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2542. return dir ? dir : nullstr;
  2543. }
  2544. static void
  2545. setpwd(const char *val, int setold)
  2546. {
  2547. char *oldcur, *dir;
  2548. oldcur = dir = curdir;
  2549. if (setold) {
  2550. setvar("OLDPWD", oldcur, VEXPORT);
  2551. }
  2552. INT_OFF;
  2553. if (physdir != nullstr) {
  2554. if (physdir != oldcur)
  2555. free(physdir);
  2556. physdir = nullstr;
  2557. }
  2558. if (oldcur == val || !val) {
  2559. char *s = getpwd();
  2560. physdir = s;
  2561. if (!val)
  2562. dir = s;
  2563. } else
  2564. dir = ckstrdup(val);
  2565. if (oldcur != dir && oldcur != nullstr) {
  2566. free(oldcur);
  2567. }
  2568. curdir = dir;
  2569. INT_ON;
  2570. setvar("PWD", dir, VEXPORT);
  2571. }
  2572. static void hashcd(void);
  2573. /*
  2574. * Actually do the chdir. We also call hashcd to let other routines
  2575. * know that the current directory has changed.
  2576. */
  2577. static int
  2578. docd(const char *dest, int flags)
  2579. {
  2580. const char *dir = NULL;
  2581. int err;
  2582. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2583. INT_OFF;
  2584. if (!(flags & CD_PHYSICAL)) {
  2585. dir = updatepwd(dest);
  2586. if (dir)
  2587. dest = dir;
  2588. }
  2589. err = chdir(dest);
  2590. if (err)
  2591. goto out;
  2592. setpwd(dir, 1);
  2593. hashcd();
  2594. out:
  2595. INT_ON;
  2596. return err;
  2597. }
  2598. static int FAST_FUNC
  2599. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2600. {
  2601. const char *dest;
  2602. const char *path;
  2603. const char *p;
  2604. char c;
  2605. struct stat statb;
  2606. int flags;
  2607. int len;
  2608. flags = cdopt();
  2609. dest = *argptr;
  2610. if (!dest)
  2611. dest = bltinlookup("HOME");
  2612. else if (LONE_DASH(dest)) {
  2613. dest = bltinlookup("OLDPWD");
  2614. flags |= CD_PRINT;
  2615. }
  2616. if (!dest)
  2617. dest = nullstr;
  2618. if (*dest == '/')
  2619. goto step6;
  2620. if (*dest == '.') {
  2621. c = dest[1];
  2622. dotdot:
  2623. switch (c) {
  2624. case '\0':
  2625. case '/':
  2626. goto step6;
  2627. case '.':
  2628. c = dest[2];
  2629. if (c != '.')
  2630. goto dotdot;
  2631. }
  2632. }
  2633. if (!*dest)
  2634. dest = ".";
  2635. path = bltinlookup("CDPATH");
  2636. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2637. c = *p;
  2638. p = stalloc(len);
  2639. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2640. if (c && c != ':')
  2641. flags |= CD_PRINT;
  2642. docd:
  2643. if (!docd(p, flags))
  2644. goto out;
  2645. goto err;
  2646. }
  2647. }
  2648. step6:
  2649. p = dest;
  2650. goto docd;
  2651. err:
  2652. ash_msg_and_raise_perror("can't cd to %s", dest);
  2653. /* NOTREACHED */
  2654. out:
  2655. if (flags & CD_PRINT)
  2656. out1fmt("%s\n", curdir);
  2657. return 0;
  2658. }
  2659. static int FAST_FUNC
  2660. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2661. {
  2662. int flags;
  2663. const char *dir = curdir;
  2664. flags = cdopt();
  2665. if (flags) {
  2666. if (physdir == nullstr)
  2667. setpwd(dir, 0);
  2668. dir = physdir;
  2669. }
  2670. out1fmt("%s\n", dir);
  2671. return 0;
  2672. }
  2673. /* ============ ... */
  2674. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2675. /* Syntax classes */
  2676. #define CWORD 0 /* character is nothing special */
  2677. #define CNL 1 /* newline character */
  2678. #define CBACK 2 /* a backslash character */
  2679. #define CSQUOTE 3 /* single quote */
  2680. #define CDQUOTE 4 /* double quote */
  2681. #define CENDQUOTE 5 /* a terminating quote */
  2682. #define CBQUOTE 6 /* backwards single quote */
  2683. #define CVAR 7 /* a dollar sign */
  2684. #define CENDVAR 8 /* a '}' character */
  2685. #define CLP 9 /* a left paren in arithmetic */
  2686. #define CRP 10 /* a right paren in arithmetic */
  2687. #define CENDFILE 11 /* end of file */
  2688. #define CCTL 12 /* like CWORD, except it must be escaped */
  2689. #define CSPCL 13 /* these terminate a word */
  2690. #define CIGN 14 /* character should be ignored */
  2691. #define PEOF 256
  2692. #if ENABLE_ASH_ALIAS
  2693. # define PEOA 257
  2694. #endif
  2695. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2696. #if ENABLE_FEATURE_SH_MATH
  2697. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2698. #else
  2699. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2700. #endif
  2701. static const uint16_t S_I_T[] ALIGN2 = {
  2702. #if ENABLE_ASH_ALIAS
  2703. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2704. #endif
  2705. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2706. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2707. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2708. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2709. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2710. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2711. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2712. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2713. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2714. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2715. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2716. #if !USE_SIT_FUNCTION
  2717. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2718. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2719. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2720. #endif
  2721. #undef SIT_ITEM
  2722. };
  2723. /* Constants below must match table above */
  2724. enum {
  2725. #if ENABLE_ASH_ALIAS
  2726. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2727. #endif
  2728. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2729. CNL_CNL_CNL_CNL , /* 2 */
  2730. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2731. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2732. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2733. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2734. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2735. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2736. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2737. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2738. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2739. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2740. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2741. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2742. };
  2743. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2744. * caller must ensure proper cast on it if c is *char_ptr!
  2745. */
  2746. #if USE_SIT_FUNCTION
  2747. static int
  2748. SIT(int c, int syntax)
  2749. {
  2750. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2751. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2752. /*
  2753. * This causes '/' to be prepended with CTLESC in dquoted string,
  2754. * making "./file"* treated incorrectly because we feed
  2755. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2756. * The "homegrown" glob implementation is okay with that,
  2757. * but glibc one isn't. With '/' always treated as CWORD,
  2758. * both work fine.
  2759. */
  2760. # if ENABLE_ASH_ALIAS
  2761. static const uint8_t syntax_index_table[] ALIGN1 = {
  2762. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2763. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2764. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2765. 11, 3 /* "}~" */
  2766. };
  2767. # else
  2768. static const uint8_t syntax_index_table[] ALIGN1 = {
  2769. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2770. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2771. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2772. 10, 2 /* "}~" */
  2773. };
  2774. # endif
  2775. const char *s;
  2776. int indx;
  2777. if (c == PEOF)
  2778. return CENDFILE;
  2779. # if ENABLE_ASH_ALIAS
  2780. if (c == PEOA)
  2781. indx = 0;
  2782. else
  2783. # endif
  2784. {
  2785. /* Cast is purely for paranoia here,
  2786. * just in case someone passed signed char to us */
  2787. if ((unsigned char)c >= CTL_FIRST
  2788. && (unsigned char)c <= CTL_LAST
  2789. ) {
  2790. return CCTL;
  2791. }
  2792. s = strchrnul(spec_symbls, c);
  2793. if (*s == '\0')
  2794. return CWORD;
  2795. indx = syntax_index_table[s - spec_symbls];
  2796. }
  2797. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2798. }
  2799. #else /* !USE_SIT_FUNCTION */
  2800. static const uint8_t syntax_index_table[] ALIGN1 = {
  2801. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2802. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2812. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2813. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2835. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2836. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2837. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2839. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2841. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2842. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2843. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2844. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2845. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2848. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2849. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2850. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2862. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2863. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2864. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2865. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2866. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2867. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2895. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2896. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2897. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2900. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2928. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2929. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2930. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2933. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2934. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2935. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2936. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2937. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2938. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2939. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2940. #if BASH_PROCESS_SUBST
  2941. /* 137 CTLTOPROC */ CCTL_CCTL_CCTL_CCTL,
  2942. /* 138 CTLFROMPROC */ CCTL_CCTL_CCTL_CCTL,
  2943. #else
  2944. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2946. #endif
  2947. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  3029. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  3030. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  3031. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  3032. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  3033. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  3034. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  3035. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3036. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3037. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3038. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3039. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3040. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3041. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3042. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3043. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3044. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3045. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3046. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3047. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3048. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3049. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3050. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3051. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3052. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3053. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3054. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3055. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3056. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3057. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3058. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3059. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3060. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3061. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3062. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3063. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3064. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3065. # if ENABLE_ASH_ALIAS
  3066. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3067. # endif
  3068. };
  3069. #if 1
  3070. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3071. #else /* debug version, caught one signed char bug */
  3072. # define SIT(c, syntax) \
  3073. ({ \
  3074. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3075. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3076. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3077. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3078. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3079. })
  3080. #endif
  3081. #endif /* !USE_SIT_FUNCTION */
  3082. /* ============ Alias handling */
  3083. #if ENABLE_ASH_ALIAS
  3084. #define ALIASINUSE 1
  3085. #define ALIASDEAD 2
  3086. struct alias {
  3087. struct alias *next;
  3088. char *name;
  3089. char *val;
  3090. int flag;
  3091. };
  3092. static struct alias **atab; // [ATABSIZE];
  3093. #define INIT_G_alias() do { \
  3094. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3095. } while (0)
  3096. static struct alias **
  3097. __lookupalias(const char *name)
  3098. {
  3099. unsigned int hashval;
  3100. struct alias **app;
  3101. const char *p;
  3102. unsigned int ch;
  3103. p = name;
  3104. ch = (unsigned char)*p;
  3105. hashval = ch << 4;
  3106. while (ch) {
  3107. hashval += ch;
  3108. ch = (unsigned char)*++p;
  3109. }
  3110. app = &atab[hashval % ATABSIZE];
  3111. for (; *app; app = &(*app)->next) {
  3112. if (strcmp(name, (*app)->name) == 0) {
  3113. break;
  3114. }
  3115. }
  3116. return app;
  3117. }
  3118. static struct alias *
  3119. lookupalias(const char *name, int check)
  3120. {
  3121. struct alias *ap = *__lookupalias(name);
  3122. if (check && ap && (ap->flag & ALIASINUSE))
  3123. return NULL;
  3124. return ap;
  3125. }
  3126. static struct alias *
  3127. freealias(struct alias *ap)
  3128. {
  3129. struct alias *next;
  3130. if (ap->flag & ALIASINUSE) {
  3131. ap->flag |= ALIASDEAD;
  3132. return ap;
  3133. }
  3134. next = ap->next;
  3135. free(ap->name);
  3136. free(ap->val);
  3137. free(ap);
  3138. return next;
  3139. }
  3140. static void
  3141. setalias(const char *name, const char *val)
  3142. {
  3143. struct alias *ap, **app;
  3144. app = __lookupalias(name);
  3145. ap = *app;
  3146. INT_OFF;
  3147. if (ap) {
  3148. if (!(ap->flag & ALIASINUSE)) {
  3149. free(ap->val);
  3150. }
  3151. ap->val = ckstrdup(val);
  3152. ap->flag &= ~ALIASDEAD;
  3153. } else {
  3154. /* not found */
  3155. ap = ckzalloc(sizeof(struct alias));
  3156. ap->name = ckstrdup(name);
  3157. ap->val = ckstrdup(val);
  3158. /*ap->flag = 0; - ckzalloc did it */
  3159. /*ap->next = NULL;*/
  3160. *app = ap;
  3161. }
  3162. INT_ON;
  3163. }
  3164. static int
  3165. unalias(const char *name)
  3166. {
  3167. struct alias **app;
  3168. app = __lookupalias(name);
  3169. if (*app) {
  3170. INT_OFF;
  3171. *app = freealias(*app);
  3172. INT_ON;
  3173. return 0;
  3174. }
  3175. return 1;
  3176. }
  3177. static void
  3178. rmaliases(void)
  3179. {
  3180. struct alias *ap, **app;
  3181. int i;
  3182. INT_OFF;
  3183. for (i = 0; i < ATABSIZE; i++) {
  3184. app = &atab[i];
  3185. for (ap = *app; ap; ap = *app) {
  3186. *app = freealias(*app);
  3187. if (ap == *app) {
  3188. app = &ap->next;
  3189. }
  3190. }
  3191. }
  3192. INT_ON;
  3193. }
  3194. static void
  3195. printalias(const struct alias *ap)
  3196. {
  3197. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3198. }
  3199. /*
  3200. * TODO - sort output
  3201. */
  3202. static int FAST_FUNC
  3203. aliascmd(int argc UNUSED_PARAM, char **argv)
  3204. {
  3205. char *n, *v;
  3206. int ret = 0;
  3207. struct alias *ap;
  3208. if (!argv[1]) {
  3209. int i;
  3210. for (i = 0; i < ATABSIZE; i++) {
  3211. for (ap = atab[i]; ap; ap = ap->next) {
  3212. printalias(ap);
  3213. }
  3214. }
  3215. return 0;
  3216. }
  3217. while ((n = *++argv) != NULL) {
  3218. v = strchr(n+1, '=');
  3219. if (v == NULL) { /* n+1: funny ksh stuff */
  3220. ap = *__lookupalias(n);
  3221. if (ap == NULL) {
  3222. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3223. ret = 1;
  3224. } else
  3225. printalias(ap);
  3226. } else {
  3227. *v++ = '\0';
  3228. setalias(n, v);
  3229. }
  3230. }
  3231. return ret;
  3232. }
  3233. static int FAST_FUNC
  3234. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3235. {
  3236. int i;
  3237. while (nextopt("a") != '\0') {
  3238. rmaliases();
  3239. return 0;
  3240. }
  3241. for (i = 0; *argptr; argptr++) {
  3242. if (unalias(*argptr)) {
  3243. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3244. i = 1;
  3245. }
  3246. }
  3247. return i;
  3248. }
  3249. #endif /* ASH_ALIAS */
  3250. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3251. #define FORK_FG 0
  3252. #define FORK_BG 1
  3253. #define FORK_NOJOB 2
  3254. /* mode flags for showjob(s) */
  3255. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3256. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3257. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3258. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3259. /*
  3260. * A job structure contains information about a job. A job is either a
  3261. * single process or a set of processes contained in a pipeline. In the
  3262. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3263. * array of pids.
  3264. */
  3265. struct procstat {
  3266. pid_t ps_pid; /* process id */
  3267. int ps_status; /* last process status from wait() */
  3268. char *ps_cmd; /* text of command being run */
  3269. };
  3270. struct job {
  3271. struct procstat ps0; /* status of process */
  3272. struct procstat *ps; /* status of processes when more than one */
  3273. #if JOBS
  3274. int stopstatus; /* status of a stopped job */
  3275. #endif
  3276. unsigned nprocs; /* number of processes */
  3277. #define JOBRUNNING 0 /* at least one proc running */
  3278. #define JOBSTOPPED 1 /* all procs are stopped */
  3279. #define JOBDONE 2 /* all procs are completed */
  3280. unsigned
  3281. state: 8,
  3282. #if JOBS
  3283. sigint: 1, /* job was killed by SIGINT */
  3284. jobctl: 1, /* job running under job control */
  3285. #endif
  3286. waited: 1, /* true if this entry has been waited for */
  3287. used: 1, /* true if this entry is in used */
  3288. changed: 1; /* true if status has changed */
  3289. struct job *prev_job; /* previous job */
  3290. };
  3291. static struct job *makejob(/*union node *,*/ int);
  3292. static int forkshell(struct job *, union node *, int);
  3293. static int waitforjob(struct job *);
  3294. #if !JOBS
  3295. enum { doing_jobctl = 0 };
  3296. #define setjobctl(on) do {} while (0)
  3297. #else
  3298. static smallint doing_jobctl; //references:8
  3299. static void setjobctl(int);
  3300. #endif
  3301. /*
  3302. * Ignore a signal.
  3303. */
  3304. static void
  3305. ignoresig(int signo)
  3306. {
  3307. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3308. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3309. /* No, need to do it */
  3310. signal(signo, SIG_IGN);
  3311. }
  3312. sigmode[signo - 1] = S_HARD_IGN;
  3313. }
  3314. /*
  3315. * Only one usage site - in setsignal()
  3316. */
  3317. static void
  3318. signal_handler(int signo)
  3319. {
  3320. if (signo == SIGCHLD) {
  3321. got_sigchld = 1;
  3322. if (!trap[SIGCHLD])
  3323. return;
  3324. }
  3325. gotsig[signo - 1] = 1;
  3326. pending_sig = signo;
  3327. if (signo == SIGINT && !trap[SIGINT]) {
  3328. if (!suppress_int) {
  3329. pending_sig = 0;
  3330. raise_interrupt(); /* does not return */
  3331. }
  3332. pending_int = 1;
  3333. }
  3334. }
  3335. /*
  3336. * Set the signal handler for the specified signal. The routine figures
  3337. * out what it should be set to.
  3338. */
  3339. static void
  3340. setsignal(int signo)
  3341. {
  3342. char *t;
  3343. char cur_act, new_act;
  3344. struct sigaction act;
  3345. t = trap[signo];
  3346. new_act = S_DFL;
  3347. if (t != NULL) { /* trap for this sig is set */
  3348. new_act = S_CATCH;
  3349. if (t[0] == '\0') /* trap is "": ignore this sig */
  3350. new_act = S_IGN;
  3351. }
  3352. if (rootshell && new_act == S_DFL) {
  3353. switch (signo) {
  3354. case SIGINT:
  3355. if (iflag || minusc || sflag == 0)
  3356. new_act = S_CATCH;
  3357. break;
  3358. case SIGQUIT:
  3359. #if DEBUG
  3360. if (debug)
  3361. break;
  3362. #endif
  3363. /* man bash:
  3364. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3365. * commands run by bash have signal handlers
  3366. * set to the values inherited by the shell
  3367. * from its parent". */
  3368. new_act = S_IGN;
  3369. break;
  3370. case SIGTERM:
  3371. if (iflag)
  3372. new_act = S_IGN;
  3373. break;
  3374. #if JOBS
  3375. case SIGTSTP:
  3376. case SIGTTOU:
  3377. if (mflag)
  3378. new_act = S_IGN;
  3379. break;
  3380. #endif
  3381. }
  3382. }
  3383. /* if !rootshell, we reset SIGQUIT to DFL,
  3384. * whereas we have to restore it to what shell got on entry.
  3385. * This is handled by the fact that if signal was IGNored on entry,
  3386. * then cur_act is S_HARD_IGN and we never change its sigaction
  3387. * (see code below).
  3388. */
  3389. if (signo == SIGCHLD)
  3390. new_act = S_CATCH;
  3391. t = &sigmode[signo - 1];
  3392. cur_act = *t;
  3393. if (cur_act == 0) {
  3394. /* current setting is not yet known */
  3395. if (sigaction(signo, NULL, &act)) {
  3396. /* pretend it worked; maybe we should give a warning,
  3397. * but other shells don't. We don't alter sigmode,
  3398. * so we retry every time.
  3399. * btw, in Linux it never fails. --vda */
  3400. return;
  3401. }
  3402. if (act.sa_handler == SIG_IGN) {
  3403. cur_act = S_HARD_IGN;
  3404. if (mflag
  3405. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3406. ) {
  3407. cur_act = S_IGN; /* don't hard ignore these */
  3408. }
  3409. }
  3410. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3411. /* installing SIG_DFL over SIG_DFL is a no-op */
  3412. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3413. *t = S_DFL;
  3414. return;
  3415. }
  3416. }
  3417. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3418. return;
  3419. *t = new_act;
  3420. act.sa_handler = SIG_DFL;
  3421. switch (new_act) {
  3422. case S_CATCH:
  3423. act.sa_handler = signal_handler;
  3424. break;
  3425. case S_IGN:
  3426. act.sa_handler = SIG_IGN;
  3427. break;
  3428. }
  3429. /* flags and mask matter only if !DFL and !IGN, but we do it
  3430. * for all cases for more deterministic behavior:
  3431. */
  3432. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3433. sigfillset(&act.sa_mask);
  3434. sigaction_set(signo, &act);
  3435. }
  3436. /* mode flags for set_curjob */
  3437. #define CUR_DELETE 2
  3438. #define CUR_RUNNING 1
  3439. #define CUR_STOPPED 0
  3440. #if JOBS
  3441. /* pgrp of shell on invocation */
  3442. static int initialpgrp; //references:2
  3443. static int ttyfd = -1; //5
  3444. #endif
  3445. /* array of jobs */
  3446. static struct job *jobtab; //5
  3447. /* size of array */
  3448. static unsigned njobs; //4
  3449. /* current job */
  3450. static struct job *curjob; //lots
  3451. #if 0
  3452. /* Bash has a feature: it restores termios after a successful wait for
  3453. * a foreground job which had at least one stopped or sigkilled member.
  3454. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3455. * properly restoring tty state. Should we do this too?
  3456. * A reproducer: ^Z an interactive python:
  3457. *
  3458. * # python
  3459. * Python 2.7.12 (...)
  3460. * >>> ^Z
  3461. * { python leaves tty in -icanon -echo state. We do survive that... }
  3462. * [1]+ Stopped python
  3463. * { ...however, next program (python #2) does not survive it well: }
  3464. * # python
  3465. * Python 2.7.12 (...)
  3466. * >>> Traceback (most recent call last):
  3467. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3468. * File "<stdin>", line 1, in <module>
  3469. * NameError: name 'qwerty' is not defined
  3470. *
  3471. * The implementation below is modeled on bash code and seems to work.
  3472. * However, I'm not sure we should do this. For one: what if I'd fg
  3473. * the stopped python instead? It'll be confused by "restored" tty state.
  3474. */
  3475. static struct termios shell_tty_info;
  3476. static void
  3477. get_tty_state(void)
  3478. {
  3479. if (rootshell && ttyfd >= 0)
  3480. tcgetattr(ttyfd, &shell_tty_info);
  3481. }
  3482. static void
  3483. set_tty_state(void)
  3484. {
  3485. /* if (rootshell) - caller ensures this */
  3486. if (ttyfd >= 0)
  3487. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3488. }
  3489. static int
  3490. job_signal_status(struct job *jp)
  3491. {
  3492. int status;
  3493. unsigned i;
  3494. struct procstat *ps = jp->ps;
  3495. for (i = 0; i < jp->nprocs; i++) {
  3496. status = ps[i].ps_status;
  3497. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3498. return status;
  3499. }
  3500. return 0;
  3501. }
  3502. static void
  3503. restore_tty_if_stopped_or_signaled(struct job *jp)
  3504. {
  3505. //TODO: check what happens if we come from waitforjob() in expbackq()
  3506. if (rootshell) {
  3507. int s = job_signal_status(jp);
  3508. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3509. set_tty_state();
  3510. }
  3511. }
  3512. #else
  3513. # define get_tty_state() ((void)0)
  3514. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3515. #endif
  3516. static void
  3517. set_curjob(struct job *jp, unsigned mode)
  3518. {
  3519. struct job *jp1;
  3520. struct job **jpp, **curp;
  3521. /* first remove from list */
  3522. jpp = curp = &curjob;
  3523. while (1) {
  3524. jp1 = *jpp;
  3525. if (jp1 == jp)
  3526. break;
  3527. jpp = &jp1->prev_job;
  3528. }
  3529. *jpp = jp1->prev_job;
  3530. /* Then re-insert in correct position */
  3531. jpp = curp;
  3532. switch (mode) {
  3533. default:
  3534. #if DEBUG
  3535. abort();
  3536. #endif
  3537. case CUR_DELETE:
  3538. /* job being deleted */
  3539. break;
  3540. case CUR_RUNNING:
  3541. /* newly created job or backgrounded job,
  3542. * put after all stopped jobs.
  3543. */
  3544. while (1) {
  3545. jp1 = *jpp;
  3546. #if JOBS
  3547. if (!jp1 || jp1->state != JOBSTOPPED)
  3548. #endif
  3549. break;
  3550. jpp = &jp1->prev_job;
  3551. }
  3552. /* FALLTHROUGH */
  3553. #if JOBS
  3554. case CUR_STOPPED:
  3555. #endif
  3556. /* newly stopped job - becomes curjob */
  3557. jp->prev_job = *jpp;
  3558. *jpp = jp;
  3559. break;
  3560. }
  3561. }
  3562. #if JOBS || DEBUG
  3563. static int
  3564. jobno(const struct job *jp)
  3565. {
  3566. return jp - jobtab + 1;
  3567. }
  3568. #endif
  3569. /*
  3570. * Convert a job name to a job structure.
  3571. */
  3572. #if !JOBS
  3573. #define getjob(name, getctl) getjob(name)
  3574. #endif
  3575. static struct job *
  3576. getjob(const char *name, int getctl)
  3577. {
  3578. struct job *jp;
  3579. struct job *found;
  3580. const char *err_msg = "%s: no such job";
  3581. unsigned num;
  3582. int c;
  3583. const char *p;
  3584. char *(*match)(const char *, const char *);
  3585. jp = curjob;
  3586. p = name;
  3587. if (!p)
  3588. goto currentjob;
  3589. if (*p != '%')
  3590. goto err;
  3591. c = *++p;
  3592. if (!c)
  3593. goto currentjob;
  3594. if (!p[1]) {
  3595. if (c == '+' || c == '%') {
  3596. currentjob:
  3597. err_msg = "No current job";
  3598. goto check;
  3599. }
  3600. if (c == '-') {
  3601. if (jp)
  3602. jp = jp->prev_job;
  3603. err_msg = "No previous job";
  3604. check:
  3605. if (!jp)
  3606. goto err;
  3607. goto gotit;
  3608. }
  3609. }
  3610. if (is_number(p)) {
  3611. num = atoi(p);
  3612. if (num > 0 && num <= njobs) {
  3613. jp = jobtab + num - 1;
  3614. if (jp->used)
  3615. goto gotit;
  3616. goto err;
  3617. }
  3618. }
  3619. match = prefix;
  3620. if (*p == '?') {
  3621. match = strstr;
  3622. p++;
  3623. }
  3624. found = NULL;
  3625. while (jp) {
  3626. if (match(jp->ps[0].ps_cmd, p)) {
  3627. if (found)
  3628. goto err;
  3629. found = jp;
  3630. err_msg = "%s: ambiguous";
  3631. }
  3632. jp = jp->prev_job;
  3633. }
  3634. if (!found)
  3635. goto err;
  3636. jp = found;
  3637. gotit:
  3638. #if JOBS
  3639. err_msg = "job %s not created under job control";
  3640. if (getctl && jp->jobctl == 0)
  3641. goto err;
  3642. #endif
  3643. return jp;
  3644. err:
  3645. ash_msg_and_raise_error(err_msg, name);
  3646. }
  3647. /*
  3648. * Mark a job structure as unused.
  3649. */
  3650. static void
  3651. freejob(struct job *jp)
  3652. {
  3653. struct procstat *ps;
  3654. int i;
  3655. INT_OFF;
  3656. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3657. if (ps->ps_cmd != nullstr)
  3658. free(ps->ps_cmd);
  3659. }
  3660. if (jp->ps != &jp->ps0)
  3661. free(jp->ps);
  3662. jp->used = 0;
  3663. set_curjob(jp, CUR_DELETE);
  3664. INT_ON;
  3665. }
  3666. #if JOBS
  3667. static void
  3668. xtcsetpgrp(int fd, pid_t pgrp)
  3669. {
  3670. if (tcsetpgrp(fd, pgrp))
  3671. ash_msg_and_raise_perror("can't set tty process group");
  3672. }
  3673. /*
  3674. * Turn job control on and off.
  3675. *
  3676. * Note: This code assumes that the third arg to ioctl is a character
  3677. * pointer, which is true on Berkeley systems but not System V. Since
  3678. * System V doesn't have job control yet, this isn't a problem now.
  3679. *
  3680. * Called with interrupts off.
  3681. */
  3682. static void
  3683. setjobctl(int on)
  3684. {
  3685. int fd;
  3686. int pgrp;
  3687. if (on == doing_jobctl || rootshell == 0)
  3688. return;
  3689. if (on) {
  3690. int ofd;
  3691. ofd = fd = open(_PATH_TTY, O_RDWR);
  3692. if (fd < 0) {
  3693. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3694. * That sometimes helps to acquire controlling tty.
  3695. * Obviously, a workaround for bugs when someone
  3696. * failed to provide a controlling tty to bash! :) */
  3697. fd = 2;
  3698. while (!isatty(fd))
  3699. if (--fd < 0)
  3700. goto out;
  3701. }
  3702. /* fd is a tty at this point */
  3703. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3704. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3705. close(ofd);
  3706. if (fd < 0)
  3707. goto out; /* F_DUPFD failed */
  3708. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3709. close_on_exec_on(fd);
  3710. while (1) { /* while we are in the background */
  3711. pgrp = tcgetpgrp(fd);
  3712. if (pgrp < 0) {
  3713. out:
  3714. ash_msg("can't access tty; job control turned off");
  3715. mflag = on = 0;
  3716. goto close;
  3717. }
  3718. if (pgrp == getpgrp())
  3719. break;
  3720. killpg(0, SIGTTIN);
  3721. }
  3722. initialpgrp = pgrp;
  3723. setsignal(SIGTSTP);
  3724. setsignal(SIGTTOU);
  3725. setsignal(SIGTTIN);
  3726. pgrp = rootpid;
  3727. setpgid(0, pgrp);
  3728. xtcsetpgrp(fd, pgrp);
  3729. } else {
  3730. /* turning job control off */
  3731. fd = ttyfd;
  3732. pgrp = initialpgrp;
  3733. /* was xtcsetpgrp, but this can make exiting ash
  3734. * loop forever if pty is already deleted */
  3735. tcsetpgrp(fd, pgrp);
  3736. setpgid(0, pgrp);
  3737. setsignal(SIGTSTP);
  3738. setsignal(SIGTTOU);
  3739. setsignal(SIGTTIN);
  3740. close:
  3741. if (fd >= 0)
  3742. close(fd);
  3743. fd = -1;
  3744. }
  3745. ttyfd = fd;
  3746. doing_jobctl = on;
  3747. }
  3748. static int FAST_FUNC
  3749. killcmd(int argc, char **argv)
  3750. {
  3751. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3752. int i = 1;
  3753. do {
  3754. if (argv[i][0] == '%') {
  3755. /*
  3756. * "kill %N" - job kill
  3757. * Converting to pgrp / pid kill
  3758. */
  3759. struct job *jp;
  3760. char *dst;
  3761. int j, n;
  3762. jp = getjob(argv[i], 0);
  3763. /*
  3764. * In jobs started under job control, we signal
  3765. * entire process group by kill -PGRP_ID.
  3766. * This happens, f.e., in interactive shell.
  3767. *
  3768. * Otherwise, we signal each child via
  3769. * kill PID1 PID2 PID3.
  3770. * Testcases:
  3771. * sh -c 'sleep 1|sleep 1 & kill %1'
  3772. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3773. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3774. */
  3775. n = jp->nprocs; /* can't be 0 (I hope) */
  3776. if (jp->jobctl)
  3777. n = 1;
  3778. dst = alloca(n * sizeof(int)*4);
  3779. argv[i] = dst;
  3780. for (j = 0; j < n; j++) {
  3781. struct procstat *ps = &jp->ps[j];
  3782. /* Skip non-running and not-stopped members
  3783. * (i.e. dead members) of the job
  3784. */
  3785. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3786. continue;
  3787. /*
  3788. * kill_main has matching code to expect
  3789. * leading space. Needed to not confuse
  3790. * negative pids with "kill -SIGNAL_NO" syntax
  3791. */
  3792. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3793. }
  3794. *dst = '\0';
  3795. }
  3796. } while (argv[++i]);
  3797. }
  3798. return kill_main(argc, argv);
  3799. }
  3800. static void
  3801. showpipe(struct job *jp /*, FILE *out*/)
  3802. {
  3803. struct procstat *ps;
  3804. struct procstat *psend;
  3805. psend = jp->ps + jp->nprocs;
  3806. for (ps = jp->ps + 1; ps < psend; ps++)
  3807. printf(" | %s", ps->ps_cmd);
  3808. newline_and_flush(stdout);
  3809. flush_stdout_stderr();
  3810. }
  3811. static int
  3812. restartjob(struct job *jp, int mode)
  3813. {
  3814. struct procstat *ps;
  3815. int i;
  3816. int status;
  3817. pid_t pgid;
  3818. INT_OFF;
  3819. if (jp->state == JOBDONE)
  3820. goto out;
  3821. jp->state = JOBRUNNING;
  3822. pgid = jp->ps[0].ps_pid;
  3823. if (mode == FORK_FG) {
  3824. get_tty_state();
  3825. xtcsetpgrp(ttyfd, pgid);
  3826. }
  3827. killpg(pgid, SIGCONT);
  3828. ps = jp->ps;
  3829. i = jp->nprocs;
  3830. do {
  3831. if (WIFSTOPPED(ps->ps_status)) {
  3832. ps->ps_status = -1;
  3833. }
  3834. ps++;
  3835. } while (--i);
  3836. out:
  3837. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3838. INT_ON;
  3839. return status;
  3840. }
  3841. static int FAST_FUNC
  3842. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3843. {
  3844. struct job *jp;
  3845. int mode;
  3846. int retval;
  3847. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3848. nextopt(nullstr);
  3849. argv = argptr;
  3850. do {
  3851. jp = getjob(*argv, 1);
  3852. if (mode == FORK_BG) {
  3853. set_curjob(jp, CUR_RUNNING);
  3854. printf("[%d] ", jobno(jp));
  3855. }
  3856. out1str(jp->ps[0].ps_cmd);
  3857. showpipe(jp /*, stdout*/);
  3858. retval = restartjob(jp, mode);
  3859. } while (*argv && *++argv);
  3860. return retval;
  3861. }
  3862. #endif
  3863. static int
  3864. sprint_status48(char *os, int status, int sigonly)
  3865. {
  3866. char *s = os;
  3867. int st;
  3868. if (!WIFEXITED(status)) {
  3869. #if JOBS
  3870. if (WIFSTOPPED(status))
  3871. st = WSTOPSIG(status);
  3872. else
  3873. #endif
  3874. st = WTERMSIG(status);
  3875. if (sigonly) {
  3876. if (st == SIGINT || st == SIGPIPE)
  3877. goto out;
  3878. #if JOBS
  3879. if (WIFSTOPPED(status))
  3880. goto out;
  3881. #endif
  3882. }
  3883. st &= 0x7f;
  3884. s = stpncpy(s, strsignal(st), 32);
  3885. if (WCOREDUMP(status)) {
  3886. s = stpcpy(s, " (core dumped)");
  3887. }
  3888. } else if (!sigonly) {
  3889. st = WEXITSTATUS(status);
  3890. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3891. }
  3892. out:
  3893. return s - os;
  3894. }
  3895. #define DOWAIT_NONBLOCK 0
  3896. #define DOWAIT_BLOCK 1
  3897. #define DOWAIT_BLOCK_OR_SIG 2
  3898. #if BASH_WAIT_N
  3899. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3900. #endif
  3901. static int
  3902. waitproc(int block, int *status)
  3903. {
  3904. sigset_t oldmask;
  3905. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3906. int err;
  3907. #if JOBS
  3908. if (doing_jobctl)
  3909. flags |= WUNTRACED;
  3910. #endif
  3911. do {
  3912. got_sigchld = 0;
  3913. do
  3914. err = waitpid(-1, status, flags);
  3915. while (err < 0 && errno == EINTR);
  3916. if (err || (err = -!block))
  3917. break;
  3918. sigfillset(&oldmask);
  3919. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3920. while (!got_sigchld && !pending_sig)
  3921. sigsuspend(&oldmask);
  3922. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3923. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3924. //while (!got_sigchld && !pending_sig)
  3925. // pause();
  3926. } while (got_sigchld);
  3927. return err;
  3928. }
  3929. static int
  3930. waitone(int block, struct job *job)
  3931. {
  3932. int pid;
  3933. int status;
  3934. struct job *jp;
  3935. struct job *thisjob = NULL;
  3936. #if BASH_WAIT_N
  3937. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3938. block = (block & ~DOWAIT_JOBSTATUS);
  3939. #endif
  3940. TRACE(("dowait(0x%x) called\n", block));
  3941. /* It's wrong to call waitpid() outside of INT_OFF region:
  3942. * signal can arrive just after syscall return and handler can
  3943. * longjmp away, losing stop/exit notification processing.
  3944. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3945. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3946. *
  3947. * However, for "wait" builtin it is wrong to simply call waitpid()
  3948. * in INT_OFF region: "wait" needs to wait for any running job
  3949. * to change state, but should exit on any trap too.
  3950. * In INT_OFF region, a signal just before syscall entry can set
  3951. * pending_sig variables, but we can't check them, and we would
  3952. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3953. *
  3954. * Because of this, we run inside INT_OFF, but use a special routine
  3955. * which combines waitpid() and sigsuspend().
  3956. * This is the reason why we need to have a handler for SIGCHLD:
  3957. * SIG_DFL handler does not wake sigsuspend().
  3958. */
  3959. INT_OFF;
  3960. pid = waitproc(block, &status);
  3961. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3962. if (pid <= 0)
  3963. goto out;
  3964. for (jp = curjob; jp; jp = jp->prev_job) {
  3965. int jobstate;
  3966. struct procstat *ps;
  3967. struct procstat *psend;
  3968. if (jp->state == JOBDONE)
  3969. continue;
  3970. jobstate = JOBDONE;
  3971. ps = jp->ps;
  3972. psend = ps + jp->nprocs;
  3973. do {
  3974. if (ps->ps_pid == pid) {
  3975. TRACE(("Job %d: changing status of proc %d "
  3976. "from 0x%x to 0x%x\n",
  3977. jobno(jp), pid, ps->ps_status, status));
  3978. ps->ps_status = status;
  3979. thisjob = jp;
  3980. }
  3981. if (ps->ps_status == -1)
  3982. jobstate = JOBRUNNING;
  3983. #if JOBS
  3984. if (jobstate == JOBRUNNING)
  3985. continue;
  3986. if (WIFSTOPPED(ps->ps_status)) {
  3987. jp->stopstatus = ps->ps_status;
  3988. jobstate = JOBSTOPPED;
  3989. }
  3990. #endif
  3991. } while (++ps < psend);
  3992. if (!thisjob)
  3993. continue;
  3994. /* Found the job where one of its processes changed its state.
  3995. * Is there at least one live and running process in this job? */
  3996. if (jobstate != JOBRUNNING) {
  3997. /* No. All live processes in the job are stopped
  3998. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3999. */
  4000. thisjob->changed = 1;
  4001. if (thisjob->state != jobstate) {
  4002. TRACE(("Job %d: changing state from %d to %d\n",
  4003. jobno(thisjob), thisjob->state, jobstate));
  4004. thisjob->state = jobstate;
  4005. #if JOBS
  4006. if (jobstate == JOBSTOPPED)
  4007. set_curjob(thisjob, CUR_STOPPED);
  4008. #endif
  4009. }
  4010. }
  4011. goto out;
  4012. }
  4013. /* The process wasn't found in job list */
  4014. out:
  4015. INT_ON;
  4016. #if BASH_WAIT_N
  4017. if (want_jobexitstatus) {
  4018. pid = -1;
  4019. if (thisjob && thisjob->state == JOBDONE)
  4020. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4021. }
  4022. #endif
  4023. if (thisjob && thisjob == job) {
  4024. char s[48 + 1];
  4025. int len;
  4026. len = sprint_status48(s, status, 1);
  4027. if (len) {
  4028. s[len] = '\n';
  4029. s[len + 1] = '\0';
  4030. out2str(s);
  4031. }
  4032. }
  4033. return pid;
  4034. }
  4035. static int
  4036. dowait(int block, struct job *jp)
  4037. {
  4038. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4039. int rpid;
  4040. int pid;
  4041. if (jp && jp->state != JOBRUNNING)
  4042. block = DOWAIT_NONBLOCK;
  4043. if (block == DOWAIT_NONBLOCK && !gotchld)
  4044. return 1;
  4045. rpid = 1;
  4046. do {
  4047. pid = waitone(block, jp);
  4048. rpid &= !!pid;
  4049. if (!pid || (jp && jp->state != JOBRUNNING))
  4050. block = DOWAIT_NONBLOCK;
  4051. } while (pid >= 0);
  4052. return rpid;
  4053. }
  4054. #if JOBS
  4055. static void
  4056. showjob(struct job *jp, int mode)
  4057. {
  4058. struct procstat *ps;
  4059. struct procstat *psend;
  4060. int col;
  4061. int indent_col;
  4062. char s[16 + 16 + 48];
  4063. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4064. ps = jp->ps;
  4065. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4066. /* just output process (group) id of pipeline */
  4067. fprintf(out, "%d\n", ps->ps_pid);
  4068. return;
  4069. }
  4070. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4071. indent_col = col;
  4072. if (jp == curjob)
  4073. s[col - 3] = '+';
  4074. else if (curjob && jp == curjob->prev_job)
  4075. s[col - 3] = '-';
  4076. if (mode & SHOW_PIDS)
  4077. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4078. psend = ps + jp->nprocs;
  4079. if (jp->state == JOBRUNNING) {
  4080. strcpy(s + col, "Running");
  4081. col += sizeof("Running") - 1;
  4082. } else {
  4083. int status = psend[-1].ps_status;
  4084. if (jp->state == JOBSTOPPED)
  4085. status = jp->stopstatus;
  4086. col += sprint_status48(s + col, status, 0);
  4087. }
  4088. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4089. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4090. * or prints several "PID | <cmdN>" lines,
  4091. * depending on SHOW_PIDS bit.
  4092. * We do not print status of individual processes
  4093. * between PID and <cmdN>. bash does it, but not very well:
  4094. * first line shows overall job status, not process status,
  4095. * making it impossible to know 1st process status.
  4096. */
  4097. goto start;
  4098. do {
  4099. /* for each process */
  4100. s[0] = '\0';
  4101. col = 33;
  4102. if (mode & SHOW_PIDS)
  4103. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4104. start:
  4105. fprintf(out, "%s%*c%s%s",
  4106. s,
  4107. 33 - col >= 0 ? 33 - col : 0, ' ',
  4108. ps == jp->ps ? "" : "| ",
  4109. ps->ps_cmd
  4110. );
  4111. } while (++ps != psend);
  4112. newline_and_flush(out);
  4113. jp->changed = 0;
  4114. if (jp->state == JOBDONE) {
  4115. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4116. freejob(jp);
  4117. }
  4118. }
  4119. /*
  4120. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4121. * statuses have changed since the last call to showjobs.
  4122. */
  4123. static void
  4124. showjobs(int mode)
  4125. {
  4126. struct job *jp;
  4127. TRACE(("showjobs(0x%x) called\n", mode));
  4128. /* Handle all finished jobs */
  4129. dowait(DOWAIT_NONBLOCK, NULL);
  4130. for (jp = curjob; jp; jp = jp->prev_job) {
  4131. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4132. showjob(jp, mode);
  4133. }
  4134. }
  4135. }
  4136. static int FAST_FUNC
  4137. jobscmd(int argc UNUSED_PARAM, char **argv)
  4138. {
  4139. int mode, m;
  4140. mode = 0;
  4141. while ((m = nextopt("lp")) != '\0') {
  4142. if (m == 'l')
  4143. mode |= SHOW_PIDS;
  4144. else
  4145. mode |= SHOW_ONLY_PGID;
  4146. }
  4147. argv = argptr;
  4148. if (*argv) {
  4149. do
  4150. showjob(getjob(*argv, 0), mode);
  4151. while (*++argv);
  4152. } else {
  4153. showjobs(mode);
  4154. }
  4155. return 0;
  4156. }
  4157. #endif /* JOBS */
  4158. /* Called only on finished or stopped jobs (no members are running) */
  4159. static int
  4160. getstatus(struct job *job)
  4161. {
  4162. int status;
  4163. int retval;
  4164. struct procstat *ps;
  4165. /* Fetch last member's status */
  4166. ps = job->ps + job->nprocs - 1;
  4167. status = ps->ps_status;
  4168. if (pipefail) {
  4169. /* "set -o pipefail" mode: use last _nonzero_ status */
  4170. while (status == 0 && --ps >= job->ps)
  4171. status = ps->ps_status;
  4172. }
  4173. retval = WEXITSTATUS(status);
  4174. if (!WIFEXITED(status)) {
  4175. #if JOBS
  4176. retval = WSTOPSIG(status);
  4177. if (!WIFSTOPPED(status))
  4178. #endif
  4179. {
  4180. /* XXX: limits number of signals */
  4181. retval = WTERMSIG(status);
  4182. #if JOBS
  4183. if (retval == SIGINT)
  4184. job->sigint = 1;
  4185. #endif
  4186. }
  4187. retval |= 128;
  4188. }
  4189. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4190. jobno(job), job->nprocs, status, retval));
  4191. return retval;
  4192. }
  4193. static int FAST_FUNC
  4194. waitcmd(int argc UNUSED_PARAM, char **argv)
  4195. {
  4196. struct job *job;
  4197. int retval;
  4198. struct job *jp;
  4199. #if BASH_WAIT_N
  4200. int status;
  4201. char one = nextopt("n");
  4202. #else
  4203. nextopt(nullstr);
  4204. #endif
  4205. retval = 0;
  4206. argv = argptr;
  4207. if (!argv[0]) {
  4208. /* wait for all jobs / one job if -n */
  4209. for (;;) {
  4210. jp = curjob;
  4211. #if BASH_WAIT_N
  4212. if (one && !jp)
  4213. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4214. retval = 127;
  4215. #endif
  4216. while (1) {
  4217. if (!jp) /* no running procs */
  4218. goto ret;
  4219. if (jp->state == JOBRUNNING)
  4220. break;
  4221. jp->waited = 1;
  4222. jp = jp->prev_job;
  4223. }
  4224. /* man bash:
  4225. * "When bash is waiting for an asynchronous command via
  4226. * the wait builtin, the reception of a signal for which a trap
  4227. * has been set will cause the wait builtin to return immediately
  4228. * with an exit status greater than 128, immediately after which
  4229. * the trap is executed."
  4230. */
  4231. #if BASH_WAIT_N
  4232. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4233. #else
  4234. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4235. #endif
  4236. /* if child sends us a signal *and immediately exits*,
  4237. * dowait() returns pid > 0. Check this case,
  4238. * not "if (dowait() < 0)"!
  4239. */
  4240. if (pending_sig)
  4241. goto sigout;
  4242. #if BASH_WAIT_N
  4243. if (one) {
  4244. /* wait -n waits for one _job_, not one _process_.
  4245. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4246. * should wait for 2 seconds. Not 1 or 3.
  4247. */
  4248. if (status != -1 && !WIFSTOPPED(status)) {
  4249. retval = WEXITSTATUS(status);
  4250. if (WIFSIGNALED(status))
  4251. retval = 128 | WTERMSIG(status);
  4252. goto ret;
  4253. }
  4254. }
  4255. #endif
  4256. }
  4257. }
  4258. retval = 127;
  4259. do {
  4260. if (**argv != '%') {
  4261. pid_t pid = number(*argv);
  4262. job = curjob;
  4263. while (1) {
  4264. if (!job)
  4265. goto repeat;
  4266. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4267. break;
  4268. job = job->prev_job;
  4269. }
  4270. } else {
  4271. job = getjob(*argv, 0);
  4272. }
  4273. /* loop until process terminated or stopped */
  4274. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4275. if (pending_sig)
  4276. goto sigout;
  4277. job->waited = 1;
  4278. retval = getstatus(job);
  4279. repeat: ;
  4280. } while (*++argv);
  4281. ret:
  4282. return retval;
  4283. sigout:
  4284. retval = 128 | pending_sig;
  4285. return retval;
  4286. }
  4287. static struct job *
  4288. growjobtab(void)
  4289. {
  4290. size_t len;
  4291. ptrdiff_t offset;
  4292. struct job *jp, *jq;
  4293. len = njobs * sizeof(*jp);
  4294. jq = jobtab;
  4295. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4296. offset = (char *)jp - (char *)jq;
  4297. if (offset) {
  4298. /* Relocate pointers */
  4299. size_t l = len;
  4300. jq = (struct job *)((char *)jq + l);
  4301. while (l) {
  4302. l -= sizeof(*jp);
  4303. jq--;
  4304. #define joff(p) ((struct job *)((char *)(p) + l))
  4305. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4306. if (joff(jp)->ps == &jq->ps0)
  4307. jmove(joff(jp)->ps);
  4308. if (joff(jp)->prev_job)
  4309. jmove(joff(jp)->prev_job);
  4310. }
  4311. if (curjob)
  4312. jmove(curjob);
  4313. #undef joff
  4314. #undef jmove
  4315. }
  4316. njobs += 4;
  4317. jobtab = jp;
  4318. jp = (struct job *)((char *)jp + len);
  4319. jq = jp + 3;
  4320. do {
  4321. jq->used = 0;
  4322. } while (--jq >= jp);
  4323. return jp;
  4324. }
  4325. /*
  4326. * Return a new job structure.
  4327. * Called with interrupts off.
  4328. */
  4329. static struct job *
  4330. makejob(/*union node *node,*/ int nprocs)
  4331. {
  4332. int i;
  4333. struct job *jp;
  4334. for (i = njobs, jp = jobtab; ; jp++) {
  4335. if (--i < 0) {
  4336. jp = growjobtab();
  4337. break;
  4338. }
  4339. if (jp->used == 0)
  4340. break;
  4341. if (jp->state != JOBDONE || !jp->waited)
  4342. continue;
  4343. #if JOBS
  4344. if (doing_jobctl)
  4345. continue;
  4346. #endif
  4347. freejob(jp);
  4348. break;
  4349. }
  4350. memset(jp, 0, sizeof(*jp));
  4351. #if JOBS
  4352. /* jp->jobctl is a bitfield.
  4353. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4354. if (doing_jobctl)
  4355. jp->jobctl = 1;
  4356. #endif
  4357. jp->prev_job = curjob;
  4358. curjob = jp;
  4359. jp->used = 1;
  4360. jp->ps = &jp->ps0;
  4361. if (nprocs > 1) {
  4362. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4363. }
  4364. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4365. jobno(jp)));
  4366. return jp;
  4367. }
  4368. #if JOBS
  4369. /*
  4370. * Return a string identifying a command (to be printed by the
  4371. * jobs command).
  4372. */
  4373. static char *cmdnextc;
  4374. static void
  4375. cmdputs(const char *s)
  4376. {
  4377. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4378. "", "}", "-", "+", "?", "=",
  4379. "%", "%%", "#", "##"
  4380. IF_BASH_SUBSTR(, ":")
  4381. IF_BASH_PATTERN_SUBST(, "/", "//")
  4382. };
  4383. const char *p, *str;
  4384. char cc[2];
  4385. char *nextc;
  4386. unsigned char c;
  4387. unsigned char subtype = 0;
  4388. int quoted = 0;
  4389. cc[1] = '\0';
  4390. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4391. p = s;
  4392. while ((c = *p++) != '\0') {
  4393. str = NULL;
  4394. switch (c) {
  4395. case CTLESC:
  4396. c = *p++;
  4397. break;
  4398. case CTLVAR:
  4399. subtype = *p++;
  4400. if ((subtype & VSTYPE) == VSLENGTH)
  4401. str = "${#";
  4402. else
  4403. str = "${";
  4404. goto dostr;
  4405. case CTLENDVAR:
  4406. str = "\"}";
  4407. str += !(quoted & 1);
  4408. quoted >>= 1;
  4409. subtype = 0;
  4410. goto dostr;
  4411. #if BASH_PROCESS_SUBST
  4412. case CTLBACKQ:
  4413. c = '$';
  4414. str = "(...)";
  4415. break;
  4416. case CTLTOPROC:
  4417. c = '>';
  4418. str = "(...)";
  4419. break;
  4420. case CTLFROMPROC:
  4421. c = '<';
  4422. str = "(...)";
  4423. break;
  4424. #else
  4425. case CTLBACKQ:
  4426. str = "$(...)";
  4427. goto dostr;
  4428. #endif
  4429. #if ENABLE_FEATURE_SH_MATH
  4430. case CTLARI:
  4431. str = "$((";
  4432. goto dostr;
  4433. case CTLENDARI:
  4434. str = "))";
  4435. goto dostr;
  4436. #endif
  4437. case CTLQUOTEMARK:
  4438. quoted ^= 1;
  4439. c = '"';
  4440. break;
  4441. case '=':
  4442. if (subtype == 0)
  4443. break;
  4444. if ((subtype & VSTYPE) != VSNORMAL)
  4445. quoted <<= 1;
  4446. str = vstype[subtype & VSTYPE];
  4447. if (subtype & VSNUL)
  4448. c = ':';
  4449. else
  4450. goto checkstr;
  4451. break;
  4452. case '\'':
  4453. case '\\':
  4454. case '"':
  4455. case '$':
  4456. /* These can only happen inside quotes */
  4457. cc[0] = c;
  4458. str = cc;
  4459. //FIXME:
  4460. // $ true $$ &
  4461. // $ <cr>
  4462. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4463. c = '\\';
  4464. break;
  4465. default:
  4466. break;
  4467. }
  4468. USTPUTC(c, nextc);
  4469. checkstr:
  4470. if (!str)
  4471. continue;
  4472. dostr:
  4473. while ((c = *str++) != '\0') {
  4474. USTPUTC(c, nextc);
  4475. }
  4476. } /* while *p++ not NUL */
  4477. if (quoted & 1) {
  4478. USTPUTC('"', nextc);
  4479. }
  4480. *nextc = 0;
  4481. cmdnextc = nextc;
  4482. }
  4483. /* cmdtxt() and cmdlist() call each other */
  4484. static void cmdtxt(union node *n);
  4485. static void
  4486. cmdlist(union node *np, int sep)
  4487. {
  4488. for (; np; np = np->narg.next) {
  4489. if (!sep)
  4490. cmdputs(" ");
  4491. cmdtxt(np);
  4492. if (sep && np->narg.next)
  4493. cmdputs(" ");
  4494. }
  4495. }
  4496. static void
  4497. cmdtxt(union node *n)
  4498. {
  4499. union node *np;
  4500. struct nodelist *lp;
  4501. const char *p;
  4502. if (!n)
  4503. return;
  4504. switch (n->type) {
  4505. default:
  4506. #if DEBUG
  4507. abort();
  4508. #endif
  4509. case NPIPE:
  4510. lp = n->npipe.cmdlist;
  4511. for (;;) {
  4512. cmdtxt(lp->n);
  4513. lp = lp->next;
  4514. if (!lp)
  4515. break;
  4516. cmdputs(" | ");
  4517. }
  4518. break;
  4519. case NSEMI:
  4520. p = "; ";
  4521. goto binop;
  4522. case NAND:
  4523. p = " && ";
  4524. goto binop;
  4525. case NOR:
  4526. p = " || ";
  4527. binop:
  4528. cmdtxt(n->nbinary.ch1);
  4529. cmdputs(p);
  4530. n = n->nbinary.ch2;
  4531. goto donode;
  4532. case NREDIR:
  4533. case NBACKGND:
  4534. n = n->nredir.n;
  4535. goto donode;
  4536. case NNOT:
  4537. cmdputs("!");
  4538. n = n->nnot.com;
  4539. donode:
  4540. cmdtxt(n);
  4541. break;
  4542. case NIF:
  4543. cmdputs("if ");
  4544. cmdtxt(n->nif.test);
  4545. cmdputs("; then ");
  4546. if (n->nif.elsepart) {
  4547. cmdtxt(n->nif.ifpart);
  4548. cmdputs("; else ");
  4549. n = n->nif.elsepart;
  4550. } else {
  4551. n = n->nif.ifpart;
  4552. }
  4553. p = "; fi";
  4554. goto dotail;
  4555. case NSUBSHELL:
  4556. cmdputs("(");
  4557. n = n->nredir.n;
  4558. p = ")";
  4559. goto dotail;
  4560. case NWHILE:
  4561. p = "while ";
  4562. goto until;
  4563. case NUNTIL:
  4564. p = "until ";
  4565. until:
  4566. cmdputs(p);
  4567. cmdtxt(n->nbinary.ch1);
  4568. n = n->nbinary.ch2;
  4569. p = "; done";
  4570. dodo:
  4571. cmdputs("; do ");
  4572. dotail:
  4573. cmdtxt(n);
  4574. goto dotail2;
  4575. case NFOR:
  4576. cmdputs("for ");
  4577. cmdputs(n->nfor.var);
  4578. cmdputs(" in ");
  4579. cmdlist(n->nfor.args, 1);
  4580. n = n->nfor.body;
  4581. p = "; done";
  4582. goto dodo;
  4583. case NDEFUN:
  4584. cmdputs(n->ndefun.text);
  4585. p = "() { ... }";
  4586. goto dotail2;
  4587. case NCMD:
  4588. cmdlist(n->ncmd.args, 1);
  4589. cmdlist(n->ncmd.redirect, 0);
  4590. break;
  4591. case NARG:
  4592. p = n->narg.text;
  4593. dotail2:
  4594. cmdputs(p);
  4595. break;
  4596. case NHERE:
  4597. case NXHERE:
  4598. p = "<<...";
  4599. goto dotail2;
  4600. case NCASE:
  4601. cmdputs("case ");
  4602. cmdputs(n->ncase.expr->narg.text);
  4603. cmdputs(" in ");
  4604. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4605. cmdtxt(np->nclist.pattern);
  4606. cmdputs(") ");
  4607. cmdtxt(np->nclist.body);
  4608. cmdputs(";; ");
  4609. }
  4610. p = "esac";
  4611. goto dotail2;
  4612. case NTO:
  4613. p = ">";
  4614. goto redir;
  4615. case NCLOBBER:
  4616. p = ">|";
  4617. goto redir;
  4618. case NAPPEND:
  4619. p = ">>";
  4620. goto redir;
  4621. #if BASH_REDIR_OUTPUT
  4622. case NTO2:
  4623. #endif
  4624. case NTOFD:
  4625. p = ">&";
  4626. goto redir;
  4627. case NFROM:
  4628. p = "<";
  4629. goto redir;
  4630. case NFROMFD:
  4631. p = "<&";
  4632. goto redir;
  4633. case NFROMTO:
  4634. p = "<>";
  4635. redir:
  4636. cmdputs(utoa(n->nfile.fd));
  4637. cmdputs(p);
  4638. if (n->type == NTOFD || n->type == NFROMFD) {
  4639. if (n->ndup.dupfd >= 0)
  4640. cmdputs(utoa(n->ndup.dupfd));
  4641. else
  4642. cmdputs("-");
  4643. break;
  4644. }
  4645. n = n->nfile.fname;
  4646. goto donode;
  4647. }
  4648. }
  4649. static char *
  4650. commandtext(union node *n)
  4651. {
  4652. char *name;
  4653. STARTSTACKSTR(cmdnextc);
  4654. cmdtxt(n);
  4655. name = stackblock();
  4656. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4657. return ckstrdup(name);
  4658. }
  4659. #endif /* JOBS */
  4660. /*
  4661. * Fork off a subshell. If we are doing job control, give the subshell its
  4662. * own process group. Jp is a job structure that the job is to be added to.
  4663. * N is the command that will be evaluated by the child. Both jp and n may
  4664. * be NULL. The mode parameter can be one of the following:
  4665. * FORK_FG - Fork off a foreground process.
  4666. * FORK_BG - Fork off a background process.
  4667. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4668. * process group even if job control is on.
  4669. *
  4670. * When job control is turned off, background processes have their standard
  4671. * input redirected to /dev/null (except for the second and later processes
  4672. * in a pipeline).
  4673. *
  4674. * Called with interrupts off.
  4675. */
  4676. /*
  4677. * Clear traps on a fork.
  4678. */
  4679. static void
  4680. clear_traps(void)
  4681. {
  4682. char **tp;
  4683. INT_OFF;
  4684. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4685. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4686. if (trap_ptr == trap)
  4687. free(*tp);
  4688. /* else: it "belongs" to trap_ptr vector, don't free */
  4689. *tp = NULL;
  4690. if ((tp - trap) != 0)
  4691. setsignal(tp - trap);
  4692. }
  4693. }
  4694. may_have_traps = 0;
  4695. INT_ON;
  4696. }
  4697. /* Lives far away from here, needed for forkchild */
  4698. static void closescript(void);
  4699. /* Called after fork(), in child */
  4700. /* jp and n are NULL when called by openhere() for heredoc support */
  4701. static NOINLINE void
  4702. forkchild(struct job *jp, union node *n, int mode)
  4703. {
  4704. int oldlvl;
  4705. TRACE(("Child shell %d\n", getpid()));
  4706. oldlvl = shlvl;
  4707. shlvl++;
  4708. /* man bash: "Non-builtin commands run by bash have signal handlers
  4709. * set to the values inherited by the shell from its parent".
  4710. * Do we do it correctly? */
  4711. closescript();
  4712. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4713. && n && n->type == NCMD /* is it single cmd? */
  4714. /* && n->ncmd.args->type == NARG - always true? */
  4715. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4716. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4717. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4718. ) {
  4719. TRACE(("Trap hack\n"));
  4720. /* Awful hack for `trap` or $(trap).
  4721. *
  4722. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4723. * contains an example where "trap" is executed in a subshell:
  4724. *
  4725. * save_traps=$(trap)
  4726. * ...
  4727. * eval "$save_traps"
  4728. *
  4729. * Standard does not say that "trap" in subshell shall print
  4730. * parent shell's traps. It only says that its output
  4731. * must have suitable form, but then, in the above example
  4732. * (which is not supposed to be normative), it implies that.
  4733. *
  4734. * bash (and probably other shell) does implement it
  4735. * (traps are reset to defaults, but "trap" still shows them),
  4736. * but as a result, "trap" logic is hopelessly messed up:
  4737. *
  4738. * # trap
  4739. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4740. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4741. * # true | trap <--- trap is in subshell - no output (ditto)
  4742. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4743. * trap -- 'echo Ho' SIGWINCH
  4744. * # echo `(trap)` <--- in subshell in subshell - output
  4745. * trap -- 'echo Ho' SIGWINCH
  4746. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4747. * trap -- 'echo Ho' SIGWINCH
  4748. *
  4749. * The rules when to forget and when to not forget traps
  4750. * get really complex and nonsensical.
  4751. *
  4752. * Our solution: ONLY bare $(trap) or `trap` is special.
  4753. */
  4754. /* Save trap handler strings for trap builtin to print */
  4755. trap_ptr = xmemdup(trap, sizeof(trap));
  4756. /* Fall through into clearing traps */
  4757. }
  4758. clear_traps();
  4759. #if JOBS
  4760. /* do job control only in root shell */
  4761. doing_jobctl = 0;
  4762. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4763. pid_t pgrp;
  4764. if (jp->nprocs == 0)
  4765. pgrp = getpid();
  4766. else
  4767. pgrp = jp->ps[0].ps_pid;
  4768. /* this can fail because we are doing it in the parent also */
  4769. setpgid(0, pgrp);
  4770. if (mode == FORK_FG)
  4771. xtcsetpgrp(ttyfd, pgrp);
  4772. setsignal(SIGTSTP);
  4773. setsignal(SIGTTOU);
  4774. } else
  4775. #endif
  4776. if (mode == FORK_BG) {
  4777. /* man bash: "When job control is not in effect,
  4778. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4779. ignoresig(SIGINT);
  4780. ignoresig(SIGQUIT);
  4781. if (jp->nprocs == 0) {
  4782. close(0);
  4783. if (open(bb_dev_null, O_RDONLY) != 0)
  4784. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4785. }
  4786. }
  4787. if (oldlvl == 0) {
  4788. if (iflag) { /* why if iflag only? */
  4789. setsignal(SIGINT);
  4790. setsignal(SIGTERM);
  4791. }
  4792. /* man bash:
  4793. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4794. * commands run by bash have signal handlers
  4795. * set to the values inherited by the shell
  4796. * from its parent".
  4797. * Take care of the second rule: */
  4798. setsignal(SIGQUIT);
  4799. }
  4800. #if JOBS
  4801. if (n && n->type == NCMD
  4802. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4803. ) {
  4804. TRACE(("Job hack\n"));
  4805. /* "jobs": we do not want to clear job list for it,
  4806. * instead we remove only _its_ own_ job from job list.
  4807. * This makes "jobs .... | cat" more useful.
  4808. */
  4809. freejob(curjob);
  4810. return;
  4811. }
  4812. #endif
  4813. for (jp = curjob; jp; jp = jp->prev_job)
  4814. freejob(jp);
  4815. }
  4816. /* Called after fork(), in parent */
  4817. #if !JOBS
  4818. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4819. #endif
  4820. static void
  4821. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4822. {
  4823. TRACE(("In parent shell: child = %d\n", pid));
  4824. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4825. return;
  4826. #if JOBS
  4827. if (mode != FORK_NOJOB && jp->jobctl) {
  4828. int pgrp;
  4829. if (jp->nprocs == 0)
  4830. pgrp = pid;
  4831. else
  4832. pgrp = jp->ps[0].ps_pid;
  4833. /* This can fail because we are doing it in the child also */
  4834. setpgid(pid, pgrp);
  4835. }
  4836. #endif
  4837. if (mode == FORK_BG) {
  4838. backgndpid = pid; /* set $! */
  4839. set_curjob(jp, CUR_RUNNING);
  4840. }
  4841. if (jp) {
  4842. struct procstat *ps = &jp->ps[jp->nprocs++];
  4843. ps->ps_pid = pid;
  4844. ps->ps_status = -1;
  4845. ps->ps_cmd = nullstr;
  4846. #if JOBS
  4847. if (doing_jobctl && n)
  4848. ps->ps_cmd = commandtext(n);
  4849. #endif
  4850. }
  4851. }
  4852. /* jp and n are NULL when called by openhere() for heredoc support */
  4853. static int
  4854. forkshell(struct job *jp, union node *n, int mode)
  4855. {
  4856. int pid;
  4857. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4858. pid = fork();
  4859. if (pid < 0) {
  4860. TRACE(("Fork failed, errno=%d", errno));
  4861. if (jp)
  4862. freejob(jp);
  4863. ash_msg_and_raise_perror("can't fork");
  4864. }
  4865. if (pid == 0) {
  4866. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4867. forkchild(jp, n, mode);
  4868. } else {
  4869. forkparent(jp, n, mode, pid);
  4870. }
  4871. return pid;
  4872. }
  4873. /*
  4874. * Wait for job to finish.
  4875. *
  4876. * Under job control we have the problem that while a child process
  4877. * is running interrupts generated by the user are sent to the child
  4878. * but not to the shell. This means that an infinite loop started by
  4879. * an interactive user may be hard to kill. With job control turned off,
  4880. * an interactive user may place an interactive program inside a loop.
  4881. * If the interactive program catches interrupts, the user doesn't want
  4882. * these interrupts to also abort the loop. The approach we take here
  4883. * is to have the shell ignore interrupt signals while waiting for a
  4884. * foreground process to terminate, and then send itself an interrupt
  4885. * signal if the child process was terminated by an interrupt signal.
  4886. * Unfortunately, some programs want to do a bit of cleanup and then
  4887. * exit on interrupt; unless these processes terminate themselves by
  4888. * sending a signal to themselves (instead of calling exit) they will
  4889. * confuse this approach.
  4890. *
  4891. * Called with interrupts off.
  4892. */
  4893. static int
  4894. waitforjob(struct job *jp)
  4895. {
  4896. int st;
  4897. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4898. /* In non-interactive shells, we _can_ get
  4899. * a keyboard signal here and be EINTRed, but we just loop
  4900. * inside dowait(), waiting for command to complete.
  4901. *
  4902. * man bash:
  4903. * "If bash is waiting for a command to complete and receives
  4904. * a signal for which a trap has been set, the trap
  4905. * will not be executed until the command completes."
  4906. *
  4907. * Reality is that even if trap is not set, bash
  4908. * will not act on the signal until command completes.
  4909. * Try this. sleep5intoff.c:
  4910. * #include <signal.h>
  4911. * #include <unistd.h>
  4912. * int main() {
  4913. * sigset_t set;
  4914. * sigemptyset(&set);
  4915. * sigaddset(&set, SIGINT);
  4916. * sigaddset(&set, SIGQUIT);
  4917. * sigprocmask(SIG_BLOCK, &set, NULL);
  4918. * sleep(5);
  4919. * return 0;
  4920. * }
  4921. * $ bash -c './sleep5intoff; echo hi'
  4922. * ^C^C^C^C <--- pressing ^C once a second
  4923. * $ _
  4924. * $ bash -c './sleep5intoff; echo hi'
  4925. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4926. * $ _
  4927. */
  4928. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4929. if (!jp)
  4930. return exitstatus;
  4931. st = getstatus(jp);
  4932. #if JOBS
  4933. if (jp->jobctl) {
  4934. xtcsetpgrp(ttyfd, rootpid);
  4935. restore_tty_if_stopped_or_signaled(jp);
  4936. /*
  4937. * This is truly gross.
  4938. * If we're doing job control, then we did a TIOCSPGRP which
  4939. * caused us (the shell) to no longer be in the controlling
  4940. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4941. * intuit from the subprocess exit status whether a SIGINT
  4942. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4943. */
  4944. if (jp->sigint) /* TODO: do the same with all signals */
  4945. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4946. }
  4947. if (jp->state == JOBDONE)
  4948. #endif
  4949. freejob(jp);
  4950. return st;
  4951. }
  4952. /*
  4953. * return 1 if there are stopped jobs, otherwise 0
  4954. */
  4955. static int
  4956. stoppedjobs(void)
  4957. {
  4958. struct job *jp;
  4959. int retval;
  4960. retval = 0;
  4961. if (job_warning)
  4962. goto out;
  4963. jp = curjob;
  4964. if (jp && jp->state == JOBSTOPPED) {
  4965. out2str("You have stopped jobs.\n");
  4966. job_warning = 2;
  4967. retval++;
  4968. }
  4969. out:
  4970. return retval;
  4971. }
  4972. /*
  4973. * Code for dealing with input/output redirection.
  4974. */
  4975. #undef EMPTY
  4976. #undef CLOSED
  4977. #define EMPTY -2 /* marks an unused slot in redirtab */
  4978. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4979. /*
  4980. * Handle here documents. Normally we fork off a process to write the
  4981. * data to a pipe. If the document is short, we can stuff the data in
  4982. * the pipe without forking.
  4983. */
  4984. /* openhere needs this forward reference */
  4985. static void expandhere(union node *arg);
  4986. static int
  4987. openhere(union node *redir)
  4988. {
  4989. char *p;
  4990. int pip[2];
  4991. size_t len = 0;
  4992. if (pipe(pip) < 0)
  4993. ash_msg_and_raise_perror("can't create pipe");
  4994. p = redir->nhere.doc->narg.text;
  4995. if (redir->type == NXHERE) {
  4996. expandhere(redir->nhere.doc);
  4997. p = stackblock();
  4998. }
  4999. len = strlen(p);
  5000. if (len <= PIPE_BUF) {
  5001. xwrite(pip[1], p, len);
  5002. goto out;
  5003. }
  5004. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  5005. /* child */
  5006. close(pip[0]);
  5007. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  5008. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  5009. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  5010. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  5011. signal(SIGPIPE, SIG_DFL);
  5012. xwrite(pip[1], p, len);
  5013. _exit(EXIT_SUCCESS);
  5014. }
  5015. out:
  5016. close(pip[1]);
  5017. return pip[0];
  5018. }
  5019. static int
  5020. openredirect(union node *redir)
  5021. {
  5022. struct stat sb;
  5023. char *fname;
  5024. int f;
  5025. switch (redir->nfile.type) {
  5026. /* Can't happen, our single caller does this itself */
  5027. // case NTOFD:
  5028. // case NFROMFD:
  5029. // return -1;
  5030. case NHERE:
  5031. case NXHERE:
  5032. return openhere(redir);
  5033. }
  5034. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  5035. * allocated space. Do it only when we know it is safe.
  5036. */
  5037. fname = redir->nfile.expfname;
  5038. switch (redir->nfile.type) {
  5039. default:
  5040. #if DEBUG
  5041. abort();
  5042. #endif
  5043. case NFROM:
  5044. f = open(fname, O_RDONLY);
  5045. if (f < 0)
  5046. goto eopen;
  5047. break;
  5048. case NFROMTO:
  5049. f = open(fname, O_RDWR|O_CREAT, 0666);
  5050. if (f < 0)
  5051. goto ecreate;
  5052. break;
  5053. case NTO:
  5054. #if BASH_REDIR_OUTPUT
  5055. case NTO2:
  5056. #endif
  5057. /* Take care of noclobber mode. */
  5058. if (Cflag) {
  5059. if (stat(fname, &sb) < 0) {
  5060. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5061. if (f < 0)
  5062. goto ecreate;
  5063. } else if (!S_ISREG(sb.st_mode)) {
  5064. f = open(fname, O_WRONLY, 0666);
  5065. if (f < 0)
  5066. goto ecreate;
  5067. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5068. close(f);
  5069. errno = EEXIST;
  5070. goto ecreate;
  5071. }
  5072. } else {
  5073. errno = EEXIST;
  5074. goto ecreate;
  5075. }
  5076. break;
  5077. }
  5078. /* FALLTHROUGH */
  5079. case NCLOBBER:
  5080. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5081. if (f < 0)
  5082. goto ecreate;
  5083. break;
  5084. case NAPPEND:
  5085. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5086. if (f < 0)
  5087. goto ecreate;
  5088. break;
  5089. }
  5090. return f;
  5091. ecreate:
  5092. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5093. eopen:
  5094. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5095. }
  5096. /*
  5097. * Copy a file descriptor to be >= 10. Throws exception on error.
  5098. */
  5099. static int
  5100. savefd(int from)
  5101. {
  5102. int newfd;
  5103. int err;
  5104. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5105. err = newfd < 0 ? errno : 0;
  5106. if (err != EBADF) {
  5107. if (err)
  5108. ash_msg_and_raise_perror("%d", from);
  5109. close(from);
  5110. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5111. close_on_exec_on(newfd);
  5112. }
  5113. return newfd;
  5114. }
  5115. static int
  5116. dup2_or_raise(int from, int to)
  5117. {
  5118. int newfd;
  5119. newfd = (from != to) ? dup2(from, to) : to;
  5120. if (newfd < 0) {
  5121. /* Happens when source fd is not open: try "echo >&99" */
  5122. ash_msg_and_raise_perror("%d", from);
  5123. }
  5124. return newfd;
  5125. }
  5126. static int
  5127. dup_CLOEXEC(int fd, int avoid_fd)
  5128. {
  5129. int newfd;
  5130. repeat:
  5131. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5132. if (newfd >= 0) {
  5133. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5134. close_on_exec_on(newfd);
  5135. } else { /* newfd < 0 */
  5136. if (errno == EBUSY)
  5137. goto repeat;
  5138. if (errno == EINTR)
  5139. goto repeat;
  5140. }
  5141. return newfd;
  5142. }
  5143. static int
  5144. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5145. {
  5146. int newfd;
  5147. repeat:
  5148. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5149. if (newfd < 0) {
  5150. if (errno == EBUSY)
  5151. goto repeat;
  5152. if (errno == EINTR)
  5153. goto repeat;
  5154. /* fd was not open? */
  5155. if (errno == EBADF)
  5156. return fd;
  5157. ash_msg_and_raise_perror("%d", newfd);
  5158. }
  5159. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5160. close_on_exec_on(newfd);
  5161. close(fd);
  5162. return newfd;
  5163. }
  5164. /* Struct def and variable are moved down to the first usage site */
  5165. struct squirrel {
  5166. int orig_fd;
  5167. int moved_to;
  5168. };
  5169. struct redirtab {
  5170. struct redirtab *next;
  5171. int pair_count;
  5172. struct squirrel two_fd[];
  5173. };
  5174. #define redirlist (G_var.redirlist)
  5175. static void
  5176. add_squirrel_closed(struct redirtab *sq, int fd)
  5177. {
  5178. int i;
  5179. if (!sq)
  5180. return;
  5181. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5182. /* If we collide with an already moved fd... */
  5183. if (fd == sq->two_fd[i].orig_fd) {
  5184. /* Examples:
  5185. * "echo 3>FILE 3>&- 3>FILE"
  5186. * "echo 3>&- 3>FILE"
  5187. * No need for last redirect to insert
  5188. * another "need to close 3" indicator.
  5189. */
  5190. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5191. return;
  5192. }
  5193. }
  5194. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5195. sq->two_fd[i].orig_fd = fd;
  5196. sq->two_fd[i].moved_to = CLOSED;
  5197. }
  5198. static int
  5199. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5200. {
  5201. int i, new_fd;
  5202. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5203. avoid_fd = 9;
  5204. #if JOBS
  5205. if (fd == ttyfd) {
  5206. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5207. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5208. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5209. return 1; /* "we closed fd" */
  5210. }
  5211. #endif
  5212. /* Are we called from redirect(0)? E.g. redirect
  5213. * in a forked child. No need to save fds,
  5214. * we aren't going to use them anymore, ok to trash.
  5215. */
  5216. if (!sq)
  5217. return 0;
  5218. /* If this one of script's fds? */
  5219. if (fd != 0) {
  5220. struct parsefile *pf = g_parsefile;
  5221. while (pf) {
  5222. /* We skip fd == 0 case because of the following:
  5223. * $ ash # running ash interactively
  5224. * $ . ./script.sh
  5225. * and in script.sh: "exec 9>&0".
  5226. * Even though top-level pf_fd _is_ 0,
  5227. * it's still ok to use it: "read" builtin uses it,
  5228. * why should we cripple "exec" builtin?
  5229. */
  5230. if (fd == pf->pf_fd) {
  5231. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5232. return 1; /* "we closed fd" */
  5233. }
  5234. pf = pf->prev;
  5235. }
  5236. }
  5237. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5238. /* First: do we collide with some already moved fds? */
  5239. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5240. /* If we collide with an already moved fd... */
  5241. if (fd == sq->two_fd[i].moved_to) {
  5242. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5243. sq->two_fd[i].moved_to = new_fd;
  5244. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5245. if (new_fd < 0) /* what? */
  5246. xfunc_die();
  5247. return 0; /* "we did not close fd" */
  5248. }
  5249. if (fd == sq->two_fd[i].orig_fd) {
  5250. /* Example: echo Hello >/dev/null 1>&2 */
  5251. TRACE(("redirect_fd %d: already moved\n", fd));
  5252. return 0; /* "we did not close fd" */
  5253. }
  5254. }
  5255. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5256. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5257. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5258. if (new_fd < 0) {
  5259. if (errno != EBADF)
  5260. xfunc_die();
  5261. /* new_fd = CLOSED; - already is -1 */
  5262. }
  5263. sq->two_fd[i].moved_to = new_fd;
  5264. sq->two_fd[i].orig_fd = fd;
  5265. /* if we move stderr, let "set -x" code know */
  5266. if (fd == preverrout_fd)
  5267. preverrout_fd = new_fd;
  5268. return 0; /* "we did not close fd" */
  5269. }
  5270. static int
  5271. internally_opened_fd(int fd, struct redirtab *sq)
  5272. {
  5273. int i;
  5274. #if JOBS
  5275. if (fd == ttyfd)
  5276. return 1;
  5277. #endif
  5278. /* If this one of script's fds? */
  5279. if (fd != 0) {
  5280. struct parsefile *pf = g_parsefile;
  5281. while (pf) {
  5282. if (fd == pf->pf_fd)
  5283. return 1;
  5284. pf = pf->prev;
  5285. }
  5286. }
  5287. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5288. if (fd == sq->two_fd[i].moved_to)
  5289. return 1;
  5290. }
  5291. return 0;
  5292. }
  5293. /*
  5294. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5295. * old file descriptors are stashed away so that the redirection can be
  5296. * undone by calling popredir.
  5297. */
  5298. /* flags passed to redirect */
  5299. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5300. static void
  5301. redirect(union node *redir, int flags)
  5302. {
  5303. struct redirtab *sv;
  5304. if (!redir)
  5305. return;
  5306. sv = NULL;
  5307. INT_OFF;
  5308. if (flags & REDIR_PUSH)
  5309. sv = redirlist;
  5310. do {
  5311. int fd;
  5312. int newfd;
  5313. int close_fd;
  5314. int closed;
  5315. fd = redir->nfile.fd;
  5316. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5317. //bb_error_msg("doing %d > %d", fd, newfd);
  5318. newfd = redir->ndup.dupfd;
  5319. close_fd = -1;
  5320. } else {
  5321. newfd = openredirect(redir); /* always >= 0 */
  5322. if (fd == newfd) {
  5323. /* open() gave us precisely the fd we wanted.
  5324. * This means that this fd was not busy
  5325. * (not opened to anywhere).
  5326. * Remember to close it on restore:
  5327. */
  5328. add_squirrel_closed(sv, fd);
  5329. continue;
  5330. }
  5331. close_fd = newfd;
  5332. }
  5333. if (fd == newfd)
  5334. continue;
  5335. /* if "N>FILE": move newfd to fd */
  5336. /* if "N>&M": dup newfd to fd */
  5337. /* if "N>&-": close fd (newfd is -1) */
  5338. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5339. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5340. if (newfd == -1) {
  5341. /* "N>&-" means "close me" */
  5342. if (!closed) {
  5343. /* ^^^ optimization: saving may already
  5344. * have closed it. If not... */
  5345. close(fd);
  5346. }
  5347. } else {
  5348. /* if newfd is a script fd or saved fd, simulate EBADF */
  5349. if (internally_opened_fd(newfd, sv)) {
  5350. errno = EBADF;
  5351. ash_msg_and_raise_perror("%d", newfd);
  5352. }
  5353. dup2_or_raise(newfd, fd);
  5354. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5355. close(close_fd);
  5356. #if BASH_REDIR_OUTPUT
  5357. if (redir->nfile.type == NTO2 && fd == 1) {
  5358. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5359. fd = 2;
  5360. newfd = 1;
  5361. close_fd = -1;
  5362. goto redirect_more;
  5363. }
  5364. #endif
  5365. }
  5366. } while ((redir = redir->nfile.next) != NULL);
  5367. INT_ON;
  5368. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5369. #define REDIR_SAVEFD2 0
  5370. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5371. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5372. // not only for calls with flags containing REDIR_SAVEFD2.
  5373. // We do this unconditionally (see save_fd_on_redirect()).
  5374. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5375. // preverrout_fd = copied_fd2;
  5376. }
  5377. static int
  5378. redirectsafe(union node *redir, int flags)
  5379. {
  5380. int err;
  5381. volatile int saveint;
  5382. struct jmploc *volatile savehandler = exception_handler;
  5383. struct jmploc jmploc;
  5384. SAVE_INT(saveint);
  5385. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5386. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5387. if (!err) {
  5388. exception_handler = &jmploc;
  5389. redirect(redir, flags);
  5390. }
  5391. exception_handler = savehandler;
  5392. if (err && exception_type != EXERROR)
  5393. longjmp(exception_handler->loc, 1);
  5394. RESTORE_INT(saveint);
  5395. return err;
  5396. }
  5397. #if BASH_PROCESS_SUBST
  5398. static void
  5399. pushfd(int fd)
  5400. {
  5401. struct redirtab *sv;
  5402. sv = ckzalloc(sizeof(*sv) + sizeof(sv->two_fd[0]));
  5403. sv->pair_count = 1;
  5404. sv->two_fd[0].orig_fd = fd;
  5405. sv->two_fd[0].moved_to = CLOSED;
  5406. sv->next = redirlist;
  5407. redirlist = sv;
  5408. }
  5409. #endif
  5410. static struct redirtab*
  5411. pushredir(union node *redir)
  5412. {
  5413. struct redirtab *sv;
  5414. int i;
  5415. if (!redir)
  5416. return redirlist;
  5417. i = 0;
  5418. do {
  5419. i++;
  5420. #if BASH_REDIR_OUTPUT
  5421. if (redir->nfile.type == NTO2)
  5422. i++;
  5423. #endif
  5424. redir = redir->nfile.next;
  5425. } while (redir);
  5426. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5427. sv->pair_count = i;
  5428. while (--i >= 0)
  5429. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5430. sv->next = redirlist;
  5431. redirlist = sv;
  5432. return sv->next;
  5433. }
  5434. /*
  5435. * Undo the effects of the last redirection.
  5436. */
  5437. static void
  5438. popredir(int drop)
  5439. {
  5440. struct redirtab *rp;
  5441. int i;
  5442. if (redirlist == NULL)
  5443. return;
  5444. INT_OFF;
  5445. rp = redirlist;
  5446. for (i = 0; i < rp->pair_count; i++) {
  5447. int fd = rp->two_fd[i].orig_fd;
  5448. int copy = rp->two_fd[i].moved_to;
  5449. if (copy == CLOSED) {
  5450. if (!drop)
  5451. close(fd);
  5452. continue;
  5453. }
  5454. if (copy != EMPTY) {
  5455. if (!drop) {
  5456. /*close(fd);*/
  5457. dup2_or_raise(copy, fd);
  5458. }
  5459. close(copy);
  5460. }
  5461. }
  5462. redirlist = rp->next;
  5463. free(rp);
  5464. INT_ON;
  5465. }
  5466. static void
  5467. unwindredir(struct redirtab *stop)
  5468. {
  5469. while (redirlist != stop)
  5470. popredir(/*drop:*/ 0);
  5471. }
  5472. /* ============ Routines to expand arguments to commands
  5473. *
  5474. * We have to deal with backquotes, shell variables, and file metacharacters.
  5475. */
  5476. #if ENABLE_FEATURE_SH_MATH
  5477. static arith_t
  5478. ash_arith(const char *s)
  5479. {
  5480. arith_state_t math_state;
  5481. arith_t result;
  5482. math_state.lookupvar = lookupvar;
  5483. math_state.setvar = setvar0;
  5484. //math_state.endofname = endofname;
  5485. INT_OFF;
  5486. result = arith(&math_state, s);
  5487. if (math_state.errmsg)
  5488. ash_msg_and_raise_error(math_state.errmsg);
  5489. INT_ON;
  5490. return result;
  5491. }
  5492. #endif
  5493. #if BASH_SUBSTR
  5494. # if ENABLE_FEATURE_SH_MATH
  5495. static int substr_atoi(const char *s)
  5496. {
  5497. arith_t t = ash_arith(s);
  5498. if (sizeof(t) > sizeof(int)) {
  5499. /* clamp very large or very large negative nums for ${v:N:M}:
  5500. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5501. */
  5502. if (t > INT_MAX)
  5503. t = INT_MAX;
  5504. if (t < INT_MIN)
  5505. t = INT_MIN;
  5506. }
  5507. return t;
  5508. }
  5509. # else
  5510. # define substr_atoi(s) number(s)
  5511. # endif
  5512. #endif
  5513. /*
  5514. * expandarg flags
  5515. */
  5516. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5517. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5518. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5519. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5520. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5521. * POSIX says for this case:
  5522. * Pathname expansion shall not be performed on the word by a
  5523. * non-interactive shell; an interactive shell may perform it, but shall
  5524. * do so only when the expansion would result in one word.
  5525. * Currently, our code complies to the above rule by never globbing
  5526. * redirection filenames.
  5527. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5528. * (this means that on a typical Linux distro, bash almost always
  5529. * performs globbing, and thus diverges from what we do).
  5530. */
  5531. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5532. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5533. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5534. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5535. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5536. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5537. /*
  5538. * rmescape() flags
  5539. */
  5540. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5541. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5542. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5543. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5544. /* Add CTLESC when necessary. */
  5545. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5546. /*
  5547. * Structure specifying which parts of the string should be searched
  5548. * for IFS characters.
  5549. */
  5550. struct ifsregion {
  5551. struct ifsregion *next; /* next region in list */
  5552. int begoff; /* offset of start of region */
  5553. int endoff; /* offset of end of region */
  5554. int nulonly; /* search for nul bytes only */
  5555. };
  5556. struct arglist {
  5557. struct strlist *list;
  5558. struct strlist **lastp;
  5559. };
  5560. /* output of current string */
  5561. static char *expdest;
  5562. /* list of back quote expressions */
  5563. static struct nodelist *argbackq;
  5564. /* first struct in list of ifs regions */
  5565. static struct ifsregion ifsfirst;
  5566. /* last struct in list */
  5567. static struct ifsregion *ifslastp;
  5568. /* holds expanded arg list */
  5569. static struct arglist exparg;
  5570. /*
  5571. * Break the argument string into pieces based upon IFS and add the
  5572. * strings to the argument list. The regions of the string to be
  5573. * searched for IFS characters have been stored by recordregion.
  5574. */
  5575. static void
  5576. ifsbreakup(char *string, struct arglist *arglist)
  5577. {
  5578. struct ifsregion *ifsp;
  5579. struct strlist *sp;
  5580. char *start;
  5581. char *p;
  5582. char *q;
  5583. const char *ifs, *realifs;
  5584. int ifsspc;
  5585. int nulonly;
  5586. start = string;
  5587. if (ifslastp != NULL) {
  5588. ifsspc = 0;
  5589. nulonly = 0;
  5590. realifs = ifsset() ? ifsval() : defifs;
  5591. ifsp = &ifsfirst;
  5592. do {
  5593. int afternul;
  5594. p = string + ifsp->begoff;
  5595. afternul = nulonly;
  5596. nulonly = ifsp->nulonly;
  5597. ifs = nulonly ? nullstr : realifs;
  5598. ifsspc = 0;
  5599. while (p < string + ifsp->endoff) {
  5600. q = p;
  5601. if ((unsigned char)*p == CTLESC)
  5602. p++;
  5603. if (!strchr(ifs, *p)) {
  5604. p++;
  5605. continue;
  5606. }
  5607. if (!(afternul || nulonly))
  5608. ifsspc = (strchr(defifs, *p) != NULL);
  5609. /* Ignore IFS whitespace at start */
  5610. if (q == start && ifsspc) {
  5611. p++;
  5612. start = p;
  5613. continue;
  5614. }
  5615. *q = '\0';
  5616. sp = stzalloc(sizeof(*sp));
  5617. sp->text = start;
  5618. *arglist->lastp = sp;
  5619. arglist->lastp = &sp->next;
  5620. p++;
  5621. if (!nulonly) {
  5622. for (;;) {
  5623. if (p >= string + ifsp->endoff) {
  5624. break;
  5625. }
  5626. q = p;
  5627. if ((unsigned char)*p == CTLESC)
  5628. p++;
  5629. if (strchr(ifs, *p) == NULL) {
  5630. p = q;
  5631. break;
  5632. }
  5633. if (strchr(defifs, *p) == NULL) {
  5634. if (ifsspc) {
  5635. p++;
  5636. ifsspc = 0;
  5637. } else {
  5638. p = q;
  5639. break;
  5640. }
  5641. } else
  5642. p++;
  5643. }
  5644. }
  5645. start = p;
  5646. } /* while */
  5647. ifsp = ifsp->next;
  5648. } while (ifsp != NULL);
  5649. if (nulonly)
  5650. goto add;
  5651. }
  5652. if (!*start)
  5653. return;
  5654. add:
  5655. sp = stzalloc(sizeof(*sp));
  5656. sp->text = start;
  5657. *arglist->lastp = sp;
  5658. arglist->lastp = &sp->next;
  5659. }
  5660. static void
  5661. ifsfree(void)
  5662. {
  5663. struct ifsregion *p = ifsfirst.next;
  5664. if (!p)
  5665. goto out;
  5666. INT_OFF;
  5667. do {
  5668. struct ifsregion *ifsp;
  5669. ifsp = p->next;
  5670. free(p);
  5671. p = ifsp;
  5672. } while (p);
  5673. ifsfirst.next = NULL;
  5674. INT_ON;
  5675. out:
  5676. ifslastp = NULL;
  5677. }
  5678. static size_t
  5679. esclen(const char *start, const char *p)
  5680. {
  5681. size_t esc = 0;
  5682. while (p > start && (unsigned char)*--p == CTLESC) {
  5683. esc++;
  5684. }
  5685. return esc;
  5686. }
  5687. /*
  5688. * Remove any CTLESC characters from a string.
  5689. */
  5690. #if !BASH_PATTERN_SUBST
  5691. #define rmescapes(str, flag, slash_position) \
  5692. rmescapes(str, flag)
  5693. #endif
  5694. static char *
  5695. rmescapes(char *str, int flag, int *slash_position)
  5696. {
  5697. static const char qchars[] ALIGN1 = {
  5698. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5699. char *p, *q, *r;
  5700. unsigned protect_against_glob;
  5701. unsigned globbing;
  5702. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5703. if (!p)
  5704. return str;
  5705. q = p;
  5706. r = str;
  5707. if (flag & RMESCAPE_ALLOC) {
  5708. size_t len = p - str;
  5709. size_t fulllen = len + strlen(p) + 1;
  5710. if (flag & RMESCAPE_GROW) {
  5711. int strloc = str - (char *)stackblock();
  5712. r = makestrspace(fulllen, expdest);
  5713. /* p and str may be invalidated by makestrspace */
  5714. str = (char *)stackblock() + strloc;
  5715. p = str + len;
  5716. } else if (flag & RMESCAPE_HEAP) {
  5717. r = ckmalloc(fulllen);
  5718. } else {
  5719. r = stalloc(fulllen);
  5720. }
  5721. q = r;
  5722. if (len > 0) {
  5723. q = (char *)mempcpy(q, str, len);
  5724. }
  5725. }
  5726. globbing = flag & RMESCAPE_GLOB;
  5727. protect_against_glob = globbing;
  5728. while (*p) {
  5729. if ((unsigned char)*p == CTLQUOTEMARK) {
  5730. // Note: protect_against_glob only affect whether
  5731. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5732. p++;
  5733. protect_against_glob = globbing;
  5734. continue;
  5735. }
  5736. if (*p == '\\') {
  5737. /* naked back slash */
  5738. protect_against_glob = 0;
  5739. goto copy;
  5740. }
  5741. if ((unsigned char)*p == CTLESC) {
  5742. p++;
  5743. #if DEBUG
  5744. if (*p == '\0')
  5745. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5746. #endif
  5747. if (protect_against_glob) {
  5748. /*
  5749. * We used to trust glob() and fnmatch() to eat
  5750. * superfluous escapes (\z where z has no
  5751. * special meaning anyway). But this causes
  5752. * bugs such as string of one greek letter rho
  5753. * (unicode-encoded as two bytes "cf,81")
  5754. * getting encoded as "cf,CTLESC,81"
  5755. * and here, converted to "cf,\,81" -
  5756. * which does not go well with some flavors
  5757. * of fnmatch() in unicode locales
  5758. * (for example, glibc <= 2.22).
  5759. *
  5760. * Lets add "\" only on the chars which need it.
  5761. * Testcases for less obvious chars are shown.
  5762. */
  5763. if (*p == '*'
  5764. || *p == '?'
  5765. || *p == '['
  5766. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5767. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5768. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5769. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5770. /* Some libc support [^negate], that's why "^" also needs love */
  5771. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5772. ) {
  5773. *q++ = '\\';
  5774. }
  5775. }
  5776. }
  5777. #if BASH_PATTERN_SUBST
  5778. else if (slash_position && p == str + *slash_position) {
  5779. /* stop handling globbing */
  5780. globbing = 0;
  5781. *slash_position = q - r;
  5782. slash_position = NULL;
  5783. }
  5784. #endif
  5785. protect_against_glob = globbing;
  5786. copy:
  5787. *q++ = *p++;
  5788. }
  5789. *q = '\0';
  5790. if (flag & RMESCAPE_GROW) {
  5791. expdest = r;
  5792. STADJUST(q - r + 1, expdest);
  5793. }
  5794. return r;
  5795. }
  5796. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5797. /*
  5798. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5799. *
  5800. * Returns an stalloced string.
  5801. */
  5802. static char *
  5803. preglob(const char *pattern, int flag)
  5804. {
  5805. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5806. }
  5807. /*
  5808. * Put a string on the stack.
  5809. */
  5810. static size_t
  5811. memtodest(const char *p, size_t len, int flags)
  5812. {
  5813. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5814. char *q;
  5815. char *s;
  5816. if (!len)
  5817. return 0;
  5818. q = makestrspace(len * 2, expdest);
  5819. s = q;
  5820. do {
  5821. unsigned char c = *p++;
  5822. if (c) {
  5823. if (flags & QUOTES_ESC) {
  5824. int n = SIT(c, syntax);
  5825. if (n == CCTL
  5826. || ((flags & EXP_QUOTED) && n == CBACK)
  5827. ) {
  5828. USTPUTC(CTLESC, q);
  5829. }
  5830. }
  5831. } else if (!(flags & EXP_KEEPNUL))
  5832. continue;
  5833. USTPUTC(c, q);
  5834. } while (--len);
  5835. expdest = q;
  5836. return q - s;
  5837. }
  5838. static size_t
  5839. strtodest(const char *p, int flags)
  5840. {
  5841. size_t len = strlen(p);
  5842. memtodest(p, len, flags);
  5843. return len;
  5844. }
  5845. /*
  5846. * Our own itoa().
  5847. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5848. */
  5849. static int
  5850. cvtnum(arith_t num, int flags)
  5851. {
  5852. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5853. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5854. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5855. char buf[len];
  5856. len = fmtstr(buf, len, ARITH_FMT, num);
  5857. return memtodest(buf, len, flags);
  5858. }
  5859. /*
  5860. * Record the fact that we have to scan this region of the
  5861. * string for IFS characters.
  5862. */
  5863. static void
  5864. recordregion(int start, int end, int nulonly)
  5865. {
  5866. struct ifsregion *ifsp;
  5867. if (ifslastp == NULL) {
  5868. ifsp = &ifsfirst;
  5869. } else {
  5870. INT_OFF;
  5871. ifsp = ckzalloc(sizeof(*ifsp));
  5872. /*ifsp->next = NULL; - ckzalloc did it */
  5873. ifslastp->next = ifsp;
  5874. INT_ON;
  5875. }
  5876. ifslastp = ifsp;
  5877. ifslastp->begoff = start;
  5878. ifslastp->endoff = end;
  5879. ifslastp->nulonly = nulonly;
  5880. }
  5881. static void
  5882. removerecordregions(int endoff)
  5883. {
  5884. if (ifslastp == NULL)
  5885. return;
  5886. if (ifsfirst.endoff > endoff) {
  5887. while (ifsfirst.next) {
  5888. struct ifsregion *ifsp;
  5889. INT_OFF;
  5890. ifsp = ifsfirst.next->next;
  5891. free(ifsfirst.next);
  5892. ifsfirst.next = ifsp;
  5893. INT_ON;
  5894. }
  5895. if (ifsfirst.begoff > endoff) {
  5896. ifslastp = NULL;
  5897. } else {
  5898. ifslastp = &ifsfirst;
  5899. ifsfirst.endoff = endoff;
  5900. }
  5901. return;
  5902. }
  5903. ifslastp = &ifsfirst;
  5904. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5905. ifslastp = ifslastp->next;
  5906. while (ifslastp->next) {
  5907. struct ifsregion *ifsp;
  5908. INT_OFF;
  5909. ifsp = ifslastp->next->next;
  5910. free(ifslastp->next);
  5911. ifslastp->next = ifsp;
  5912. INT_ON;
  5913. }
  5914. if (ifslastp->endoff > endoff)
  5915. ifslastp->endoff = endoff;
  5916. }
  5917. static char *
  5918. exptilde(char *startp, int flag)
  5919. {
  5920. unsigned char c;
  5921. char *name;
  5922. struct passwd *pw;
  5923. const char *home;
  5924. char *p;
  5925. p = startp;
  5926. name = p + 1;
  5927. while ((c = *++p) != '\0') {
  5928. switch (c) {
  5929. case CTLESC:
  5930. return startp;
  5931. case CTLQUOTEMARK:
  5932. return startp;
  5933. case ':':
  5934. if (flag & EXP_VARTILDE)
  5935. goto done;
  5936. break;
  5937. case '/':
  5938. case CTLENDVAR:
  5939. goto done;
  5940. }
  5941. }
  5942. done:
  5943. if (flag & EXP_DISCARD)
  5944. goto out;
  5945. *p = '\0';
  5946. if (*name == '\0') {
  5947. home = lookupvar("HOME");
  5948. } else {
  5949. pw = getpwnam(name);
  5950. if (pw == NULL)
  5951. goto lose;
  5952. home = pw->pw_dir;
  5953. }
  5954. *p = c;
  5955. if (!home)
  5956. goto lose;
  5957. strtodest(home, flag | EXP_QUOTED);
  5958. out:
  5959. return p;
  5960. lose:
  5961. return startp;
  5962. }
  5963. /*
  5964. * Execute a command inside back quotes. If it's a builtin command, we
  5965. * want to save its output in a block obtained from malloc. Otherwise
  5966. * we fork off a subprocess and get the output of the command via a pipe.
  5967. * Should be called with interrupts off.
  5968. */
  5969. struct backcmd { /* result of evalbackcmd */
  5970. int fd; /* file descriptor to read from */
  5971. int nleft; /* number of chars in buffer */
  5972. char *buf; /* buffer */
  5973. struct job *jp; /* job structure for command */
  5974. };
  5975. /* These forward decls are needed to use "eval" code for backticks handling: */
  5976. /* flags in argument to evaltree */
  5977. #define EV_EXIT 01 /* exit after evaluating tree */
  5978. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5979. static int evaltree(union node *, int);
  5980. /* An evaltree() which is known to never return.
  5981. * Used to use an alias:
  5982. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5983. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5984. */
  5985. static ALWAYS_INLINE NORETURN void
  5986. evaltreenr(union node *n, int flags)
  5987. {
  5988. evaltree(n, flags);
  5989. bb_unreachable(abort());
  5990. /* NOTREACHED */
  5991. }
  5992. static void FAST_FUNC
  5993. evalbackcmd(union node *n, struct backcmd *result
  5994. IF_BASH_PROCESS_SUBST(, int ctl))
  5995. {
  5996. int pip[2];
  5997. struct job *jp;
  5998. #if BASH_PROCESS_SUBST
  5999. /* determine end of pipe used by parent (ip) and child (ic) */
  6000. const int ip = (ctl == CTLTOPROC);
  6001. const int ic = !(ctl == CTLTOPROC);
  6002. #else
  6003. const int ctl = CTLBACKQ;
  6004. const int ip = 0;
  6005. const int ic = 1;
  6006. #endif
  6007. result->fd = -1;
  6008. result->buf = NULL;
  6009. result->nleft = 0;
  6010. result->jp = NULL;
  6011. if (n == NULL) {
  6012. goto out;
  6013. }
  6014. if (pipe(pip) < 0)
  6015. ash_msg_and_raise_perror("can't create pipe");
  6016. /* process substitution uses NULL job/node, like openhere() */
  6017. jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
  6018. if (forkshell(jp, (ctl == CTLBACKQ) ? n : NULL, FORK_NOJOB) == 0) {
  6019. /* child */
  6020. FORCE_INT_ON;
  6021. close(pip[ip]);
  6022. /* ic is index of child end of pipe *and* fd to connect it to */
  6023. if (pip[ic] != ic) {
  6024. /*close(ic);*/
  6025. dup2_or_raise(pip[ic], ic);
  6026. close(pip[ic]);
  6027. }
  6028. /* TODO: eflag clearing makes the following not abort:
  6029. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  6030. * which is what bash does (unless it is in POSIX mode).
  6031. * dash deleted "eflag = 0" line in the commit
  6032. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  6033. * [EVAL] Don't clear eflag in evalbackcmd
  6034. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  6035. */
  6036. eflag = 0;
  6037. ifsfree();
  6038. evaltreenr(n, EV_EXIT);
  6039. /* NOTREACHED */
  6040. }
  6041. /* parent */
  6042. #if BASH_PROCESS_SUBST
  6043. if (ctl != CTLBACKQ) {
  6044. int fd = fcntl(pip[ip], F_DUPFD, 64);
  6045. if (fd > 0) {
  6046. close(pip[ip]);
  6047. pip[ip] = fd;
  6048. }
  6049. pushfd(pip[ip]);
  6050. }
  6051. #endif
  6052. close(pip[ic]);
  6053. result->fd = pip[ip];
  6054. result->jp = jp;
  6055. out:
  6056. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  6057. result->fd, result->buf, result->nleft, result->jp));
  6058. }
  6059. /*
  6060. * Expand stuff in backwards quotes.
  6061. */
  6062. static void
  6063. expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
  6064. {
  6065. #if !BASH_PROCESS_SUBST
  6066. const int ctl = CTLBACKQ;
  6067. #endif
  6068. struct backcmd in;
  6069. int i;
  6070. char buf[128];
  6071. char *p;
  6072. char *dest;
  6073. int startloc;
  6074. struct stackmark smark;
  6075. if (flag & EXP_DISCARD)
  6076. goto out;
  6077. INT_OFF;
  6078. startloc = expdest - (char *)stackblock();
  6079. pushstackmark(&smark, startloc);
  6080. evalbackcmd(cmd, &in IF_BASH_PROCESS_SUBST(, ctl));
  6081. popstackmark(&smark);
  6082. if (ctl != CTLBACKQ) {
  6083. sprintf(buf, DEV_FD_PREFIX"%d", in.fd);
  6084. strtodest(buf, BASESYNTAX);
  6085. goto done;
  6086. }
  6087. p = in.buf;
  6088. i = in.nleft;
  6089. if (i == 0)
  6090. goto read;
  6091. for (;;) {
  6092. memtodest(p, i, flag);
  6093. read:
  6094. if (in.fd < 0)
  6095. break;
  6096. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6097. TRACE(("expbackq: read returns %d\n", i));
  6098. if (i <= 0)
  6099. break;
  6100. p = buf;
  6101. }
  6102. free(in.buf);
  6103. if (in.fd >= 0) {
  6104. close(in.fd);
  6105. back_exitstatus = waitforjob(in.jp);
  6106. }
  6107. done:
  6108. INT_ON;
  6109. /* Eat all trailing newlines */
  6110. dest = expdest;
  6111. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6112. STUNPUTC(dest);
  6113. expdest = dest;
  6114. if (!(flag & EXP_QUOTED))
  6115. recordregion(startloc, dest - (char *)stackblock(), 0);
  6116. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6117. (int)((dest - (char *)stackblock()) - startloc),
  6118. (int)((dest - (char *)stackblock()) - startloc),
  6119. stackblock() + startloc));
  6120. out:
  6121. argbackq = argbackq->next;
  6122. }
  6123. /* expari needs it */
  6124. static char *argstr(char *p, int flag);
  6125. #if ENABLE_FEATURE_SH_MATH
  6126. /*
  6127. * Expand arithmetic expression. Backup to start of expression,
  6128. * evaluate, place result in (backed up) result, adjust string position.
  6129. */
  6130. static char *
  6131. expari(char *start, int flag)
  6132. {
  6133. struct stackmark sm;
  6134. int begoff;
  6135. int endoff;
  6136. int len;
  6137. arith_t result;
  6138. char *p;
  6139. p = stackblock();
  6140. begoff = expdest - p;
  6141. p = argstr(start, flag & EXP_DISCARD);
  6142. if (flag & EXP_DISCARD)
  6143. goto out;
  6144. start = stackblock();
  6145. endoff = expdest - start;
  6146. start += begoff;
  6147. STADJUST(start - expdest, expdest);
  6148. removerecordregions(begoff);
  6149. if (flag & QUOTES_ESC)
  6150. rmescapes(start, 0, NULL);
  6151. pushstackmark(&sm, endoff);
  6152. result = ash_arith(start);
  6153. popstackmark(&sm);
  6154. len = cvtnum(result, flag);
  6155. if (!(flag & EXP_QUOTED))
  6156. recordregion(begoff, begoff + len, 0);
  6157. out:
  6158. return p;
  6159. }
  6160. #endif
  6161. /* argstr needs it */
  6162. static char *evalvar(char *p, int flags);
  6163. /*
  6164. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6165. * characters to allow for further processing. Otherwise treat
  6166. * $@ like $* since no splitting will be performed.
  6167. */
  6168. static char *
  6169. argstr(char *p, int flag)
  6170. {
  6171. static const char spclchars[] ALIGN1 = {
  6172. '=',
  6173. ':',
  6174. CTLQUOTEMARK,
  6175. CTLENDVAR,
  6176. CTLESC,
  6177. CTLVAR,
  6178. CTLBACKQ,
  6179. #if BASH_PROCESS_SUBST
  6180. CTLTOPROC,
  6181. CTLFROMPROC,
  6182. #endif
  6183. #if ENABLE_FEATURE_SH_MATH
  6184. CTLARI,
  6185. CTLENDARI,
  6186. #endif
  6187. '\0'
  6188. };
  6189. const char *reject = spclchars;
  6190. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6191. int inquotes;
  6192. size_t length;
  6193. int startloc;
  6194. reject += !!(flag & EXP_VARTILDE2);
  6195. reject += flag & EXP_VARTILDE ? 0 : 2;
  6196. inquotes = 0;
  6197. length = 0;
  6198. if (flag & EXP_TILDE) {
  6199. flag &= ~EXP_TILDE;
  6200. tilde:
  6201. if (*p == '~')
  6202. p = exptilde(p, flag);
  6203. }
  6204. start:
  6205. startloc = expdest - (char *)stackblock();
  6206. for (;;) {
  6207. int end;
  6208. unsigned char c;
  6209. length += strcspn(p + length, reject);
  6210. end = 0;
  6211. c = p[length];
  6212. if (!(c & 0x80)
  6213. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6214. || c == CTLENDVAR
  6215. ) {
  6216. /*
  6217. * c == '=' || c == ':' || c == '\0' ||
  6218. * c == CTLENDARI || c == CTLENDVAR
  6219. */
  6220. length++;
  6221. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6222. end = !!((c - 1) & 0x80);
  6223. }
  6224. if (length > 0 && !(flag & EXP_DISCARD)) {
  6225. int newloc;
  6226. char *q;
  6227. q = stnputs(p, length, expdest);
  6228. q[-1] &= end - 1;
  6229. expdest = q - (flag & EXP_WORD ? end : 0);
  6230. newloc = q - (char *)stackblock() - end;
  6231. if (breakall && !inquotes && newloc > startloc) {
  6232. recordregion(startloc, newloc, 0);
  6233. }
  6234. startloc = newloc;
  6235. }
  6236. p += length + 1;
  6237. length = 0;
  6238. if (end)
  6239. break;
  6240. switch (c) {
  6241. case '=':
  6242. flag |= EXP_VARTILDE2;
  6243. reject++;
  6244. /* fall through */
  6245. case ':':
  6246. /*
  6247. * sort of a hack - expand tildes in variable
  6248. * assignments (after the first '=' and after ':'s).
  6249. */
  6250. if (*--p == '~') {
  6251. goto tilde;
  6252. }
  6253. continue;
  6254. case CTLQUOTEMARK:
  6255. /* "$@" syntax adherence hack */
  6256. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6257. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6258. goto start;
  6259. }
  6260. inquotes ^= EXP_QUOTED;
  6261. addquote:
  6262. if (flag & QUOTES_ESC) {
  6263. p--;
  6264. length++;
  6265. startloc++;
  6266. }
  6267. break;
  6268. case CTLESC:
  6269. startloc++;
  6270. length++;
  6271. goto addquote;
  6272. case CTLVAR:
  6273. TRACE(("argstr: evalvar('%s')\n", p));
  6274. p = evalvar(p, flag | inquotes);
  6275. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6276. goto start;
  6277. #if BASH_PROCESS_SUBST
  6278. case CTLTOPROC:
  6279. case CTLFROMPROC:
  6280. #endif
  6281. case CTLBACKQ:
  6282. expbackq(argbackq->n, flag | inquotes IF_BASH_PROCESS_SUBST(, c));
  6283. goto start;
  6284. #if ENABLE_FEATURE_SH_MATH
  6285. case CTLARI:
  6286. p = expari(p, flag | inquotes);
  6287. goto start;
  6288. #endif
  6289. }
  6290. }
  6291. return p - 1;
  6292. }
  6293. static char *
  6294. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6295. char *pattern, int quotes, int zero)
  6296. {
  6297. char *loc, *loc2;
  6298. char c;
  6299. loc = startp;
  6300. loc2 = rmesc;
  6301. do {
  6302. int match;
  6303. const char *s = loc2;
  6304. c = *loc2;
  6305. if (zero) {
  6306. *loc2 = '\0';
  6307. s = rmesc;
  6308. }
  6309. match = pmatch(pattern, s);
  6310. *loc2 = c;
  6311. if (match)
  6312. return loc;
  6313. if (quotes && (unsigned char)*loc == CTLESC)
  6314. loc++;
  6315. loc++;
  6316. loc2++;
  6317. } while (c);
  6318. return NULL;
  6319. }
  6320. static char *
  6321. scanright(char *startp, char *rmesc, char *rmescend,
  6322. char *pattern, int quotes, int match_at_start)
  6323. {
  6324. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6325. int try2optimize = match_at_start;
  6326. #endif
  6327. int esc = 0;
  6328. char *loc;
  6329. char *loc2;
  6330. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6331. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6332. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6333. * Logic:
  6334. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6335. * and on each iteration they go back two/one char until they reach the beginning.
  6336. * We try to match "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6337. * If one of these matches, return pointer past last matched char in startp.
  6338. */
  6339. /* TODO: document in what other circumstances we are called. */
  6340. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6341. int match;
  6342. char c = *loc2;
  6343. const char *s = loc2;
  6344. if (match_at_start) {
  6345. *loc2 = '\0';
  6346. s = rmesc;
  6347. }
  6348. match = pmatch(pattern, s);
  6349. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6350. *loc2 = c;
  6351. if (match)
  6352. return loc;
  6353. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6354. if (try2optimize) {
  6355. /* Maybe we can optimize this:
  6356. * if pattern ends with unescaped *, we can avoid checking
  6357. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6358. * it won't match truncated "raw_value_of_" strings too.
  6359. */
  6360. unsigned plen = strlen(pattern);
  6361. /* Does it end with "*"? */
  6362. if (plen != 0 && pattern[--plen] == '*') {
  6363. /* "xxxx*" is not escaped */
  6364. /* "xxx\*" is escaped */
  6365. /* "xx\\*" is not escaped */
  6366. /* "x\\\*" is escaped */
  6367. int slashes = 0;
  6368. while (plen != 0 && pattern[--plen] == '\\')
  6369. slashes++;
  6370. if (!(slashes & 1))
  6371. break; /* ends with unescaped "*" */
  6372. }
  6373. try2optimize = 0;
  6374. }
  6375. #endif
  6376. loc--;
  6377. if (quotes) {
  6378. if (--esc < 0) {
  6379. esc = esclen(startp, loc);
  6380. }
  6381. if (esc % 2) {
  6382. esc--;
  6383. loc--;
  6384. }
  6385. }
  6386. }
  6387. return NULL;
  6388. }
  6389. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6390. static void
  6391. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6392. {
  6393. const char *msg;
  6394. const char *tail;
  6395. tail = nullstr;
  6396. msg = "parameter not set";
  6397. if (umsg) {
  6398. if ((unsigned char)*end == CTLENDVAR) {
  6399. if (varflags & VSNUL)
  6400. tail = " or null";
  6401. } else {
  6402. msg = umsg;
  6403. }
  6404. }
  6405. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6406. }
  6407. static char *
  6408. subevalvar(char *start, char *str, int strloc,
  6409. int startloc, int varflags, int flag)
  6410. {
  6411. int subtype = varflags & VSTYPE;
  6412. int quotes = flag & QUOTES_ESC;
  6413. char *startp;
  6414. char *loc;
  6415. char *rmesc, *rmescend;
  6416. long amount;
  6417. int resetloc;
  6418. int argstr_flags;
  6419. IF_BASH_PATTERN_SUBST(int workloc;)
  6420. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6421. IF_BASH_PATTERN_SUBST(char *repl;)
  6422. int zero;
  6423. char *(*scan)(char*, char*, char*, char*, int, int);
  6424. char *p;
  6425. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6426. // start, str, strloc, startloc, varflags, quotes);
  6427. #if BASH_PATTERN_SUBST
  6428. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6429. * argstr() call expands possible variable references in pattern:
  6430. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6431. */
  6432. repl = NULL;
  6433. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6434. /* Find '/' and replace with NUL */
  6435. repl = start;
  6436. /* The pattern can't be empty.
  6437. * IOW: if the first char after "${v//" is a slash,
  6438. * it does not terminate the pattern - it's the first char of the pattern:
  6439. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6440. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6441. */
  6442. if (*repl == '/')
  6443. repl++;
  6444. for (;;) {
  6445. if (*repl == '\0') {
  6446. repl = NULL;
  6447. break;
  6448. }
  6449. if (*repl == '/') {
  6450. *repl = '\0';
  6451. break;
  6452. }
  6453. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6454. if ((unsigned char)*repl == CTLESC && repl[1])
  6455. repl++;
  6456. repl++;
  6457. }
  6458. }
  6459. #endif
  6460. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6461. if (!str
  6462. #if BASH_SUBSTR
  6463. && subtype != VSSUBSTR
  6464. #endif
  6465. ) {
  6466. /* EXP_CASE keeps CTLESC's */
  6467. argstr_flags |= EXP_CASE;
  6468. }
  6469. p = argstr(start, argstr_flags);
  6470. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6471. #if BASH_PATTERN_SUBST
  6472. slash_pos = -1;
  6473. if (repl) {
  6474. slash_pos = expdest - ((char *)stackblock() + strloc);
  6475. if (!(flag & EXP_DISCARD))
  6476. STPUTC('/', expdest);
  6477. //bb_error_msg("repl+1:'%s'", repl + 1);
  6478. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6479. *repl = '/';
  6480. }
  6481. #endif
  6482. if (flag & EXP_DISCARD)
  6483. return p;
  6484. startp = (char *)stackblock() + startloc;
  6485. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6486. switch (subtype) {
  6487. case VSASSIGN:
  6488. setvar0(str, startp);
  6489. loc = startp;
  6490. goto out;
  6491. case VSQUESTION:
  6492. varunset(start, str, startp, varflags);
  6493. /* NOTREACHED */
  6494. #if BASH_SUBSTR
  6495. case VSSUBSTR: {
  6496. int pos, len, orig_len;
  6497. char *colon;
  6498. char *vstr;
  6499. loc = vstr = stackblock() + strloc;
  6500. /* Read POS in ${var:POS:LEN} */
  6501. colon = strchr(loc, ':');
  6502. if (colon) *colon = '\0';
  6503. pos = substr_atoi(loc);
  6504. if (colon) *colon = ':';
  6505. /* Read LEN in ${var:POS:LEN} */
  6506. len = vstr - startp - 1;
  6507. /* *loc != '\0', guaranteed by parser */
  6508. if (quotes) {
  6509. char *ptr;
  6510. /* Adjust the length by the number of escapes */
  6511. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6512. if ((unsigned char)*ptr == CTLESC) {
  6513. len--;
  6514. ptr++;
  6515. }
  6516. }
  6517. }
  6518. orig_len = len;
  6519. if (*loc++ == ':') {
  6520. /* ${var::LEN} */
  6521. len = substr_atoi(loc);
  6522. } else {
  6523. /* Skip POS in ${var:POS:LEN} */
  6524. len = orig_len;
  6525. while (*loc && *loc != ':')
  6526. loc++;
  6527. if (*loc++ == ':')
  6528. len = substr_atoi(loc);
  6529. }
  6530. if (pos < 0) {
  6531. /* ${VAR:$((-n)):l} starts n chars from the end */
  6532. pos = orig_len + pos;
  6533. }
  6534. if ((unsigned)pos >= orig_len) {
  6535. /* apart from obvious ${VAR:999999:l},
  6536. * covers ${VAR:$((-9999999)):l} - result is ""
  6537. * (bash compat)
  6538. */
  6539. pos = 0;
  6540. len = 0;
  6541. }
  6542. if (len < 0) {
  6543. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6544. len = (orig_len - pos) + len;
  6545. }
  6546. if ((unsigned)len > (orig_len - pos))
  6547. len = orig_len - pos;
  6548. for (vstr = startp; pos; vstr++, pos--) {
  6549. if (quotes && (unsigned char)*vstr == CTLESC)
  6550. vstr++;
  6551. }
  6552. for (loc = startp; len; len--) {
  6553. if (quotes && (unsigned char)*vstr == CTLESC)
  6554. *loc++ = *vstr++;
  6555. *loc++ = *vstr++;
  6556. }
  6557. *loc = '\0';
  6558. goto out;
  6559. }
  6560. #endif /* BASH_SUBSTR */
  6561. }
  6562. resetloc = expdest - (char *)stackblock();
  6563. #if BASH_PATTERN_SUBST
  6564. repl = NULL;
  6565. /* We'll comeback here if we grow the stack while handling
  6566. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6567. * stack will need rebasing, and we'll need to remove our work
  6568. * areas each time
  6569. */
  6570. restart:
  6571. #endif
  6572. amount = expdest - ((char *)stackblock() + resetloc);
  6573. STADJUST(-amount, expdest);
  6574. startp = (char *)stackblock() + startloc;
  6575. rmesc = startp;
  6576. rmescend = (char *)stackblock() + strloc;
  6577. //bb_error_msg("str7:'%s'", rmescend);
  6578. if (quotes) {
  6579. //TODO: how to handle slash_pos here if string changes (shortens?)
  6580. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6581. if (rmesc != startp) {
  6582. rmescend = expdest;
  6583. startp = (char *)stackblock() + startloc;
  6584. }
  6585. }
  6586. rmescend--;
  6587. str = (char *)stackblock() + strloc;
  6588. /*
  6589. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6590. * The result is a_\_z_c (not a\_\_z_c)!
  6591. *
  6592. * The search pattern and replace string treat backslashes differently!
  6593. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6594. * and string. It's only used on the first call.
  6595. */
  6596. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6597. rmescapes(str, RMESCAPE_GLOB,
  6598. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6599. );
  6600. #if BASH_PATTERN_SUBST
  6601. workloc = expdest - (char *)stackblock();
  6602. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6603. size_t no_meta_len;
  6604. int len;
  6605. char *idx, *end;
  6606. if (!repl) {
  6607. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6608. repl = nullstr;
  6609. if (slash_pos >= 0) {
  6610. repl = str + slash_pos;
  6611. *repl++ = '\0';
  6612. }
  6613. }
  6614. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6615. /* If there's no pattern to match, return the expansion unmolested */
  6616. if (str[0] == '\0')
  6617. goto out1;
  6618. no_meta_len = (ENABLE_ASH_OPTIMIZE_FOR_SIZE || strpbrk(str, "*?[\\")) ? 0 : strlen(str);
  6619. len = 0;
  6620. idx = startp;
  6621. end = str - 1;
  6622. while (idx <= end) {
  6623. try_to_match:
  6624. if (no_meta_len == 0) {
  6625. /* pattern has meta chars, have to glob; or ENABLE_ASH_OPTIMIZE_FOR_SIZE */
  6626. loc = scanright(idx, rmesc, rmescend, str, quotes, /*match_at_start:*/ 1);
  6627. } else {
  6628. /* Testcase for very slow replace (performs about 22k replaces):
  6629. * x=::::::::::::::::::::::
  6630. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6631. * echo "${x//:/|}"
  6632. */
  6633. if (strncmp(rmesc, str, no_meta_len) != 0)
  6634. goto no_match;
  6635. loc = idx;
  6636. if (!quotes) {
  6637. loc += no_meta_len;
  6638. } else {
  6639. size_t n = no_meta_len;
  6640. do {
  6641. if ((unsigned char)*loc == CTLESC)
  6642. loc++;
  6643. loc++;
  6644. } while (--n != 0);
  6645. }
  6646. }
  6647. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6648. if (!loc) {
  6649. char *restart_detect;
  6650. no_match:
  6651. /* No match, advance */
  6652. restart_detect = stackblock();
  6653. skip_matching:
  6654. if (idx >= end)
  6655. break;
  6656. STPUTC(*idx, expdest);
  6657. if (quotes && (unsigned char)*idx == CTLESC) {
  6658. idx++;
  6659. len++;
  6660. STPUTC(*idx, expdest);
  6661. }
  6662. if (stackblock() != restart_detect)
  6663. goto restart;
  6664. idx++;
  6665. len++;
  6666. rmesc++;
  6667. /* continue; - prone to quadratic behavior, smarter code: */
  6668. if (str[0] == '*') {
  6669. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6670. * it would never match "ong_string" etc, no point in trying.
  6671. */
  6672. goto skip_matching;
  6673. }
  6674. goto try_to_match;
  6675. }
  6676. if (subtype == VSREPLACEALL) {
  6677. while (idx < loc) {
  6678. if (quotes && (unsigned char)*idx == CTLESC)
  6679. idx++;
  6680. idx++;
  6681. rmesc++;
  6682. }
  6683. } else {
  6684. idx = loc;
  6685. }
  6686. //bb_error_msg("repl:'%s'", repl);
  6687. for (loc = (char*)repl; *loc; loc++) {
  6688. char *restart_detect = stackblock();
  6689. if (quotes && *loc == '\\') {
  6690. STPUTC(CTLESC, expdest);
  6691. len++;
  6692. }
  6693. STPUTC(*loc, expdest);
  6694. if (stackblock() != restart_detect)
  6695. goto restart;
  6696. len++;
  6697. }
  6698. if (subtype == VSREPLACE) {
  6699. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6700. while (*idx) {
  6701. char *restart_detect = stackblock();
  6702. STPUTC(*idx, expdest);
  6703. if (stackblock() != restart_detect)
  6704. goto restart;
  6705. len++;
  6706. idx++;
  6707. }
  6708. break;
  6709. }
  6710. }
  6711. /* We've put the replaced text into a buffer at workloc, now
  6712. * move it to the right place and adjust the stack.
  6713. */
  6714. STPUTC('\0', expdest);
  6715. startp = (char *)stackblock() + startloc;
  6716. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6717. //bb_error_msg("startp:'%s'", startp);
  6718. loc = startp + len;
  6719. goto out;
  6720. }
  6721. #endif /* BASH_PATTERN_SUBST */
  6722. subtype -= VSTRIMRIGHT;
  6723. #if DEBUG
  6724. if (subtype < 0 || subtype > 7)
  6725. abort();
  6726. #endif
  6727. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6728. zero = subtype >> 1;
  6729. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6730. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6731. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6732. if (loc) {
  6733. if (zero) {
  6734. memmove(startp, loc, str - loc);
  6735. loc = startp + (str - loc) - 1;
  6736. }
  6737. *loc = '\0';
  6738. } else
  6739. loc = str - 1;
  6740. out:
  6741. amount = loc - expdest;
  6742. STADJUST(amount, expdest);
  6743. #if BASH_PATTERN_SUBST
  6744. out1:
  6745. #endif
  6746. /* Remove any recorded regions beyond start of variable */
  6747. removerecordregions(startloc);
  6748. return p;
  6749. }
  6750. /*
  6751. * Add the value of a specialized variable to the stack string.
  6752. * name parameter (examples):
  6753. * ash -c 'echo $1' name:'1='
  6754. * ash -c 'echo $qwe' name:'qwe='
  6755. * ash -c 'echo $$' name:'$='
  6756. * ash -c 'echo ${$}' name:'$='
  6757. * ash -c 'echo ${$##q}' name:'$=q'
  6758. * ash -c 'echo ${#$}' name:'$='
  6759. * note: examples with bad shell syntax:
  6760. * ash -c 'echo ${#$1}' name:'$=1'
  6761. * ash -c 'echo ${#1#}' name:'1=#'
  6762. */
  6763. static NOINLINE ssize_t
  6764. varvalue(char *name, int varflags, int flags, int quoted)
  6765. {
  6766. const char *p;
  6767. int num;
  6768. int i;
  6769. ssize_t len = 0;
  6770. int sep;
  6771. int subtype = varflags & VSTYPE;
  6772. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6773. if (!subtype) {
  6774. if (discard)
  6775. return -1;
  6776. raise_error_syntax("bad substitution");
  6777. }
  6778. flags |= EXP_KEEPNUL;
  6779. flags &= discard ? ~QUOTES_ESC : ~0;
  6780. sep = (flags & EXP_FULL) << CHAR_BIT;
  6781. switch (*name) {
  6782. case '$':
  6783. num = rootpid;
  6784. goto numvar;
  6785. case '?':
  6786. num = exitstatus;
  6787. goto numvar;
  6788. case '#':
  6789. num = shellparam.nparam;
  6790. goto numvar;
  6791. case '!':
  6792. num = backgndpid;
  6793. if (num == 0)
  6794. return -1;
  6795. numvar:
  6796. len = cvtnum(num, flags);
  6797. goto check_1char_name;
  6798. case '-':
  6799. expdest = makestrspace(NOPTS, expdest);
  6800. for (i = NOPTS - 1; i >= 0; i--) {
  6801. if (optlist[i] && optletters(i)) {
  6802. USTPUTC(optletters(i), expdest);
  6803. len++;
  6804. }
  6805. }
  6806. check_1char_name:
  6807. #if 0
  6808. /* handles cases similar to ${#$1} */
  6809. if (name[2] != '\0')
  6810. raise_error_syntax("bad substitution");
  6811. #endif
  6812. break;
  6813. case '@':
  6814. if (quoted && sep)
  6815. goto param;
  6816. /* fall through */
  6817. case '*': {
  6818. char **ap;
  6819. char sepc;
  6820. char c;
  6821. /* We will set c to 0 or ~0 depending on whether
  6822. * we're doing field splitting. We won't do field
  6823. * splitting if either we're quoted or sep is zero.
  6824. *
  6825. * Instead of testing (quoted || !sep) the following
  6826. * trick optimises away any branches by using the
  6827. * fact that EXP_QUOTED (which is the only bit that
  6828. * can be set in quoted) is the same as EXP_FULL <<
  6829. * CHAR_BIT (which is the only bit that can be set
  6830. * in sep).
  6831. */
  6832. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6833. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6834. #endif
  6835. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6836. sep &= ~quoted;
  6837. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6838. param:
  6839. sepc = sep;
  6840. ap = shellparam.p;
  6841. if (!ap)
  6842. return -1;
  6843. while ((p = *ap++) != NULL) {
  6844. len += strtodest(p, flags);
  6845. if (*ap && sep) {
  6846. len++;
  6847. memtodest(&sepc, 1, flags);
  6848. }
  6849. }
  6850. break;
  6851. } /* case '*' */
  6852. case '0':
  6853. case '1':
  6854. case '2':
  6855. case '3':
  6856. case '4':
  6857. case '5':
  6858. case '6':
  6859. case '7':
  6860. case '8':
  6861. case '9':
  6862. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6863. if (num < 0 || num > shellparam.nparam)
  6864. return -1;
  6865. p = num ? shellparam.p[num - 1] : arg0;
  6866. goto value;
  6867. default:
  6868. /* NB: name has form "VAR=..." */
  6869. p = lookupvar(name);
  6870. value:
  6871. if (!p)
  6872. return -1;
  6873. len = strtodest(p, flags);
  6874. #if ENABLE_UNICODE_SUPPORT
  6875. if (subtype == VSLENGTH && len > 0) {
  6876. reinit_unicode_for_ash();
  6877. if (unicode_status == UNICODE_ON) {
  6878. STADJUST(-len, expdest);
  6879. discard = 0;
  6880. len = unicode_strlen(p);
  6881. }
  6882. }
  6883. #endif
  6884. break;
  6885. }
  6886. if (discard)
  6887. STADJUST(-len, expdest);
  6888. return len;
  6889. }
  6890. /*
  6891. * Expand a variable, and return a pointer to the next character in the
  6892. * input string.
  6893. */
  6894. static char *
  6895. evalvar(char *p, int flag)
  6896. {
  6897. char varflags;
  6898. char subtype;
  6899. char *var;
  6900. int patloc;
  6901. int startloc;
  6902. ssize_t varlen;
  6903. int discard;
  6904. int quoted;
  6905. varflags = (unsigned char) *p++;
  6906. subtype = varflags & VSTYPE;
  6907. quoted = flag & EXP_QUOTED;
  6908. var = p;
  6909. startloc = expdest - (char *)stackblock();
  6910. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6911. again:
  6912. varlen = varvalue(var, varflags, flag, quoted);
  6913. if (varflags & VSNUL)
  6914. varlen--;
  6915. discard = varlen < 0 ? EXP_DISCARD : 0;
  6916. switch (subtype) {
  6917. case VSPLUS:
  6918. discard ^= EXP_DISCARD;
  6919. /* fall through */
  6920. case 0:
  6921. case VSMINUS:
  6922. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6923. goto record;
  6924. case VSASSIGN:
  6925. case VSQUESTION:
  6926. p = subevalvar(p, var, 0, startloc, varflags,
  6927. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6928. if ((flag | ~discard) & EXP_DISCARD)
  6929. goto record;
  6930. varflags &= ~VSNUL;
  6931. subtype = VSNORMAL;
  6932. goto again;
  6933. }
  6934. if ((discard & ~flag) && uflag)
  6935. varunset(p, var, 0, 0);
  6936. if (subtype == VSLENGTH) {
  6937. p++;
  6938. if (flag & EXP_DISCARD)
  6939. return p;
  6940. cvtnum(varlen > 0 ? varlen : 0, flag);
  6941. goto really_record;
  6942. }
  6943. if (subtype == VSNORMAL)
  6944. goto record;
  6945. #if DEBUG
  6946. switch (subtype) {
  6947. case VSTRIMLEFT:
  6948. case VSTRIMLEFTMAX:
  6949. case VSTRIMRIGHT:
  6950. case VSTRIMRIGHTMAX:
  6951. #if BASH_SUBSTR
  6952. case VSSUBSTR:
  6953. #endif
  6954. #if BASH_PATTERN_SUBST
  6955. case VSREPLACE:
  6956. case VSREPLACEALL:
  6957. #endif
  6958. break;
  6959. default:
  6960. abort();
  6961. }
  6962. #endif
  6963. flag |= discard;
  6964. if (!(flag & EXP_DISCARD)) {
  6965. /*
  6966. * Terminate the string and start recording the pattern
  6967. * right after it
  6968. */
  6969. STPUTC('\0', expdest);
  6970. }
  6971. patloc = expdest - (char *)stackblock();
  6972. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6973. record:
  6974. if ((flag | discard) & EXP_DISCARD)
  6975. return p;
  6976. really_record:
  6977. if (quoted) {
  6978. quoted = *var == '@' && shellparam.nparam;
  6979. if (!quoted)
  6980. return p;
  6981. }
  6982. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6983. return p;
  6984. }
  6985. /*
  6986. * Add a file name to the list.
  6987. */
  6988. static void
  6989. addfname(const char *name)
  6990. {
  6991. struct strlist *sp;
  6992. sp = stzalloc(sizeof(*sp));
  6993. sp->text = sstrdup(name);
  6994. *exparg.lastp = sp;
  6995. exparg.lastp = &sp->next;
  6996. }
  6997. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6998. static int
  6999. hasmeta(const char *p)
  7000. {
  7001. static const char chars[] ALIGN1 = {
  7002. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  7003. };
  7004. for (;;) {
  7005. p = strpbrk(p, chars);
  7006. if (!p)
  7007. break;
  7008. switch ((unsigned char)*p) {
  7009. case CTLQUOTEMARK:
  7010. for (;;) {
  7011. p++;
  7012. if ((unsigned char)*p == CTLQUOTEMARK)
  7013. break;
  7014. if ((unsigned char)*p == CTLESC)
  7015. p++;
  7016. if (*p == '\0') /* huh? */
  7017. return 0;
  7018. }
  7019. break;
  7020. case '\\':
  7021. case CTLESC:
  7022. p++;
  7023. if (*p == '\0')
  7024. return 0;
  7025. break;
  7026. case '[':
  7027. if (!strchr(p + 1, ']')) {
  7028. /* It's not a properly closed [] pattern,
  7029. * but other metas may follow. Continue checking.
  7030. * my[file* _is_ globbed by bash
  7031. * and matches filenames like "my[file1".
  7032. */
  7033. break;
  7034. }
  7035. /* fallthrough */
  7036. default:
  7037. /* case '*': */
  7038. /* case '?': */
  7039. return 1;
  7040. }
  7041. p++;
  7042. }
  7043. return 0;
  7044. }
  7045. /* If we want to use glob() from libc... */
  7046. #if !ENABLE_ASH_INTERNAL_GLOB
  7047. /* Add the result of glob() to the list */
  7048. static void
  7049. addglob(const glob_t *pglob)
  7050. {
  7051. char **p = pglob->gl_pathv;
  7052. do {
  7053. addfname(*p);
  7054. } while (*++p);
  7055. }
  7056. static void
  7057. expandmeta(struct strlist *str /*, int flag*/)
  7058. {
  7059. /* TODO - EXP_REDIR */
  7060. while (str) {
  7061. char *p;
  7062. glob_t pglob;
  7063. int i;
  7064. if (fflag)
  7065. goto nometa;
  7066. if (!hasmeta(str->text))
  7067. goto nometa;
  7068. INT_OFF;
  7069. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7070. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  7071. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  7072. //
  7073. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  7074. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  7075. // Which means you need to unescape the string, right? Not so fast:
  7076. // if there _is_ a file named "file\?" (with backslash), it is returned
  7077. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  7078. // You DON'T KNOW by looking at the result whether you need to unescape it.
  7079. //
  7080. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  7081. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  7082. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  7083. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  7084. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  7085. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  7086. i = glob(p, 0, NULL, &pglob);
  7087. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  7088. if (p != str->text)
  7089. free(p);
  7090. switch (i) {
  7091. case 0:
  7092. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  7093. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  7094. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  7095. goto nometa2;
  7096. #endif
  7097. addglob(&pglob);
  7098. globfree(&pglob);
  7099. INT_ON;
  7100. break;
  7101. case GLOB_NOMATCH:
  7102. //nometa2:
  7103. globfree(&pglob);
  7104. INT_ON;
  7105. nometa:
  7106. *exparg.lastp = str;
  7107. rmescapes(str->text, 0, NULL);
  7108. exparg.lastp = &str->next;
  7109. break;
  7110. default: /* GLOB_NOSPACE */
  7111. globfree(&pglob);
  7112. INT_ON;
  7113. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7114. }
  7115. str = str->next;
  7116. }
  7117. }
  7118. #else
  7119. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7120. /*
  7121. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7122. */
  7123. typedef struct exp_t {
  7124. char *dir;
  7125. unsigned dir_max;
  7126. } exp_t;
  7127. static void
  7128. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7129. {
  7130. #define expdir exp->dir
  7131. #define expdir_max exp->dir_max
  7132. char *enddir = expdir + expdir_len;
  7133. char *p;
  7134. const char *cp;
  7135. char *start;
  7136. char *endname;
  7137. int metaflag;
  7138. struct stat statb;
  7139. DIR *dirp;
  7140. struct dirent *dp;
  7141. int atend;
  7142. int matchdot;
  7143. int esc;
  7144. metaflag = 0;
  7145. start = name;
  7146. for (p = name; esc = 0, *p; p += esc + 1) {
  7147. if (*p == '*' || *p == '?')
  7148. metaflag = 1;
  7149. else if (*p == '[') {
  7150. char *q = p + 1;
  7151. if (*q == '!')
  7152. q++;
  7153. for (;;) {
  7154. if (*q == '\\')
  7155. q++;
  7156. if (*q == '/' || *q == '\0')
  7157. break;
  7158. if (*++q == ']') {
  7159. metaflag = 1;
  7160. break;
  7161. }
  7162. }
  7163. } else {
  7164. if (*p == '\\' && p[1])
  7165. esc++;
  7166. if (p[esc] == '/') {
  7167. if (metaflag)
  7168. break;
  7169. start = p + esc + 1;
  7170. }
  7171. }
  7172. }
  7173. if (metaflag == 0) { /* we've reached the end of the file name */
  7174. if (!expdir_len)
  7175. return;
  7176. p = name;
  7177. do {
  7178. if (*p == '\\' && p[1])
  7179. p++;
  7180. *enddir++ = *p;
  7181. } while (*p++);
  7182. if (lstat(expdir, &statb) == 0)
  7183. addfname(expdir);
  7184. return;
  7185. }
  7186. endname = p;
  7187. if (name < start) {
  7188. p = name;
  7189. do {
  7190. if (*p == '\\' && p[1])
  7191. p++;
  7192. *enddir++ = *p++;
  7193. } while (p < start);
  7194. }
  7195. *enddir = '\0';
  7196. cp = expdir;
  7197. expdir_len = enddir - cp;
  7198. if (!expdir_len)
  7199. cp = ".";
  7200. dirp = opendir(cp);
  7201. if (dirp == NULL)
  7202. return;
  7203. if (*endname == 0) {
  7204. atend = 1;
  7205. } else {
  7206. atend = 0;
  7207. *endname = '\0';
  7208. endname += esc + 1;
  7209. }
  7210. name_len -= endname - name;
  7211. matchdot = 0;
  7212. p = start;
  7213. if (*p == '\\')
  7214. p++;
  7215. if (*p == '.')
  7216. matchdot++;
  7217. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7218. if (dp->d_name[0] == '.' && !matchdot)
  7219. continue;
  7220. if (pmatch(start, dp->d_name)) {
  7221. if (atend) {
  7222. strcpy(enddir, dp->d_name);
  7223. addfname(expdir);
  7224. } else {
  7225. unsigned offset;
  7226. unsigned len;
  7227. p = stpcpy(enddir, dp->d_name);
  7228. *p = '/';
  7229. offset = p - expdir + 1;
  7230. len = offset + name_len + NAME_MAX;
  7231. if (len > expdir_max) {
  7232. len += PATH_MAX;
  7233. expdir = ckrealloc(expdir, len);
  7234. expdir_max = len;
  7235. }
  7236. expmeta(exp, endname, name_len, offset);
  7237. enddir = expdir + expdir_len;
  7238. }
  7239. }
  7240. }
  7241. closedir(dirp);
  7242. if (!atend)
  7243. endname[-esc - 1] = esc ? '\\' : '/';
  7244. #undef expdir
  7245. #undef expdir_max
  7246. }
  7247. static struct strlist *
  7248. msort(struct strlist *list, int len)
  7249. {
  7250. struct strlist *p, *q = NULL;
  7251. struct strlist **lpp;
  7252. int half;
  7253. int n;
  7254. if (len <= 1)
  7255. return list;
  7256. half = len >> 1;
  7257. p = list;
  7258. for (n = half; --n >= 0;) {
  7259. q = p;
  7260. p = p->next;
  7261. }
  7262. q->next = NULL; /* terminate first half of list */
  7263. q = msort(list, half); /* sort first half of list */
  7264. p = msort(p, len - half); /* sort second half */
  7265. lpp = &list;
  7266. for (;;) {
  7267. #if ENABLE_LOCALE_SUPPORT
  7268. if (strcoll(p->text, q->text) < 0)
  7269. #else
  7270. if (strcmp(p->text, q->text) < 0)
  7271. #endif
  7272. {
  7273. *lpp = p;
  7274. lpp = &p->next;
  7275. p = *lpp;
  7276. if (p == NULL) {
  7277. *lpp = q;
  7278. break;
  7279. }
  7280. } else {
  7281. *lpp = q;
  7282. lpp = &q->next;
  7283. q = *lpp;
  7284. if (q == NULL) {
  7285. *lpp = p;
  7286. break;
  7287. }
  7288. }
  7289. }
  7290. return list;
  7291. }
  7292. /*
  7293. * Sort the results of file name expansion. It calculates the number of
  7294. * strings to sort and then calls msort (short for merge sort) to do the
  7295. * work.
  7296. */
  7297. static struct strlist *
  7298. expsort(struct strlist *str)
  7299. {
  7300. int len;
  7301. struct strlist *sp;
  7302. len = 0;
  7303. for (sp = str; sp; sp = sp->next)
  7304. len++;
  7305. return msort(str, len);
  7306. }
  7307. static void
  7308. expandmeta(struct strlist *str /*, int flag*/)
  7309. {
  7310. /* TODO - EXP_REDIR */
  7311. while (str) {
  7312. exp_t exp;
  7313. struct strlist **savelastp;
  7314. struct strlist *sp;
  7315. char *p;
  7316. unsigned len;
  7317. if (fflag)
  7318. goto nometa;
  7319. if (!hasmeta(str->text))
  7320. goto nometa;
  7321. savelastp = exparg.lastp;
  7322. INT_OFF;
  7323. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7324. len = strlen(p);
  7325. exp.dir_max = len + PATH_MAX;
  7326. exp.dir = ckmalloc(exp.dir_max);
  7327. expmeta(&exp, p, len, 0);
  7328. free(exp.dir);
  7329. if (p != str->text)
  7330. free(p);
  7331. INT_ON;
  7332. if (exparg.lastp == savelastp) {
  7333. /*
  7334. * no matches
  7335. */
  7336. nometa:
  7337. *exparg.lastp = str;
  7338. rmescapes(str->text, 0, NULL);
  7339. exparg.lastp = &str->next;
  7340. } else {
  7341. *exparg.lastp = NULL;
  7342. *savelastp = sp = expsort(*savelastp);
  7343. while (sp->next != NULL)
  7344. sp = sp->next;
  7345. exparg.lastp = &sp->next;
  7346. }
  7347. str = str->next;
  7348. }
  7349. }
  7350. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7351. /*
  7352. * Perform variable substitution and command substitution on an argument,
  7353. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7354. * perform splitting and file name expansion. When arglist is NULL, perform
  7355. * here document expansion.
  7356. */
  7357. static void
  7358. expandarg(union node *arg, struct arglist *arglist, int flag)
  7359. {
  7360. struct strlist *sp;
  7361. char *p;
  7362. argbackq = arg->narg.backquote;
  7363. STARTSTACKSTR(expdest);
  7364. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7365. argstr(arg->narg.text, flag);
  7366. if (arglist == NULL) {
  7367. /* here document expanded */
  7368. goto out;
  7369. }
  7370. p = grabstackstr(expdest);
  7371. TRACE(("expandarg: p:'%s'\n", p));
  7372. exparg.lastp = &exparg.list;
  7373. /*
  7374. * TODO - EXP_REDIR
  7375. */
  7376. if (flag & EXP_FULL) {
  7377. ifsbreakup(p, &exparg);
  7378. *exparg.lastp = NULL;
  7379. exparg.lastp = &exparg.list;
  7380. expandmeta(exparg.list /*, flag*/);
  7381. } else {
  7382. sp = stzalloc(sizeof(*sp));
  7383. sp->text = p;
  7384. *exparg.lastp = sp;
  7385. exparg.lastp = &sp->next;
  7386. }
  7387. *exparg.lastp = NULL;
  7388. if (exparg.list) {
  7389. *arglist->lastp = exparg.list;
  7390. arglist->lastp = exparg.lastp;
  7391. }
  7392. out:
  7393. ifsfree();
  7394. }
  7395. /*
  7396. * Expand shell variables and backquotes inside a here document.
  7397. */
  7398. static void
  7399. expandhere(union node *arg)
  7400. {
  7401. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7402. }
  7403. /*
  7404. * Returns true if the pattern matches the string.
  7405. */
  7406. static int
  7407. patmatch(char *pattern, const char *string)
  7408. {
  7409. char *p = preglob(pattern, 0);
  7410. int r = pmatch(p, string);
  7411. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7412. return r;
  7413. }
  7414. /*
  7415. * See if a pattern matches in a case statement.
  7416. */
  7417. static int
  7418. casematch(union node *pattern, char *val)
  7419. {
  7420. struct stackmark smark;
  7421. int result;
  7422. setstackmark(&smark);
  7423. argbackq = pattern->narg.backquote;
  7424. STARTSTACKSTR(expdest);
  7425. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7426. ifsfree();
  7427. result = patmatch(stackblock(), val);
  7428. popstackmark(&smark);
  7429. return result;
  7430. }
  7431. /* ============ find_command */
  7432. struct builtincmd {
  7433. const char *name;
  7434. int (*builtin)(int, char **) FAST_FUNC;
  7435. /* unsigned flags; */
  7436. };
  7437. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7438. /* "regular" builtins always take precedence over commands,
  7439. * regardless of PATH=....%builtin... position */
  7440. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7441. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7442. struct cmdentry {
  7443. smallint cmdtype; /* CMDxxx */
  7444. union param {
  7445. int index;
  7446. /* index >= 0 for commands without path (slashes) */
  7447. /* (TODO: what exactly does the value mean? PATH position?) */
  7448. /* index == -1 for commands with slashes */
  7449. /* index == (-2 - applet_no) for NOFORK applets */
  7450. const struct builtincmd *cmd;
  7451. struct funcnode *func;
  7452. } u;
  7453. };
  7454. /* values of cmdtype */
  7455. #define CMDUNKNOWN -1 /* no entry in table for command */
  7456. #define CMDNORMAL 0 /* command is an executable program */
  7457. #define CMDFUNCTION 1 /* command is a shell function */
  7458. #define CMDBUILTIN 2 /* command is a shell builtin */
  7459. /* action to find_command() */
  7460. #define DO_ERR 0x01 /* prints errors */
  7461. #define DO_ABS 0x02 /* checks absolute paths */
  7462. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7463. #define DO_ALTPATH 0x08 /* using alternate path */
  7464. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7465. static void find_command(char *, struct cmdentry *, int, const char *);
  7466. /* ============ Hashing commands */
  7467. /*
  7468. * When commands are first encountered, they are entered in a hash table.
  7469. * This ensures that a full path search will not have to be done for them
  7470. * on each invocation.
  7471. *
  7472. * We should investigate converting to a linear search, even though that
  7473. * would make the command name "hash" a misnomer.
  7474. */
  7475. struct tblentry {
  7476. struct tblentry *next; /* next entry in hash chain */
  7477. union param param; /* definition of builtin function */
  7478. smallint cmdtype; /* CMDxxx */
  7479. char rehash; /* if set, cd done since entry created */
  7480. char cmdname[1]; /* name of command */
  7481. };
  7482. static struct tblentry **cmdtable;
  7483. #define INIT_G_cmdtable() do { \
  7484. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7485. } while (0)
  7486. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7487. static void
  7488. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7489. {
  7490. #if ENABLE_FEATURE_SH_STANDALONE
  7491. if (applet_no >= 0) {
  7492. if (APPLET_IS_NOEXEC(applet_no)) {
  7493. clearenv();
  7494. while (*envp)
  7495. putenv(*envp++);
  7496. popredir(/*drop:*/ 1);
  7497. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7498. }
  7499. /* re-exec ourselves with the new arguments */
  7500. execve(bb_busybox_exec_path, argv, envp);
  7501. /* If they called chroot or otherwise made the binary no longer
  7502. * executable, fall through */
  7503. }
  7504. #endif
  7505. repeat:
  7506. #ifdef SYSV
  7507. do {
  7508. execve(cmd, argv, envp);
  7509. } while (errno == EINTR);
  7510. #else
  7511. execve(cmd, argv, envp);
  7512. #endif
  7513. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7514. /* Run "cmd" as a shell script:
  7515. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7516. * "If the execve() function fails with ENOEXEC, the shell
  7517. * shall execute a command equivalent to having a shell invoked
  7518. * with the command name as its first operand,
  7519. * with any remaining arguments passed to the new shell"
  7520. *
  7521. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7522. * just call ourselves.
  7523. *
  7524. * Note that bash reads ~80 chars of the file, and if it sees
  7525. * a zero byte before it sees newline, it doesn't try to
  7526. * interpret it, but fails with "cannot execute binary file"
  7527. * message and exit code 126. For one, this prevents attempts
  7528. * to interpret foreign ELF binaries as shell scripts.
  7529. */
  7530. argv[0] = (char*) cmd;
  7531. cmd = bb_busybox_exec_path;
  7532. /* NB: this is only possible because all callers of shellexec()
  7533. * ensure that the argv[-1] slot exists!
  7534. */
  7535. argv--;
  7536. argv[0] = (char*) "ash";
  7537. goto repeat;
  7538. }
  7539. }
  7540. /*
  7541. * Exec a program. Never returns. If you change this routine, you may
  7542. * have to change the find_command routine as well.
  7543. * argv[-1] must exist and be writable! See tryexec() for why.
  7544. */
  7545. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7546. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7547. {
  7548. char *cmdname;
  7549. int e;
  7550. char **envp;
  7551. int exerrno;
  7552. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7553. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7554. if (strchr(prog, '/') != NULL
  7555. #if ENABLE_FEATURE_SH_STANDALONE
  7556. || (applet_no = find_applet_by_name(prog)) >= 0
  7557. #endif
  7558. ) {
  7559. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7560. if (applet_no >= 0) {
  7561. /* We tried execing ourself, but it didn't work.
  7562. * Maybe /proc/self/exe doesn't exist?
  7563. * Try $PATH search.
  7564. */
  7565. goto try_PATH;
  7566. }
  7567. e = errno;
  7568. } else {
  7569. try_PATH:
  7570. e = ENOENT;
  7571. while (padvance(&path, argv[0]) >= 0) {
  7572. cmdname = stackblock();
  7573. if (--idx < 0 && pathopt == NULL) {
  7574. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7575. if (errno != ENOENT && errno != ENOTDIR)
  7576. e = errno;
  7577. }
  7578. }
  7579. }
  7580. /* Map to POSIX errors */
  7581. switch (e) {
  7582. default:
  7583. exerrno = 126;
  7584. break;
  7585. case ELOOP:
  7586. case ENAMETOOLONG:
  7587. case ENOENT:
  7588. case ENOTDIR:
  7589. exerrno = 127;
  7590. break;
  7591. }
  7592. exitstatus = exerrno;
  7593. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7594. prog, e, suppress_int));
  7595. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7596. /* NOTREACHED */
  7597. }
  7598. static void
  7599. printentry(struct tblentry *cmdp)
  7600. {
  7601. int idx;
  7602. const char *path;
  7603. char *name;
  7604. idx = cmdp->param.index;
  7605. path = pathval();
  7606. do {
  7607. padvance(&path, cmdp->cmdname);
  7608. } while (--idx >= 0);
  7609. name = stackblock();
  7610. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7611. }
  7612. /*
  7613. * Clear out command entries.
  7614. */
  7615. static void
  7616. clearcmdentry(void)
  7617. {
  7618. struct tblentry **tblp;
  7619. struct tblentry **pp;
  7620. struct tblentry *cmdp;
  7621. INT_OFF;
  7622. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7623. pp = tblp;
  7624. while ((cmdp = *pp) != NULL) {
  7625. if (cmdp->cmdtype == CMDNORMAL
  7626. || (cmdp->cmdtype == CMDBUILTIN
  7627. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7628. && builtinloc > 0
  7629. )
  7630. ) {
  7631. *pp = cmdp->next;
  7632. free(cmdp);
  7633. } else {
  7634. pp = &cmdp->next;
  7635. }
  7636. }
  7637. }
  7638. INT_ON;
  7639. }
  7640. /*
  7641. * Locate a command in the command hash table. If "add" is nonzero,
  7642. * add the command to the table if it is not already present. The
  7643. * variable "lastcmdentry" is set to point to the address of the link
  7644. * pointing to the entry, so that delete_cmd_entry can delete the
  7645. * entry.
  7646. *
  7647. * Interrupts must be off if called with add != 0.
  7648. */
  7649. static struct tblentry **lastcmdentry;
  7650. static struct tblentry *
  7651. cmdlookup(const char *name, int add)
  7652. {
  7653. unsigned int hashval;
  7654. const char *p;
  7655. struct tblentry *cmdp;
  7656. struct tblentry **pp;
  7657. p = name;
  7658. hashval = (unsigned char)*p << 4;
  7659. while (*p)
  7660. hashval += (unsigned char)*p++;
  7661. hashval &= 0x7FFF;
  7662. pp = &cmdtable[hashval % CMDTABLESIZE];
  7663. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7664. if (strcmp(cmdp->cmdname, name) == 0)
  7665. break;
  7666. pp = &cmdp->next;
  7667. }
  7668. if (add && cmdp == NULL) {
  7669. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7670. + strlen(name)
  7671. /* + 1 - already done because
  7672. * tblentry::cmdname is char[1] */);
  7673. /*cmdp->next = NULL; - ckzalloc did it */
  7674. cmdp->cmdtype = CMDUNKNOWN;
  7675. strcpy(cmdp->cmdname, name);
  7676. }
  7677. lastcmdentry = pp;
  7678. return cmdp;
  7679. }
  7680. /*
  7681. * Delete the command entry returned on the last lookup.
  7682. */
  7683. static void
  7684. delete_cmd_entry(void)
  7685. {
  7686. struct tblentry *cmdp;
  7687. INT_OFF;
  7688. cmdp = *lastcmdentry;
  7689. *lastcmdentry = cmdp->next;
  7690. if (cmdp->cmdtype == CMDFUNCTION)
  7691. freefunc(cmdp->param.func);
  7692. free(cmdp);
  7693. INT_ON;
  7694. }
  7695. /*
  7696. * Add a new command entry, replacing any existing command entry for
  7697. * the same name - except special builtins.
  7698. */
  7699. static void
  7700. addcmdentry(char *name, struct cmdentry *entry)
  7701. {
  7702. struct tblentry *cmdp;
  7703. cmdp = cmdlookup(name, 1);
  7704. if (cmdp->cmdtype == CMDFUNCTION) {
  7705. freefunc(cmdp->param.func);
  7706. }
  7707. cmdp->cmdtype = entry->cmdtype;
  7708. cmdp->param = entry->u;
  7709. cmdp->rehash = 0;
  7710. }
  7711. static int FAST_FUNC
  7712. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7713. {
  7714. struct tblentry **pp;
  7715. struct tblentry *cmdp;
  7716. int c;
  7717. struct cmdentry entry;
  7718. char *name;
  7719. if (nextopt("r") != '\0') {
  7720. clearcmdentry();
  7721. return 0;
  7722. }
  7723. if (*argptr == NULL) {
  7724. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7725. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7726. if (cmdp->cmdtype == CMDNORMAL)
  7727. printentry(cmdp);
  7728. }
  7729. }
  7730. return 0;
  7731. }
  7732. c = 0;
  7733. while ((name = *argptr) != NULL) {
  7734. cmdp = cmdlookup(name, 0);
  7735. if (cmdp != NULL
  7736. && (cmdp->cmdtype == CMDNORMAL
  7737. || (cmdp->cmdtype == CMDBUILTIN
  7738. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7739. && builtinloc > 0
  7740. )
  7741. )
  7742. ) {
  7743. delete_cmd_entry();
  7744. }
  7745. find_command(name, &entry, DO_ERR, pathval());
  7746. if (entry.cmdtype == CMDUNKNOWN)
  7747. c = 1;
  7748. argptr++;
  7749. }
  7750. return c;
  7751. }
  7752. /*
  7753. * Called when a cd is done. Marks all commands so the next time they
  7754. * are executed they will be rehashed.
  7755. */
  7756. static void
  7757. hashcd(void)
  7758. {
  7759. struct tblentry **pp;
  7760. struct tblentry *cmdp;
  7761. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7762. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7763. if (cmdp->cmdtype == CMDNORMAL
  7764. || (cmdp->cmdtype == CMDBUILTIN
  7765. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7766. && builtinloc > 0)
  7767. ) {
  7768. cmdp->rehash = 1;
  7769. }
  7770. }
  7771. }
  7772. }
  7773. /*
  7774. * Fix command hash table when PATH changed.
  7775. * Called before PATH is changed. The argument is the new value of PATH;
  7776. * pathval() still returns the old value at this point.
  7777. * Called with interrupts off.
  7778. */
  7779. static void FAST_FUNC
  7780. changepath(const char *newval)
  7781. {
  7782. const char *new;
  7783. int idx;
  7784. int bltin;
  7785. new = newval;
  7786. idx = 0;
  7787. bltin = -1;
  7788. for (;;) {
  7789. if (*new == '%' && prefix(new + 1, "builtin")) {
  7790. bltin = idx;
  7791. break;
  7792. }
  7793. new = strchr(new, ':');
  7794. if (!new)
  7795. break;
  7796. idx++;
  7797. new++;
  7798. }
  7799. builtinloc = bltin;
  7800. clearcmdentry();
  7801. }
  7802. enum {
  7803. TEOF,
  7804. TNL,
  7805. TREDIR,
  7806. TWORD,
  7807. TSEMI,
  7808. TBACKGND,
  7809. TAND,
  7810. TOR,
  7811. TPIPE,
  7812. TLP,
  7813. TRP,
  7814. TENDCASE,
  7815. TENDBQUOTE,
  7816. TNOT,
  7817. TCASE,
  7818. TDO,
  7819. TDONE,
  7820. TELIF,
  7821. TELSE,
  7822. TESAC,
  7823. TFI,
  7824. TFOR,
  7825. #if BASH_FUNCTION
  7826. TFUNCTION,
  7827. #endif
  7828. TIF,
  7829. TIN,
  7830. TTHEN,
  7831. TUNTIL,
  7832. TWHILE,
  7833. TBEGIN,
  7834. TEND
  7835. };
  7836. typedef smallint token_id_t;
  7837. /* Nth bit indicates if token marks the end of a list */
  7838. enum {
  7839. tokendlist = 0
  7840. /* 0 */ | (1u << TEOF)
  7841. /* 1 */ | (0u << TNL)
  7842. /* 2 */ | (0u << TREDIR)
  7843. /* 3 */ | (0u << TWORD)
  7844. /* 4 */ | (0u << TSEMI)
  7845. /* 5 */ | (0u << TBACKGND)
  7846. /* 6 */ | (0u << TAND)
  7847. /* 7 */ | (0u << TOR)
  7848. /* 8 */ | (0u << TPIPE)
  7849. /* 9 */ | (0u << TLP)
  7850. /* 10 */ | (1u << TRP)
  7851. /* 11 */ | (1u << TENDCASE)
  7852. /* 12 */ | (1u << TENDBQUOTE)
  7853. /* 13 */ | (0u << TNOT)
  7854. /* 14 */ | (0u << TCASE)
  7855. /* 15 */ | (1u << TDO)
  7856. /* 16 */ | (1u << TDONE)
  7857. /* 17 */ | (1u << TELIF)
  7858. /* 18 */ | (1u << TELSE)
  7859. /* 19 */ | (1u << TESAC)
  7860. /* 20 */ | (1u << TFI)
  7861. /* 21 */ | (0u << TFOR)
  7862. #if BASH_FUNCTION
  7863. /* 22 */ | (0u << TFUNCTION)
  7864. #endif
  7865. /* 23 */ | (0u << TIF)
  7866. /* 24 */ | (0u << TIN)
  7867. /* 25 */ | (1u << TTHEN)
  7868. /* 26 */ | (0u << TUNTIL)
  7869. /* 27 */ | (0u << TWHILE)
  7870. /* 28 */ | (0u << TBEGIN)
  7871. /* 29 */ | (1u << TEND)
  7872. , /* thus far 29 bits used */
  7873. };
  7874. static const char *const tokname_array[] ALIGN_PTR = {
  7875. "end of file",
  7876. "newline",
  7877. "redirection",
  7878. "word",
  7879. ";",
  7880. "&",
  7881. "&&",
  7882. "||",
  7883. "|",
  7884. "(",
  7885. ")",
  7886. ";;",
  7887. "`",
  7888. #define KWDOFFSET 13
  7889. /* the following are keywords */
  7890. "!",
  7891. "case",
  7892. "do",
  7893. "done",
  7894. "elif",
  7895. "else",
  7896. "esac",
  7897. "fi",
  7898. "for",
  7899. #if BASH_FUNCTION
  7900. "function",
  7901. #endif
  7902. "if",
  7903. "in",
  7904. "then",
  7905. "until",
  7906. "while",
  7907. "{",
  7908. "}",
  7909. };
  7910. /* Wrapper around strcmp for qsort/bsearch/... */
  7911. static int
  7912. pstrcmp(const void *a, const void *b)
  7913. {
  7914. return strcmp((char*)a, *(char**)b);
  7915. }
  7916. static const char *const *
  7917. findkwd(const char *s)
  7918. {
  7919. return bsearch(s, tokname_array + KWDOFFSET,
  7920. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7921. sizeof(tokname_array[0]), pstrcmp);
  7922. }
  7923. /*
  7924. * Locate and print what a word is...
  7925. */
  7926. static int
  7927. describe_command(char *command, const char *path, int describe_command_verbose)
  7928. {
  7929. struct cmdentry entry;
  7930. #if ENABLE_ASH_ALIAS
  7931. const struct alias *ap;
  7932. #endif
  7933. path = path ? path : pathval();
  7934. if (describe_command_verbose) {
  7935. out1str(command);
  7936. }
  7937. /* First look at the keywords */
  7938. if (findkwd(command)) {
  7939. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7940. goto out;
  7941. }
  7942. #if ENABLE_ASH_ALIAS
  7943. /* Then look at the aliases */
  7944. ap = lookupalias(command, 0);
  7945. if (ap != NULL) {
  7946. if (!describe_command_verbose) {
  7947. out1str("alias ");
  7948. printalias(ap);
  7949. return 0;
  7950. }
  7951. out1fmt(" is an alias for %s", ap->val);
  7952. goto out;
  7953. }
  7954. #endif
  7955. /* Brute force */
  7956. find_command(command, &entry, DO_ABS, path);
  7957. switch (entry.cmdtype) {
  7958. case CMDNORMAL: {
  7959. int j = entry.u.index;
  7960. char *p;
  7961. if (j < 0) {
  7962. p = command;
  7963. } else {
  7964. do {
  7965. padvance(&path, command);
  7966. } while (--j >= 0);
  7967. p = stackblock();
  7968. }
  7969. if (describe_command_verbose) {
  7970. out1fmt(" is %s", p);
  7971. } else {
  7972. out1str(p);
  7973. }
  7974. break;
  7975. }
  7976. case CMDFUNCTION:
  7977. if (describe_command_verbose) {
  7978. /*out1str(" is a shell function");*/
  7979. out1str(" is a function"); /* bash says this */
  7980. } else {
  7981. out1str(command);
  7982. }
  7983. break;
  7984. case CMDBUILTIN:
  7985. if (describe_command_verbose) {
  7986. out1fmt(" is a %sshell builtin",
  7987. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7988. "special " : nullstr
  7989. );
  7990. } else {
  7991. out1str(command);
  7992. }
  7993. break;
  7994. default:
  7995. if (describe_command_verbose) {
  7996. out1str(": not found\n");
  7997. }
  7998. return 127;
  7999. }
  8000. out:
  8001. out1str("\n");
  8002. return 0;
  8003. }
  8004. static int FAST_FUNC
  8005. typecmd(int argc UNUSED_PARAM, char **argv)
  8006. {
  8007. int i = 1;
  8008. int err = 0;
  8009. int verbose = 1;
  8010. /* type -p ... ? (we don't bother checking for 'p') */
  8011. if (argv[1] && argv[1][0] == '-') {
  8012. i++;
  8013. verbose = 0;
  8014. }
  8015. while (argv[i]) {
  8016. err |= describe_command(argv[i++], NULL, verbose);
  8017. }
  8018. return err;
  8019. }
  8020. static struct strlist *
  8021. fill_arglist(struct arglist *arglist, union node **argpp)
  8022. {
  8023. struct strlist **lastp = arglist->lastp;
  8024. union node *argp;
  8025. while ((argp = *argpp) != NULL) {
  8026. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  8027. *argpp = argp->narg.next;
  8028. if (*lastp)
  8029. break;
  8030. }
  8031. return *lastp;
  8032. }
  8033. #if ENABLE_ASH_CMDCMD
  8034. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  8035. static int
  8036. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  8037. {
  8038. struct strlist *sp = arglist->list;
  8039. char *cp, c;
  8040. for (;;) {
  8041. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  8042. if (!sp)
  8043. return 0;
  8044. cp = sp->text;
  8045. if (*cp++ != '-')
  8046. break;
  8047. c = *cp++;
  8048. if (!c)
  8049. break;
  8050. if (c == '-' && !*cp) {
  8051. if (!sp->next && !fill_arglist(arglist, argpp))
  8052. return 0;
  8053. sp = sp->next;
  8054. break;
  8055. }
  8056. do {
  8057. switch (c) {
  8058. case 'p':
  8059. *path = bb_default_path;
  8060. break;
  8061. default:
  8062. /* run 'typecmd' for other options */
  8063. return 0;
  8064. }
  8065. c = *cp++;
  8066. } while (c);
  8067. }
  8068. arglist->list = sp;
  8069. return DO_NOFUNC;
  8070. }
  8071. static int FAST_FUNC
  8072. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8073. {
  8074. char *cmd;
  8075. int c;
  8076. enum {
  8077. VERIFY_BRIEF = 1,
  8078. VERIFY_VERBOSE = 2,
  8079. } verify = 0;
  8080. const char *path = NULL;
  8081. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  8082. * never reaches this function.
  8083. */
  8084. while ((c = nextopt("pvV")) != '\0')
  8085. if (c == 'V')
  8086. verify |= VERIFY_VERBOSE;
  8087. else if (c == 'v')
  8088. /*verify |= VERIFY_BRIEF*/;
  8089. #if DEBUG
  8090. else if (c != 'p')
  8091. abort();
  8092. #endif
  8093. else
  8094. path = bb_default_path;
  8095. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  8096. cmd = *argptr;
  8097. if (/*verify && */ cmd)
  8098. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  8099. return 0;
  8100. }
  8101. #endif
  8102. /*static int funcblocksize; // size of structures in function */
  8103. /*static int funcstringsize; // size of strings in node */
  8104. static void *funcblock; /* block to allocate function from */
  8105. static char *funcstring_end; /* end of block to allocate strings from */
  8106. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  8107. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  8108. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  8109. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  8110. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  8111. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  8112. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8113. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8114. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8115. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  8116. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8117. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8118. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8119. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8120. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8121. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8122. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8123. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8124. #if BASH_REDIR_OUTPUT
  8125. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8126. #endif
  8127. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8128. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8129. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8130. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8131. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8132. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8133. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8134. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8135. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8136. };
  8137. static int calcsize(int funcblocksize, union node *n);
  8138. static int
  8139. sizenodelist(int funcblocksize, struct nodelist *lp)
  8140. {
  8141. while (lp) {
  8142. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8143. funcblocksize = calcsize(funcblocksize, lp->n);
  8144. lp = lp->next;
  8145. }
  8146. return funcblocksize;
  8147. }
  8148. static int
  8149. calcsize(int funcblocksize, union node *n)
  8150. {
  8151. if (n == NULL)
  8152. return funcblocksize;
  8153. funcblocksize += nodesize[n->type];
  8154. switch (n->type) {
  8155. case NCMD:
  8156. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8157. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8158. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8159. break;
  8160. case NPIPE:
  8161. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8162. break;
  8163. case NREDIR:
  8164. case NBACKGND:
  8165. case NSUBSHELL:
  8166. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8167. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8168. break;
  8169. case NAND:
  8170. case NOR:
  8171. case NSEMI:
  8172. case NWHILE:
  8173. case NUNTIL:
  8174. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8175. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8176. break;
  8177. case NIF:
  8178. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8179. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8180. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8181. break;
  8182. case NFOR:
  8183. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8184. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8185. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8186. break;
  8187. case NCASE:
  8188. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8189. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8190. break;
  8191. case NCLIST:
  8192. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8193. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8194. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8195. break;
  8196. case NDEFUN:
  8197. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8198. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8199. break;
  8200. case NARG:
  8201. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8202. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8203. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8204. break;
  8205. case NTO:
  8206. #if BASH_REDIR_OUTPUT
  8207. case NTO2:
  8208. #endif
  8209. case NCLOBBER:
  8210. case NFROM:
  8211. case NFROMTO:
  8212. case NAPPEND:
  8213. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8214. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8215. break;
  8216. case NTOFD:
  8217. case NFROMFD:
  8218. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8219. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8220. break;
  8221. case NHERE:
  8222. case NXHERE:
  8223. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8224. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8225. break;
  8226. case NNOT:
  8227. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8228. break;
  8229. };
  8230. return funcblocksize;
  8231. }
  8232. static char *
  8233. nodeckstrdup(char *s)
  8234. {
  8235. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8236. return strcpy(funcstring_end, s);
  8237. }
  8238. static union node *copynode(union node *);
  8239. static struct nodelist *
  8240. copynodelist(struct nodelist *lp)
  8241. {
  8242. struct nodelist *start;
  8243. struct nodelist **lpp;
  8244. lpp = &start;
  8245. while (lp) {
  8246. *lpp = funcblock;
  8247. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8248. (*lpp)->n = copynode(lp->n);
  8249. lp = lp->next;
  8250. lpp = &(*lpp)->next;
  8251. }
  8252. *lpp = NULL;
  8253. return start;
  8254. }
  8255. static union node *
  8256. copynode(union node *n)
  8257. {
  8258. union node *new;
  8259. if (n == NULL)
  8260. return NULL;
  8261. new = funcblock;
  8262. funcblock = (char *) funcblock + nodesize[n->type];
  8263. switch (n->type) {
  8264. case NCMD:
  8265. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8266. new->ncmd.args = copynode(n->ncmd.args);
  8267. new->ncmd.assign = copynode(n->ncmd.assign);
  8268. new->ncmd.linno = n->ncmd.linno;
  8269. break;
  8270. case NPIPE:
  8271. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8272. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8273. break;
  8274. case NREDIR:
  8275. case NBACKGND:
  8276. case NSUBSHELL:
  8277. new->nredir.redirect = copynode(n->nredir.redirect);
  8278. new->nredir.n = copynode(n->nredir.n);
  8279. new->nredir.linno = n->nredir.linno;
  8280. break;
  8281. case NAND:
  8282. case NOR:
  8283. case NSEMI:
  8284. case NWHILE:
  8285. case NUNTIL:
  8286. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8287. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8288. break;
  8289. case NIF:
  8290. new->nif.elsepart = copynode(n->nif.elsepart);
  8291. new->nif.ifpart = copynode(n->nif.ifpart);
  8292. new->nif.test = copynode(n->nif.test);
  8293. break;
  8294. case NFOR:
  8295. new->nfor.var = nodeckstrdup(n->nfor.var);
  8296. new->nfor.body = copynode(n->nfor.body);
  8297. new->nfor.args = copynode(n->nfor.args);
  8298. new->nfor.linno = n->nfor.linno;
  8299. break;
  8300. case NCASE:
  8301. new->ncase.cases = copynode(n->ncase.cases);
  8302. new->ncase.expr = copynode(n->ncase.expr);
  8303. new->ncase.linno = n->ncase.linno;
  8304. break;
  8305. case NCLIST:
  8306. new->nclist.body = copynode(n->nclist.body);
  8307. new->nclist.pattern = copynode(n->nclist.pattern);
  8308. new->nclist.next = copynode(n->nclist.next);
  8309. break;
  8310. case NDEFUN:
  8311. new->ndefun.body = copynode(n->ndefun.body);
  8312. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8313. new->ndefun.linno = n->ndefun.linno;
  8314. break;
  8315. case NARG:
  8316. new->narg.backquote = copynodelist(n->narg.backquote);
  8317. new->narg.text = nodeckstrdup(n->narg.text);
  8318. new->narg.next = copynode(n->narg.next);
  8319. break;
  8320. case NTO:
  8321. #if BASH_REDIR_OUTPUT
  8322. case NTO2:
  8323. #endif
  8324. case NCLOBBER:
  8325. case NFROM:
  8326. case NFROMTO:
  8327. case NAPPEND:
  8328. new->nfile.fname = copynode(n->nfile.fname);
  8329. new->nfile.fd = n->nfile.fd;
  8330. new->nfile.next = copynode(n->nfile.next);
  8331. break;
  8332. case NTOFD:
  8333. case NFROMFD:
  8334. new->ndup.vname = copynode(n->ndup.vname);
  8335. new->ndup.dupfd = n->ndup.dupfd;
  8336. new->ndup.fd = n->ndup.fd;
  8337. new->ndup.next = copynode(n->ndup.next);
  8338. break;
  8339. case NHERE:
  8340. case NXHERE:
  8341. new->nhere.doc = copynode(n->nhere.doc);
  8342. new->nhere.fd = n->nhere.fd;
  8343. new->nhere.next = copynode(n->nhere.next);
  8344. break;
  8345. case NNOT:
  8346. new->nnot.com = copynode(n->nnot.com);
  8347. break;
  8348. };
  8349. new->type = n->type;
  8350. return new;
  8351. }
  8352. /*
  8353. * Make a copy of a parse tree.
  8354. */
  8355. static struct funcnode *
  8356. copyfunc(union node *n)
  8357. {
  8358. struct funcnode *f;
  8359. size_t blocksize;
  8360. /*funcstringsize = 0;*/
  8361. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8362. f = ckzalloc(blocksize /* + funcstringsize */);
  8363. funcblock = (char *) f + offsetof(struct funcnode, n);
  8364. funcstring_end = (char *) f + blocksize;
  8365. copynode(n);
  8366. /* f->count = 0; - ckzalloc did it */
  8367. return f;
  8368. }
  8369. /*
  8370. * Define a shell function.
  8371. */
  8372. static void
  8373. defun(union node *func)
  8374. {
  8375. struct cmdentry entry;
  8376. INT_OFF;
  8377. entry.cmdtype = CMDFUNCTION;
  8378. entry.u.func = copyfunc(func);
  8379. addcmdentry(func->ndefun.text, &entry);
  8380. INT_ON;
  8381. }
  8382. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8383. #define SKIPBREAK (1 << 0)
  8384. #define SKIPCONT (1 << 1)
  8385. #define SKIPFUNC (1 << 2)
  8386. #define SKIPFUNCDEF (1 << 3)
  8387. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8388. static int skipcount; /* number of levels to skip */
  8389. static int loopnest; /* current loop nesting level */
  8390. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8391. /* Forward decl way out to parsing code - dotrap needs it */
  8392. static int evalstring(char *s, int flags);
  8393. /* Called to execute a trap.
  8394. * Single callsite - at the end of evaltree().
  8395. * If we return non-zero, evaltree raises EXEXIT exception.
  8396. *
  8397. * Perhaps we should avoid entering new trap handlers
  8398. * while we are executing a trap handler. [is it a TODO?]
  8399. */
  8400. static void
  8401. dotrap(void)
  8402. {
  8403. uint8_t *g;
  8404. int sig;
  8405. int status, last_status;
  8406. if (!pending_sig)
  8407. return;
  8408. status = savestatus;
  8409. last_status = status;
  8410. if (status < 0) {
  8411. status = exitstatus;
  8412. savestatus = status;
  8413. }
  8414. pending_sig = 0;
  8415. barrier();
  8416. TRACE(("dotrap entered\n"));
  8417. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8418. char *p;
  8419. if (!*g)
  8420. continue;
  8421. if (evalskip) {
  8422. pending_sig = sig;
  8423. break;
  8424. }
  8425. p = trap[sig];
  8426. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8427. * don't upset it by resetting gotsig[SIGINT-1] */
  8428. if (sig == SIGINT && !p)
  8429. continue;
  8430. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8431. *g = 0;
  8432. if (!p)
  8433. continue;
  8434. evalstring(p, 0);
  8435. if (evalskip != SKIPFUNC)
  8436. exitstatus = status;
  8437. }
  8438. savestatus = last_status;
  8439. TRACE(("dotrap returns\n"));
  8440. }
  8441. /* forward declarations - evaluation is fairly recursive business... */
  8442. static int evalloop(union node *, int);
  8443. static int evalfor(union node *, int);
  8444. static int evalcase(union node *, int);
  8445. static int evalsubshell(union node *, int);
  8446. static void expredir(union node *);
  8447. static int evalpipe(union node *, int);
  8448. static int evalcommand(union node *, int);
  8449. static int evalbltin(const struct builtincmd *, int, char **, int);
  8450. static void prehash(union node *);
  8451. /*
  8452. * Evaluate a parse tree. The value is left in the global variable
  8453. * exitstatus.
  8454. */
  8455. static int
  8456. evaltree(union node *n, int flags)
  8457. {
  8458. int checkexit = 0;
  8459. int (*evalfn)(union node *, int);
  8460. struct stackmark smark;
  8461. int status = 0;
  8462. setstackmark(&smark);
  8463. if (n == NULL) {
  8464. TRACE(("evaltree(NULL) called\n"));
  8465. goto out;
  8466. }
  8467. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8468. dotrap();
  8469. switch (n->type) {
  8470. default:
  8471. #if DEBUG
  8472. out1fmt("Node type = %d\n", n->type);
  8473. fflush_all();
  8474. break;
  8475. #endif
  8476. case NNOT:
  8477. status = !evaltree(n->nnot.com, EV_TESTED);
  8478. goto setstatus;
  8479. case NREDIR:
  8480. errlinno = lineno = n->nredir.linno;
  8481. if (funcline)
  8482. lineno -= funcline - 1;
  8483. expredir(n->nredir.redirect);
  8484. pushredir(n->nredir.redirect);
  8485. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8486. if (!status) {
  8487. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8488. }
  8489. if (n->nredir.redirect)
  8490. popredir(/*drop:*/ 0);
  8491. goto setstatus;
  8492. case NCMD:
  8493. evalfn = evalcommand;
  8494. checkexit:
  8495. if (eflag && !(flags & EV_TESTED))
  8496. checkexit = ~0;
  8497. goto calleval;
  8498. case NFOR:
  8499. evalfn = evalfor;
  8500. goto calleval;
  8501. case NWHILE:
  8502. case NUNTIL:
  8503. evalfn = evalloop;
  8504. goto calleval;
  8505. case NSUBSHELL:
  8506. case NBACKGND:
  8507. evalfn = evalsubshell;
  8508. goto checkexit;
  8509. case NPIPE:
  8510. evalfn = evalpipe;
  8511. goto checkexit;
  8512. case NCASE:
  8513. evalfn = evalcase;
  8514. goto calleval;
  8515. case NAND:
  8516. case NOR:
  8517. case NSEMI: {
  8518. #if NAND + 1 != NOR
  8519. #error NAND + 1 != NOR
  8520. #endif
  8521. #if NOR + 1 != NSEMI
  8522. #error NOR + 1 != NSEMI
  8523. #endif
  8524. unsigned is_or = n->type - NAND;
  8525. status = evaltree(
  8526. n->nbinary.ch1,
  8527. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8528. );
  8529. if ((!status) == is_or || evalskip)
  8530. break;
  8531. n = n->nbinary.ch2;
  8532. evaln:
  8533. evalfn = evaltree;
  8534. calleval:
  8535. status = evalfn(n, flags);
  8536. goto setstatus;
  8537. }
  8538. case NIF:
  8539. status = evaltree(n->nif.test, EV_TESTED);
  8540. if (evalskip)
  8541. break;
  8542. if (!status) {
  8543. n = n->nif.ifpart;
  8544. goto evaln;
  8545. }
  8546. if (n->nif.elsepart) {
  8547. n = n->nif.elsepart;
  8548. goto evaln;
  8549. }
  8550. status = 0;
  8551. goto setstatus;
  8552. case NDEFUN:
  8553. defun(n);
  8554. /* Not necessary. To test it:
  8555. * "false; f() { qwerty; }; echo $?" should print 0.
  8556. */
  8557. /* status = 0; */
  8558. setstatus:
  8559. exitstatus = status;
  8560. break;
  8561. }
  8562. out:
  8563. /* Order of checks below is important:
  8564. * signal handlers trigger before exit caused by "set -e".
  8565. */
  8566. dotrap();
  8567. if (checkexit & status)
  8568. raise_exception(EXEND);
  8569. if (flags & EV_EXIT)
  8570. raise_exception(EXEND);
  8571. popstackmark(&smark);
  8572. TRACE(("leaving evaltree (no interrupts)\n"));
  8573. return exitstatus;
  8574. }
  8575. static int
  8576. skiploop(void)
  8577. {
  8578. int skip = evalskip;
  8579. switch (skip) {
  8580. case 0:
  8581. break;
  8582. case SKIPBREAK:
  8583. case SKIPCONT:
  8584. if (--skipcount <= 0) {
  8585. evalskip = 0;
  8586. break;
  8587. }
  8588. skip = SKIPBREAK;
  8589. break;
  8590. }
  8591. return skip;
  8592. }
  8593. static int
  8594. evalloop(union node *n, int flags)
  8595. {
  8596. int skip;
  8597. int status;
  8598. loopnest++;
  8599. status = 0;
  8600. flags &= EV_TESTED;
  8601. do {
  8602. int i;
  8603. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8604. skip = skiploop();
  8605. if (skip == SKIPFUNC)
  8606. status = i;
  8607. if (skip)
  8608. continue;
  8609. if (n->type != NWHILE)
  8610. i = !i;
  8611. if (i != 0)
  8612. break;
  8613. status = evaltree(n->nbinary.ch2, flags);
  8614. skip = skiploop();
  8615. } while (!(skip & ~SKIPCONT));
  8616. loopnest--;
  8617. return status;
  8618. }
  8619. static int
  8620. evalfor(union node *n, int flags)
  8621. {
  8622. struct arglist arglist;
  8623. union node *argp;
  8624. struct strlist *sp;
  8625. int status = 0;
  8626. errlinno = lineno = n->ncase.linno;
  8627. if (funcline)
  8628. lineno -= funcline - 1;
  8629. arglist.list = NULL;
  8630. arglist.lastp = &arglist.list;
  8631. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8632. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8633. }
  8634. *arglist.lastp = NULL;
  8635. loopnest++;
  8636. flags &= EV_TESTED;
  8637. for (sp = arglist.list; sp; sp = sp->next) {
  8638. setvar0(n->nfor.var, sp->text);
  8639. status = evaltree(n->nfor.body, flags);
  8640. if (skiploop() & ~SKIPCONT)
  8641. break;
  8642. }
  8643. loopnest--;
  8644. return status;
  8645. }
  8646. static int
  8647. evalcase(union node *n, int flags)
  8648. {
  8649. union node *cp;
  8650. union node *patp;
  8651. struct arglist arglist;
  8652. int status = 0;
  8653. errlinno = lineno = n->ncase.linno;
  8654. if (funcline)
  8655. lineno -= funcline - 1;
  8656. arglist.list = NULL;
  8657. arglist.lastp = &arglist.list;
  8658. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8659. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8660. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8661. if (casematch(patp, arglist.list->text)) {
  8662. /* Ensure body is non-empty as otherwise
  8663. * EV_EXIT may prevent us from setting the
  8664. * exit status.
  8665. */
  8666. if (evalskip == 0 && cp->nclist.body) {
  8667. status = evaltree(cp->nclist.body, flags);
  8668. }
  8669. goto out;
  8670. }
  8671. }
  8672. }
  8673. out:
  8674. return status;
  8675. }
  8676. /*
  8677. * Kick off a subshell to evaluate a tree.
  8678. */
  8679. static int
  8680. evalsubshell(union node *n, int flags)
  8681. {
  8682. struct job *jp;
  8683. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8684. int status;
  8685. errlinno = lineno = n->nredir.linno;
  8686. if (funcline)
  8687. lineno -= funcline - 1;
  8688. expredir(n->nredir.redirect);
  8689. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8690. goto nofork;
  8691. INT_OFF;
  8692. if (backgnd == FORK_FG)
  8693. get_tty_state();
  8694. jp = makejob(/*n,*/ 1);
  8695. if (forkshell(jp, n, backgnd) == 0) {
  8696. /* child */
  8697. INT_ON;
  8698. flags |= EV_EXIT;
  8699. if (backgnd)
  8700. flags &= ~EV_TESTED;
  8701. nofork:
  8702. redirect(n->nredir.redirect, 0);
  8703. evaltreenr(n->nredir.n, flags);
  8704. /* never returns */
  8705. }
  8706. /* parent */
  8707. status = 0;
  8708. if (backgnd == FORK_FG)
  8709. status = waitforjob(jp);
  8710. INT_ON;
  8711. return status;
  8712. }
  8713. /*
  8714. * Compute the names of the files in a redirection list.
  8715. */
  8716. static void fixredir(union node *, const char *, int);
  8717. static void
  8718. expredir(union node *n)
  8719. {
  8720. union node *redir;
  8721. for (redir = n; redir; redir = redir->nfile.next) {
  8722. struct arglist fn;
  8723. fn.list = NULL;
  8724. fn.lastp = &fn.list;
  8725. switch (redir->type) {
  8726. case NFROMTO:
  8727. case NFROM:
  8728. case NTO:
  8729. #if BASH_REDIR_OUTPUT
  8730. case NTO2:
  8731. #endif
  8732. case NCLOBBER:
  8733. case NAPPEND:
  8734. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8735. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8736. #if BASH_REDIR_OUTPUT
  8737. store_expfname:
  8738. #endif
  8739. #if 0
  8740. // By the design of stack allocator, the loop of this kind:
  8741. // while true; do while true; do break; done </dev/null; done
  8742. // will look like a memory leak: ash plans to free expfname's
  8743. // of "/dev/null" as soon as it finishes running the loop
  8744. // (in this case, never).
  8745. // This "fix" is wrong:
  8746. if (redir->nfile.expfname)
  8747. stunalloc(redir->nfile.expfname);
  8748. // It results in corrupted state of stacked allocations.
  8749. #endif
  8750. redir->nfile.expfname = fn.list->text;
  8751. break;
  8752. case NFROMFD:
  8753. case NTOFD: /* >& */
  8754. if (redir->ndup.vname) {
  8755. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8756. if (fn.list == NULL)
  8757. ash_msg_and_raise_error("redir error");
  8758. #if BASH_REDIR_OUTPUT
  8759. if (!isdigit_str9(fn.list->text)) {
  8760. /* >&file, not >&fd */
  8761. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8762. ash_msg_and_raise_error("redir error");
  8763. redir->type = NTO2;
  8764. goto store_expfname;
  8765. }
  8766. #endif
  8767. fixredir(redir, fn.list->text, 1);
  8768. }
  8769. break;
  8770. }
  8771. }
  8772. }
  8773. /*
  8774. * Evaluate a pipeline. All the processes in the pipeline are children
  8775. * of the process creating the pipeline. (This differs from some versions
  8776. * of the shell, which make the last process in a pipeline the parent
  8777. * of all the rest.)
  8778. */
  8779. static int
  8780. evalpipe(union node *n, int flags)
  8781. {
  8782. struct job *jp;
  8783. struct nodelist *lp;
  8784. int pipelen;
  8785. int prevfd;
  8786. int pip[2];
  8787. int status = 0;
  8788. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8789. pipelen = 0;
  8790. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8791. pipelen++;
  8792. flags |= EV_EXIT;
  8793. INT_OFF;
  8794. if (n->npipe.pipe_backgnd == 0)
  8795. get_tty_state();
  8796. jp = makejob(/*n,*/ pipelen);
  8797. prevfd = -1;
  8798. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8799. prehash(lp->n);
  8800. pip[1] = -1;
  8801. if (lp->next) {
  8802. if (pipe(pip) < 0) {
  8803. close(prevfd);
  8804. ash_msg_and_raise_perror("can't create pipe");
  8805. }
  8806. }
  8807. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8808. /* child */
  8809. INT_ON;
  8810. if (pip[1] >= 0) {
  8811. close(pip[0]);
  8812. }
  8813. if (prevfd > 0) {
  8814. dup2(prevfd, 0);
  8815. close(prevfd);
  8816. }
  8817. if (pip[1] > 1) {
  8818. dup2(pip[1], 1);
  8819. close(pip[1]);
  8820. }
  8821. evaltreenr(lp->n, flags);
  8822. /* never returns */
  8823. }
  8824. /* parent */
  8825. if (prevfd >= 0)
  8826. close(prevfd);
  8827. prevfd = pip[0];
  8828. /* Don't want to trigger debugging */
  8829. if (pip[1] != -1)
  8830. close(pip[1]);
  8831. }
  8832. if (n->npipe.pipe_backgnd == 0) {
  8833. status = waitforjob(jp);
  8834. TRACE(("evalpipe: job done exit status %d\n", status));
  8835. }
  8836. INT_ON;
  8837. return status;
  8838. }
  8839. /* setinteractive needs this forward reference */
  8840. #if EDITING_HAS_get_exe_name
  8841. static const char *get_builtin_name(int i) FAST_FUNC;
  8842. #endif
  8843. /*
  8844. * Controls whether the shell is interactive or not.
  8845. */
  8846. static void
  8847. setinteractive(int on)
  8848. {
  8849. static smallint is_interactive;
  8850. if (++on == is_interactive)
  8851. return;
  8852. is_interactive = on;
  8853. setsignal(SIGINT);
  8854. setsignal(SIGQUIT);
  8855. setsignal(SIGTERM);
  8856. if (is_interactive > 1) {
  8857. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8858. /* Looks like they want an interactive shell */
  8859. static smallint did_banner;
  8860. if (!did_banner) {
  8861. /* note: ash and hush share this string */
  8862. out1fmt("\n\n%s %s\n"
  8863. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8864. "\n",
  8865. bb_banner,
  8866. "built-in shell (ash)"
  8867. );
  8868. did_banner = 1;
  8869. }
  8870. #endif
  8871. #if ENABLE_FEATURE_EDITING
  8872. if (!line_input_state) {
  8873. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8874. # if EDITING_HAS_get_exe_name
  8875. line_input_state->get_exe_name = get_builtin_name;
  8876. # endif
  8877. }
  8878. #endif
  8879. }
  8880. }
  8881. static void
  8882. optschanged(void)
  8883. {
  8884. #if DEBUG
  8885. opentrace();
  8886. #endif
  8887. setinteractive(iflag);
  8888. setjobctl(mflag);
  8889. #if ENABLE_FEATURE_EDITING_VI
  8890. if (line_input_state) {
  8891. if (viflag)
  8892. line_input_state->flags |= VI_MODE;
  8893. else
  8894. line_input_state->flags &= ~VI_MODE;
  8895. }
  8896. #else
  8897. viflag = 0; /* forcibly keep the option off */
  8898. #endif
  8899. }
  8900. struct localvar_list {
  8901. struct localvar_list *next;
  8902. struct localvar *lv;
  8903. };
  8904. static struct localvar_list *localvar_stack;
  8905. /*
  8906. * Called after a function returns.
  8907. * Interrupts must be off.
  8908. */
  8909. static void
  8910. poplocalvars(int keep)
  8911. {
  8912. struct localvar_list *ll;
  8913. struct localvar *lvp, *next;
  8914. struct var *vp;
  8915. INT_OFF;
  8916. ll = localvar_stack;
  8917. localvar_stack = ll->next;
  8918. next = ll->lv;
  8919. free(ll);
  8920. while ((lvp = next) != NULL) {
  8921. next = lvp->next;
  8922. vp = lvp->vp;
  8923. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8924. if (keep) {
  8925. int bits = VSTRFIXED;
  8926. if (lvp->flags != VUNSET) {
  8927. if (vp->var_text == lvp->text)
  8928. bits |= VTEXTFIXED;
  8929. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8930. free((char*)lvp->text);
  8931. }
  8932. vp->flags &= ~bits;
  8933. vp->flags |= (lvp->flags & bits);
  8934. if ((vp->flags &
  8935. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8936. unsetvar(vp->var_text);
  8937. } else if (vp == NULL) { /* $- saved */
  8938. memcpy(optlist, lvp->text, sizeof(optlist));
  8939. free((char*)lvp->text);
  8940. optschanged();
  8941. } else if (lvp->flags == VUNSET) {
  8942. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8943. unsetvar(vp->var_text);
  8944. } else {
  8945. if (vp->var_func)
  8946. vp->var_func(var_end(lvp->text));
  8947. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8948. free((char*)vp->var_text);
  8949. vp->flags = lvp->flags;
  8950. vp->var_text = lvp->text;
  8951. }
  8952. free(lvp);
  8953. }
  8954. INT_ON;
  8955. }
  8956. /*
  8957. * Create a new localvar environment.
  8958. */
  8959. static struct localvar_list *
  8960. pushlocalvars(int push)
  8961. {
  8962. struct localvar_list *ll;
  8963. struct localvar_list *top;
  8964. top = localvar_stack;
  8965. if (!push)
  8966. goto out;
  8967. INT_OFF;
  8968. ll = ckzalloc(sizeof(*ll));
  8969. /*ll->lv = NULL; - zalloc did it */
  8970. ll->next = top;
  8971. localvar_stack = ll;
  8972. INT_ON;
  8973. out:
  8974. return top;
  8975. }
  8976. static void
  8977. unwindlocalvars(struct localvar_list *stop)
  8978. {
  8979. while (localvar_stack != stop)
  8980. poplocalvars(0);
  8981. }
  8982. static int
  8983. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8984. {
  8985. volatile struct shparam saveparam;
  8986. struct jmploc *volatile savehandler;
  8987. struct jmploc jmploc;
  8988. int e;
  8989. int savefuncline;
  8990. saveparam = shellparam;
  8991. savefuncline = funcline;
  8992. savehandler = exception_handler;
  8993. e = setjmp(jmploc.loc);
  8994. if (e) {
  8995. goto funcdone;
  8996. }
  8997. INT_OFF;
  8998. exception_handler = &jmploc;
  8999. shellparam.malloced = 0;
  9000. func->count++;
  9001. funcline = func->n.ndefun.linno;
  9002. INT_ON;
  9003. shellparam.nparam = argc - 1;
  9004. shellparam.p = argv + 1;
  9005. #if ENABLE_ASH_GETOPTS
  9006. shellparam.optind = 1;
  9007. shellparam.optoff = -1;
  9008. #endif
  9009. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  9010. funcdone:
  9011. INT_OFF;
  9012. funcline = savefuncline;
  9013. freefunc(func);
  9014. freeparam(&shellparam);
  9015. shellparam = saveparam;
  9016. exception_handler = savehandler;
  9017. INT_ON;
  9018. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  9019. return e;
  9020. }
  9021. /*
  9022. * Make a variable a local variable. When a variable is made local, it's
  9023. * value and flags are saved in a localvar structure. The saved values
  9024. * will be restored when the shell function returns. We handle the name
  9025. * "-" as a special case: it makes changes to "set +-options" local
  9026. * (options will be restored on return from the function).
  9027. */
  9028. static void
  9029. mklocal(char *name, int flags)
  9030. {
  9031. struct localvar *lvp;
  9032. struct var **vpp;
  9033. struct var *vp;
  9034. char *eq = strchr(name, '=');
  9035. INT_OFF;
  9036. /* Cater for duplicate "local". Examples:
  9037. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  9038. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  9039. */
  9040. lvp = localvar_stack->lv;
  9041. while (lvp) {
  9042. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  9043. if (eq)
  9044. setvareq(name, 0);
  9045. /* else:
  9046. * it's a duplicate "local VAR" declaration, do nothing
  9047. */
  9048. goto ret;
  9049. }
  9050. lvp = lvp->next;
  9051. }
  9052. lvp = ckzalloc(sizeof(*lvp));
  9053. if (LONE_DASH(name)) {
  9054. char *p;
  9055. p = ckmalloc(sizeof(optlist));
  9056. lvp->text = memcpy(p, optlist, sizeof(optlist));
  9057. vp = NULL;
  9058. } else {
  9059. vpp = hashvar(name);
  9060. vp = *findvar(vpp, name);
  9061. if (vp == NULL) {
  9062. /* variable did not exist yet */
  9063. if (eq)
  9064. vp = setvareq(name, VSTRFIXED | flags);
  9065. else
  9066. vp = setvar(name, NULL, VSTRFIXED | flags);
  9067. lvp->flags = VUNSET;
  9068. } else {
  9069. lvp->text = vp->var_text;
  9070. lvp->flags = vp->flags;
  9071. /* make sure neither "struct var" nor string gets freed
  9072. * during (un)setting:
  9073. */
  9074. vp->flags |= VSTRFIXED|VTEXTFIXED;
  9075. if (eq)
  9076. setvareq(name, flags);
  9077. else
  9078. /* "local VAR" unsets VAR: */
  9079. setvar0(name, NULL);
  9080. }
  9081. }
  9082. lvp->vp = vp;
  9083. lvp->next = localvar_stack->lv;
  9084. localvar_stack->lv = lvp;
  9085. ret:
  9086. INT_ON;
  9087. }
  9088. /*
  9089. * The "local" command.
  9090. */
  9091. static int FAST_FUNC
  9092. localcmd(int argc UNUSED_PARAM, char **argv)
  9093. {
  9094. char *name;
  9095. if (!localvar_stack)
  9096. ash_msg_and_raise_error("not in a function");
  9097. argv = argptr;
  9098. while ((name = *argv++) != NULL) {
  9099. mklocal(name, 0);
  9100. }
  9101. return 0;
  9102. }
  9103. static int FAST_FUNC
  9104. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9105. {
  9106. return 1;
  9107. }
  9108. static int FAST_FUNC
  9109. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9110. {
  9111. return 0;
  9112. }
  9113. static int FAST_FUNC
  9114. execcmd(int argc UNUSED_PARAM, char **argv)
  9115. {
  9116. optionarg = NULL;
  9117. while (nextopt("a:") != '\0')
  9118. /* nextopt() sets optionarg to "-a ARGV0" */;
  9119. argv = argptr;
  9120. if (argv[0]) {
  9121. char *prog;
  9122. iflag = 0; /* exit on error */
  9123. mflag = 0;
  9124. optschanged();
  9125. /* We should set up signals for "exec CMD"
  9126. * the same way as for "CMD" without "exec".
  9127. * But optschanged->setinteractive->setsignal
  9128. * still thought we are a root shell. Therefore, for example,
  9129. * SIGQUIT is still set to IGN. Fix it:
  9130. */
  9131. shlvl++;
  9132. setsignal(SIGQUIT);
  9133. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9134. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9135. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9136. prog = argv[0];
  9137. if (optionarg)
  9138. argv[0] = optionarg;
  9139. shellexec(prog, argv, pathval(), 0);
  9140. /* NOTREACHED */
  9141. }
  9142. return 0;
  9143. }
  9144. /*
  9145. * The return command.
  9146. */
  9147. static int FAST_FUNC
  9148. returncmd(int argc UNUSED_PARAM, char **argv)
  9149. {
  9150. int skip;
  9151. int status;
  9152. /*
  9153. * If called outside a function, do what ksh does;
  9154. * skip the rest of the file.
  9155. */
  9156. if (argv[1]) {
  9157. skip = SKIPFUNC;
  9158. status = number(argv[1]);
  9159. } else {
  9160. skip = SKIPFUNCDEF;
  9161. status = exitstatus;
  9162. }
  9163. evalskip = skip;
  9164. return status;
  9165. }
  9166. /* Forward declarations for builtintab[] */
  9167. static int breakcmd(int, char **) FAST_FUNC;
  9168. static int dotcmd(int, char **) FAST_FUNC;
  9169. static int evalcmd(int, char **, int) FAST_FUNC;
  9170. static int exitcmd(int, char **) FAST_FUNC;
  9171. static int exportcmd(int, char **) FAST_FUNC;
  9172. #if ENABLE_ASH_GETOPTS
  9173. static int getoptscmd(int, char **) FAST_FUNC;
  9174. #endif
  9175. #if ENABLE_ASH_HELP
  9176. static int helpcmd(int, char **) FAST_FUNC;
  9177. #endif
  9178. #if MAX_HISTORY
  9179. static int historycmd(int, char **) FAST_FUNC;
  9180. #endif
  9181. #if ENABLE_FEATURE_SH_MATH
  9182. static int letcmd(int, char **) FAST_FUNC;
  9183. #endif
  9184. static int readcmd(int, char **) FAST_FUNC;
  9185. static int setcmd(int, char **) FAST_FUNC;
  9186. static int shiftcmd(int, char **) FAST_FUNC;
  9187. static int timescmd(int, char **) FAST_FUNC;
  9188. static int trapcmd(int, char **) FAST_FUNC;
  9189. static int umaskcmd(int, char **) FAST_FUNC;
  9190. static int unsetcmd(int, char **) FAST_FUNC;
  9191. static int ulimitcmd(int, char **) FAST_FUNC;
  9192. #define BUILTIN_NOSPEC "0"
  9193. #define BUILTIN_SPECIAL "1"
  9194. #define BUILTIN_REGULAR "2"
  9195. #define BUILTIN_SPEC_REG "3"
  9196. #define BUILTIN_ASSIGN "4"
  9197. #define BUILTIN_SPEC_ASSG "5"
  9198. #define BUILTIN_REG_ASSG "6"
  9199. #define BUILTIN_SPEC_REG_ASSG "7"
  9200. /* Stubs for calling non-FAST_FUNC's */
  9201. #if ENABLE_ASH_ECHO
  9202. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9203. #endif
  9204. #if ENABLE_ASH_PRINTF
  9205. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9206. #endif
  9207. #if ENABLE_ASH_TEST || BASH_TEST2
  9208. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9209. #endif
  9210. /* Keep these in proper order since it is searched via bsearch() */
  9211. static const struct builtincmd builtintab[] = {
  9212. { BUILTIN_SPEC_REG "." , dotcmd },
  9213. { BUILTIN_SPEC_REG ":" , truecmd },
  9214. #if ENABLE_ASH_TEST
  9215. { BUILTIN_REGULAR "[" , testcmd },
  9216. #endif
  9217. #if BASH_TEST2
  9218. { BUILTIN_REGULAR "[[" , testcmd },
  9219. #endif
  9220. #if ENABLE_ASH_ALIAS
  9221. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9222. #endif
  9223. #if JOBS
  9224. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9225. #endif
  9226. { BUILTIN_SPEC_REG "break" , breakcmd },
  9227. { BUILTIN_REGULAR "cd" , cdcmd },
  9228. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9229. #if ENABLE_ASH_CMDCMD
  9230. { BUILTIN_REGULAR "command" , commandcmd },
  9231. #endif
  9232. { BUILTIN_SPEC_REG "continue", breakcmd },
  9233. #if ENABLE_ASH_ECHO
  9234. { BUILTIN_REGULAR "echo" , echocmd },
  9235. #endif
  9236. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9237. { BUILTIN_SPEC_REG "exec" , execcmd },
  9238. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9239. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9240. { BUILTIN_REGULAR "false" , falsecmd },
  9241. #if JOBS
  9242. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9243. #endif
  9244. #if ENABLE_ASH_GETOPTS
  9245. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9246. #endif
  9247. { BUILTIN_REGULAR "hash" , hashcmd },
  9248. #if ENABLE_ASH_HELP
  9249. { BUILTIN_NOSPEC "help" , helpcmd },
  9250. #endif
  9251. #if MAX_HISTORY
  9252. { BUILTIN_NOSPEC "history" , historycmd },
  9253. #endif
  9254. #if JOBS
  9255. { BUILTIN_REGULAR "jobs" , jobscmd },
  9256. { BUILTIN_REGULAR "kill" , killcmd },
  9257. #endif
  9258. #if ENABLE_FEATURE_SH_MATH
  9259. { BUILTIN_NOSPEC "let" , letcmd },
  9260. #endif
  9261. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9262. #if ENABLE_ASH_PRINTF
  9263. { BUILTIN_REGULAR "printf" , printfcmd },
  9264. #endif
  9265. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9266. { BUILTIN_REGULAR "read" , readcmd },
  9267. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9268. { BUILTIN_SPEC_REG "return" , returncmd },
  9269. { BUILTIN_SPEC_REG "set" , setcmd },
  9270. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9271. #if BASH_SOURCE
  9272. { BUILTIN_SPEC_REG "source" , dotcmd },
  9273. #endif
  9274. #if ENABLE_ASH_TEST
  9275. { BUILTIN_REGULAR "test" , testcmd },
  9276. #endif
  9277. { BUILTIN_SPEC_REG "times" , timescmd },
  9278. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9279. { BUILTIN_REGULAR "true" , truecmd },
  9280. { BUILTIN_REGULAR "type" , typecmd },
  9281. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9282. { BUILTIN_REGULAR "umask" , umaskcmd },
  9283. #if ENABLE_ASH_ALIAS
  9284. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9285. #endif
  9286. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9287. { BUILTIN_REGULAR "wait" , waitcmd },
  9288. };
  9289. /* Should match the above table! */
  9290. #define COMMANDCMD (builtintab + \
  9291. /* . : */ 2 + \
  9292. /* [ */ 1 * ENABLE_ASH_TEST + \
  9293. /* [[ */ 1 * BASH_TEST2 + \
  9294. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9295. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9296. /* break cd cddir */ 3)
  9297. #define EVALCMD (COMMANDCMD + \
  9298. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9299. /* continue */ 1 + \
  9300. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9301. 0)
  9302. #define EXECCMD (EVALCMD + \
  9303. /* eval */ 1)
  9304. /*
  9305. * Search the table of builtin commands.
  9306. */
  9307. static int
  9308. pstrcmp1(const void *a, const void *b)
  9309. {
  9310. return strcmp((char*)a, *(char**)b + 1);
  9311. }
  9312. static struct builtincmd *
  9313. find_builtin(const char *name)
  9314. {
  9315. struct builtincmd *bp;
  9316. bp = bsearch(
  9317. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9318. pstrcmp1
  9319. );
  9320. return bp;
  9321. }
  9322. #if EDITING_HAS_get_exe_name
  9323. static const char * FAST_FUNC
  9324. get_builtin_name(int i)
  9325. {
  9326. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9327. }
  9328. #endif
  9329. /*
  9330. * Execute a simple command.
  9331. */
  9332. static void unwindfiles(struct parsefile *stop);
  9333. static int
  9334. isassignment(const char *p)
  9335. {
  9336. const char *q = endofname(p);
  9337. if (p == q)
  9338. return 0;
  9339. return *q == '=';
  9340. }
  9341. static int FAST_FUNC
  9342. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9343. {
  9344. /* Preserve exitstatus of a previous possible redirection
  9345. * as POSIX mandates */
  9346. return back_exitstatus;
  9347. }
  9348. static int
  9349. evalcommand(union node *cmd, int flags)
  9350. {
  9351. static const struct builtincmd null_bltin = {
  9352. BUILTIN_REGULAR "", bltincmd
  9353. };
  9354. struct localvar_list *localvar_stop;
  9355. struct parsefile *file_stop;
  9356. struct redirtab *redir_stop;
  9357. union node *argp;
  9358. struct arglist arglist;
  9359. struct arglist varlist;
  9360. char **argv;
  9361. int argc;
  9362. struct strlist *osp;
  9363. const struct strlist *sp;
  9364. struct cmdentry cmdentry;
  9365. struct job *jp;
  9366. char *lastarg;
  9367. const char *path;
  9368. int spclbltin;
  9369. int cmd_flag;
  9370. int status;
  9371. char **nargv;
  9372. smallint cmd_is_exec;
  9373. int vflags;
  9374. int vlocal;
  9375. errlinno = lineno = cmd->ncmd.linno;
  9376. if (funcline)
  9377. lineno -= funcline - 1;
  9378. /* First expand the arguments. */
  9379. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9380. #if BASH_PROCESS_SUBST
  9381. redir_stop = redirlist;
  9382. #endif
  9383. file_stop = g_parsefile;
  9384. back_exitstatus = 0;
  9385. cmdentry.cmdtype = CMDBUILTIN;
  9386. cmdentry.u.cmd = &null_bltin;
  9387. varlist.lastp = &varlist.list;
  9388. *varlist.lastp = NULL;
  9389. arglist.lastp = &arglist.list;
  9390. *arglist.lastp = NULL;
  9391. cmd_flag = 0;
  9392. cmd_is_exec = 0;
  9393. spclbltin = -1;
  9394. vflags = 0;
  9395. vlocal = 0;
  9396. path = NULL;
  9397. argc = 0;
  9398. argp = cmd->ncmd.args;
  9399. osp = fill_arglist(&arglist, &argp);
  9400. if (osp) {
  9401. int pseudovarflag = 0;
  9402. for (;;) {
  9403. find_command(arglist.list->text, &cmdentry,
  9404. cmd_flag | DO_REGBLTIN, pathval());
  9405. vlocal++;
  9406. /* implement bltin and command here */
  9407. if (cmdentry.cmdtype != CMDBUILTIN)
  9408. break;
  9409. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9410. if (spclbltin < 0) {
  9411. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9412. vlocal = !spclbltin;
  9413. }
  9414. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9415. #if ENABLE_ASH_CMDCMD
  9416. if (cmdentry.u.cmd != COMMANDCMD)
  9417. break;
  9418. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9419. if (!cmd_flag)
  9420. #endif
  9421. break;
  9422. }
  9423. for (; argp; argp = argp->narg.next)
  9424. expandarg(argp, &arglist,
  9425. pseudovarflag &&
  9426. isassignment(argp->narg.text) ?
  9427. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9428. for (sp = arglist.list; sp; sp = sp->next)
  9429. argc++;
  9430. if (cmd_is_exec && argc > 1)
  9431. vflags = VEXPORT;
  9432. }
  9433. localvar_stop = pushlocalvars(vlocal);
  9434. /* Reserve one extra spot at the front for shellexec. */
  9435. nargv = stalloc(sizeof(char *) * (argc + 2));
  9436. argv = ++nargv;
  9437. for (sp = arglist.list; sp; sp = sp->next) {
  9438. TRACE(("evalcommand arg: %s\n", sp->text));
  9439. *nargv++ = sp->text;
  9440. }
  9441. *nargv = NULL;
  9442. lastarg = NULL;
  9443. if (iflag && funcline == 0 && argc > 0)
  9444. lastarg = nargv[-1];
  9445. expredir(cmd->ncmd.redirect);
  9446. #if !BASH_PROCESS_SUBST
  9447. redir_stop = pushredir(cmd->ncmd.redirect);
  9448. #else
  9449. pushredir(cmd->ncmd.redirect);
  9450. #endif
  9451. preverrout_fd = 2;
  9452. if (BASH_XTRACEFD && xflag) {
  9453. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9454. * we do not emulate this. We only use its value.
  9455. */
  9456. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9457. if (xtracefd && is_number(xtracefd))
  9458. preverrout_fd = atoi(xtracefd);
  9459. }
  9460. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9461. if (status) {
  9462. bail:
  9463. exitstatus = status;
  9464. /* We have a redirection error. */
  9465. if (spclbltin > 0)
  9466. raise_exception(EXERROR);
  9467. goto out;
  9468. }
  9469. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9470. struct strlist **spp;
  9471. spp = varlist.lastp;
  9472. expandarg(argp, &varlist, EXP_VARTILDE);
  9473. if (vlocal)
  9474. mklocal((*spp)->text, VEXPORT);
  9475. else
  9476. setvareq((*spp)->text, vflags);
  9477. }
  9478. /* Print the command if xflag is set. */
  9479. if (xflag) {
  9480. const char *pfx = "";
  9481. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9482. sp = varlist.list;
  9483. while (sp) {
  9484. char *varval = sp->text;
  9485. char *eq = strchrnul(varval, '=');
  9486. if (*eq)
  9487. eq++;
  9488. fdprintf(preverrout_fd, "%s%.*s%s",
  9489. pfx,
  9490. (int)(eq - varval), varval,
  9491. maybe_single_quote(eq)
  9492. );
  9493. sp = sp->next;
  9494. pfx = " ";
  9495. }
  9496. sp = arglist.list;
  9497. while (sp) {
  9498. fdprintf(preverrout_fd, "%s%s",
  9499. pfx,
  9500. /* always quote if matches reserved word: */
  9501. findkwd(sp->text)
  9502. ? single_quote(sp->text)
  9503. : maybe_single_quote(sp->text)
  9504. );
  9505. sp = sp->next;
  9506. pfx = " ";
  9507. }
  9508. safe_write(preverrout_fd, "\n", 1);
  9509. }
  9510. /* Now locate the command. */
  9511. if (cmdentry.cmdtype != CMDBUILTIN
  9512. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9513. ) {
  9514. path = path ? path : pathval();
  9515. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9516. }
  9517. jp = NULL;
  9518. /* Execute the command. */
  9519. switch (cmdentry.cmdtype) {
  9520. case CMDUNKNOWN:
  9521. status = 127;
  9522. flush_stdout_stderr();
  9523. goto bail;
  9524. default: {
  9525. #if ENABLE_FEATURE_SH_STANDALONE \
  9526. && ENABLE_FEATURE_SH_NOFORK \
  9527. && NUM_APPLETS > 1
  9528. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9529. * around run_nofork_applet() call.
  9530. * (2) Should this check also be done in forkshell()?
  9531. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9532. */
  9533. /* find_command() encodes applet_no as (-2 - applet_no) */
  9534. int applet_no = (- cmdentry.u.index - 2);
  9535. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9536. char **sv_environ;
  9537. INT_OFF;
  9538. sv_environ = environ;
  9539. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9540. /*
  9541. * Run <applet>_main().
  9542. * Signals (^C) can't interrupt here.
  9543. * Otherwise we can mangle stdio or malloc internal state.
  9544. * This makes applets which can run for a long time
  9545. * and/or wait for user input ineligible for NOFORK:
  9546. * for example, "yes" or "rm" (rm -i waits for input).
  9547. */
  9548. exitstatus = run_nofork_applet(applet_no, argv);
  9549. environ = sv_environ;
  9550. /*
  9551. * Try enabling NOFORK for "yes" applet.
  9552. * ^C _will_ stop it (write returns EINTR),
  9553. * but this causes stdout FILE to be stuck
  9554. * and needing clearerr(). What if other applets
  9555. * also can get EINTRs? Do we need to switch
  9556. * our signals to SA_RESTART?
  9557. */
  9558. /*clearerr(stdout);*/
  9559. INT_ON;
  9560. break;
  9561. }
  9562. #endif
  9563. /* Can we avoid forking? For example, very last command
  9564. * in a script or a subshell does not need forking,
  9565. * we can just exec it.
  9566. */
  9567. if (!(flags & EV_EXIT) || may_have_traps) {
  9568. /* No, forking off a child is necessary */
  9569. INT_OFF;
  9570. get_tty_state();
  9571. jp = makejob(/*cmd,*/ 1);
  9572. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9573. /* parent */
  9574. break;
  9575. }
  9576. /* child */
  9577. FORCE_INT_ON;
  9578. /* fall through to exec'ing external program */
  9579. }
  9580. shellexec(argv[0], argv, path, cmdentry.u.index);
  9581. /* NOTREACHED */
  9582. } /* default */
  9583. case CMDBUILTIN:
  9584. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9585. && !(exception_type == EXERROR && spclbltin <= 0)
  9586. ) {
  9587. raise:
  9588. longjmp(exception_handler->loc, 1);
  9589. }
  9590. break;
  9591. case CMDFUNCTION:
  9592. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9593. goto raise;
  9594. break;
  9595. } /* switch */
  9596. status = waitforjob(jp);
  9597. if (jp)
  9598. TRACE(("forked child exited with %d\n", status));
  9599. FORCE_INT_ON;
  9600. out:
  9601. if (cmd->ncmd.redirect)
  9602. popredir(/*drop:*/ cmd_is_exec);
  9603. unwindredir(redir_stop);
  9604. unwindfiles(file_stop);
  9605. unwindlocalvars(localvar_stop);
  9606. if (lastarg) {
  9607. /* dsl: I think this is intended to be used to support
  9608. * '_' in 'vi' command mode during line editing...
  9609. * However I implemented that within libedit itself.
  9610. */
  9611. setvar0("_", lastarg);
  9612. }
  9613. return status;
  9614. }
  9615. static int
  9616. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9617. {
  9618. char *volatile savecmdname;
  9619. struct jmploc *volatile savehandler;
  9620. struct jmploc jmploc;
  9621. int status;
  9622. int i;
  9623. savecmdname = commandname;
  9624. savehandler = exception_handler;
  9625. i = setjmp(jmploc.loc);
  9626. if (i)
  9627. goto cmddone;
  9628. exception_handler = &jmploc;
  9629. commandname = argv[0];
  9630. argptr = argv + 1;
  9631. optptr = NULL; /* initialize nextopt */
  9632. if (cmd == EVALCMD)
  9633. status = evalcmd(argc, argv, flags);
  9634. else
  9635. status = (*cmd->builtin)(argc, argv);
  9636. flush_stdout_stderr();
  9637. status |= ferror(stdout);
  9638. exitstatus = status;
  9639. cmddone:
  9640. clearerr(stdout);
  9641. commandname = savecmdname;
  9642. exception_handler = savehandler;
  9643. return i;
  9644. }
  9645. static int
  9646. goodname(const char *p)
  9647. {
  9648. return endofname(p)[0] == '\0';
  9649. }
  9650. /*
  9651. * Search for a command. This is called before we fork so that the
  9652. * location of the command will be available in the parent as well as
  9653. * the child. The check for "goodname" is an overly conservative
  9654. * check that the name will not be subject to expansion.
  9655. */
  9656. static void
  9657. prehash(union node *n)
  9658. {
  9659. struct cmdentry entry;
  9660. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9661. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9662. }
  9663. /* ============ Builtin commands
  9664. *
  9665. * Builtin commands whose functions are closely tied to evaluation
  9666. * are implemented here.
  9667. */
  9668. /*
  9669. * Handle break and continue commands. Break, continue, and return are
  9670. * all handled by setting the evalskip flag. The evaluation routines
  9671. * above all check this flag, and if it is set they start skipping
  9672. * commands rather than executing them. The variable skipcount is
  9673. * the number of loops to break/continue, or the number of function
  9674. * levels to return. (The latter is always 1.) It should probably
  9675. * be an error to break out of more loops than exist, but it isn't
  9676. * in the standard shell so we don't make it one here.
  9677. */
  9678. static int FAST_FUNC
  9679. breakcmd(int argc UNUSED_PARAM, char **argv)
  9680. {
  9681. int n = argv[1] ? number(argv[1]) : 1;
  9682. if (n <= 0)
  9683. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9684. if (n > loopnest)
  9685. n = loopnest;
  9686. if (n > 0) {
  9687. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9688. skipcount = n;
  9689. }
  9690. return 0;
  9691. }
  9692. /*
  9693. * This implements the input routines used by the parser.
  9694. */
  9695. enum {
  9696. INPUT_PUSH_FILE = 1,
  9697. INPUT_NOFILE_OK = 2,
  9698. };
  9699. static smallint checkkwd;
  9700. /* values of checkkwd variable */
  9701. #define CHKALIAS 0x1
  9702. #define CHKKWD 0x2
  9703. #define CHKNL 0x4
  9704. #define CHKEOFMARK 0x8
  9705. /*
  9706. * Push a string back onto the input at this current parsefile level.
  9707. * We handle aliases this way.
  9708. */
  9709. #if !ENABLE_ASH_ALIAS
  9710. #define pushstring(s, ap) pushstring(s)
  9711. #endif
  9712. static void
  9713. pushstring(char *s, struct alias *ap)
  9714. {
  9715. struct strpush *sp;
  9716. int len;
  9717. len = strlen(s);
  9718. INT_OFF;
  9719. if (g_parsefile->strpush) {
  9720. sp = ckzalloc(sizeof(*sp));
  9721. sp->prev = g_parsefile->strpush;
  9722. } else {
  9723. sp = &(g_parsefile->basestrpush);
  9724. }
  9725. g_parsefile->strpush = sp;
  9726. sp->prev_string = g_parsefile->next_to_pgetc;
  9727. sp->prev_left_in_line = g_parsefile->left_in_line;
  9728. sp->unget = g_parsefile->unget;
  9729. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9730. #if ENABLE_ASH_ALIAS
  9731. sp->ap = ap;
  9732. if (ap) {
  9733. ap->flag |= ALIASINUSE;
  9734. sp->string = s;
  9735. }
  9736. #endif
  9737. g_parsefile->next_to_pgetc = s;
  9738. g_parsefile->left_in_line = len;
  9739. g_parsefile->unget = 0;
  9740. INT_ON;
  9741. }
  9742. static void
  9743. popstring(void)
  9744. {
  9745. struct strpush *sp = g_parsefile->strpush;
  9746. INT_OFF;
  9747. #if ENABLE_ASH_ALIAS
  9748. if (sp->ap) {
  9749. if (g_parsefile->next_to_pgetc[-1] == ' '
  9750. || g_parsefile->next_to_pgetc[-1] == '\t'
  9751. ) {
  9752. checkkwd |= CHKALIAS;
  9753. }
  9754. if (sp->string != sp->ap->val) {
  9755. free(sp->string);
  9756. }
  9757. sp->ap->flag &= ~ALIASINUSE;
  9758. if (sp->ap->flag & ALIASDEAD) {
  9759. unalias(sp->ap->name);
  9760. }
  9761. }
  9762. #endif
  9763. g_parsefile->next_to_pgetc = sp->prev_string;
  9764. g_parsefile->left_in_line = sp->prev_left_in_line;
  9765. g_parsefile->unget = sp->unget;
  9766. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9767. g_parsefile->strpush = sp->prev;
  9768. if (sp != &(g_parsefile->basestrpush))
  9769. free(sp);
  9770. INT_ON;
  9771. }
  9772. static int
  9773. preadfd(void)
  9774. {
  9775. int nr;
  9776. char *buf = g_parsefile->buf;
  9777. g_parsefile->next_to_pgetc = buf;
  9778. #if ENABLE_FEATURE_EDITING
  9779. /* retry: */
  9780. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9781. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9782. else {
  9783. # if ENABLE_ASH_IDLE_TIMEOUT
  9784. int timeout = -1;
  9785. const char *tmout_var = lookupvar("TMOUT");
  9786. if (tmout_var) {
  9787. timeout = atoi(tmout_var) * 1000;
  9788. if (timeout <= 0)
  9789. timeout = -1;
  9790. }
  9791. line_input_state->timeout = timeout;
  9792. # endif
  9793. # if ENABLE_FEATURE_TAB_COMPLETION
  9794. line_input_state->path_lookup = pathval();
  9795. # endif
  9796. reinit_unicode_for_ash();
  9797. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9798. if (nr == 0) {
  9799. /* ^C pressed, "convert" to SIGINT */
  9800. write(STDOUT_FILENO, "^C", 2);
  9801. raise(SIGINT);
  9802. if (trap[SIGINT]) {
  9803. buf[0] = '\n';
  9804. buf[1] = '\0';
  9805. return 1;
  9806. }
  9807. exitstatus = 128 + SIGINT;
  9808. return -1;
  9809. }
  9810. if (nr < 0) {
  9811. if (errno == 0) {
  9812. /* Ctrl+D pressed */
  9813. nr = 0;
  9814. }
  9815. # if ENABLE_ASH_IDLE_TIMEOUT
  9816. else if (errno == EAGAIN && timeout > 0) {
  9817. puts("\007timed out waiting for input: auto-logout");
  9818. exitshell();
  9819. }
  9820. # endif
  9821. }
  9822. }
  9823. #else
  9824. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9825. #endif
  9826. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9827. if (nr < 0) {
  9828. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9829. int flags = fcntl(0, F_GETFL);
  9830. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9831. flags &= ~O_NONBLOCK;
  9832. if (fcntl(0, F_SETFL, flags) >= 0) {
  9833. out2str("sh: turning off NDELAY mode\n");
  9834. goto retry;
  9835. }
  9836. }
  9837. }
  9838. }
  9839. #endif
  9840. return nr;
  9841. }
  9842. /*
  9843. * Refill the input buffer and return the next input character:
  9844. *
  9845. * 1) If a string was pushed back on the input, pop it;
  9846. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9847. * or we are reading from a string so we can't refill the buffer,
  9848. * return EOF.
  9849. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9850. * 4) Process input up to the next newline, deleting nul characters.
  9851. */
  9852. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9853. #define pgetc_debug(...) ((void)0)
  9854. static int pgetc(void);
  9855. static int
  9856. preadbuffer(void)
  9857. {
  9858. char *q;
  9859. int more;
  9860. if (g_parsefile->strpush) {
  9861. #if ENABLE_ASH_ALIAS
  9862. if (g_parsefile->left_in_line == -1
  9863. && g_parsefile->strpush->ap
  9864. && g_parsefile->next_to_pgetc[-1] != ' '
  9865. && g_parsefile->next_to_pgetc[-1] != '\t'
  9866. ) {
  9867. pgetc_debug("preadbuffer PEOA");
  9868. return PEOA;
  9869. }
  9870. #endif
  9871. popstring();
  9872. return pgetc();
  9873. }
  9874. /* on both branches above g_parsefile->left_in_line < 0.
  9875. * "pgetc" needs refilling.
  9876. */
  9877. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9878. * pungetc() may increment it a few times.
  9879. * Assuming it won't increment it to less than -90.
  9880. */
  9881. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9882. pgetc_debug("preadbuffer PEOF1");
  9883. /* even in failure keep left_in_line and next_to_pgetc
  9884. * in lock step, for correct multi-layer pungetc.
  9885. * left_in_line was decremented before preadbuffer(),
  9886. * must inc next_to_pgetc: */
  9887. g_parsefile->next_to_pgetc++;
  9888. return PEOF;
  9889. }
  9890. more = g_parsefile->left_in_buffer;
  9891. if (more <= 0) {
  9892. flush_stdout_stderr();
  9893. again:
  9894. more = preadfd();
  9895. if (more <= 0) {
  9896. /* don't try reading again */
  9897. g_parsefile->left_in_line = -99;
  9898. pgetc_debug("preadbuffer PEOF2");
  9899. g_parsefile->next_to_pgetc++;
  9900. return PEOF;
  9901. }
  9902. }
  9903. /* Find out where's the end of line.
  9904. * Set g_parsefile->left_in_line
  9905. * and g_parsefile->left_in_buffer acordingly.
  9906. * NUL chars are deleted.
  9907. */
  9908. q = g_parsefile->next_to_pgetc;
  9909. for (;;) {
  9910. char c;
  9911. more--;
  9912. c = *q;
  9913. if (c == '\0') {
  9914. memmove(q, q + 1, more);
  9915. } else {
  9916. q++;
  9917. if (c == '\n') {
  9918. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9919. break;
  9920. }
  9921. }
  9922. if (more <= 0) {
  9923. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9924. if (g_parsefile->left_in_line < 0)
  9925. goto again;
  9926. break;
  9927. }
  9928. }
  9929. g_parsefile->left_in_buffer = more;
  9930. if (vflag) {
  9931. char save = *q;
  9932. *q = '\0';
  9933. out2str(g_parsefile->next_to_pgetc);
  9934. *q = save;
  9935. }
  9936. pgetc_debug("preadbuffer at %d:%p'%s'",
  9937. g_parsefile->left_in_line,
  9938. g_parsefile->next_to_pgetc,
  9939. g_parsefile->next_to_pgetc);
  9940. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9941. }
  9942. static void
  9943. nlprompt(void)
  9944. {
  9945. g_parsefile->linno++;
  9946. setprompt_if(doprompt, 2);
  9947. }
  9948. static void
  9949. nlnoprompt(void)
  9950. {
  9951. g_parsefile->linno++;
  9952. needprompt = doprompt;
  9953. }
  9954. static int
  9955. pgetc(void)
  9956. {
  9957. int c;
  9958. pgetc_debug("pgetc at %d:%p'%s'",
  9959. g_parsefile->left_in_line,
  9960. g_parsefile->next_to_pgetc,
  9961. g_parsefile->next_to_pgetc);
  9962. if (g_parsefile->unget)
  9963. return g_parsefile->lastc[--g_parsefile->unget];
  9964. if (--g_parsefile->left_in_line >= 0)
  9965. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9966. else
  9967. c = preadbuffer();
  9968. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9969. g_parsefile->lastc[0] = c;
  9970. return c;
  9971. }
  9972. #if ENABLE_ASH_ALIAS
  9973. static int
  9974. pgetc_without_PEOA(void)
  9975. {
  9976. int c;
  9977. do {
  9978. pgetc_debug("pgetc at %d:%p'%s'",
  9979. g_parsefile->left_in_line,
  9980. g_parsefile->next_to_pgetc,
  9981. g_parsefile->next_to_pgetc);
  9982. c = pgetc();
  9983. } while (c == PEOA);
  9984. return c;
  9985. }
  9986. #else
  9987. # define pgetc_without_PEOA() pgetc()
  9988. #endif
  9989. /*
  9990. * Undo a call to pgetc. Only two characters may be pushed back.
  9991. * PEOF may be pushed back.
  9992. */
  9993. static void
  9994. pungetc(void)
  9995. {
  9996. g_parsefile->unget++;
  9997. }
  9998. /* This one eats backslash+newline */
  9999. static int
  10000. pgetc_eatbnl(void)
  10001. {
  10002. int c;
  10003. while ((c = pgetc()) == '\\') {
  10004. if (pgetc() != '\n') {
  10005. pungetc();
  10006. break;
  10007. }
  10008. nlprompt();
  10009. }
  10010. return c;
  10011. }
  10012. struct synstack {
  10013. smalluint syntax;
  10014. uint8_t innerdq :1;
  10015. uint8_t varpushed :1;
  10016. uint8_t dblquote :1;
  10017. int varnest; /* levels of variables expansion */
  10018. int dqvarnest; /* levels of variables expansion within double quotes */
  10019. int parenlevel; /* levels of parens in arithmetic */
  10020. struct synstack *prev;
  10021. struct synstack *next;
  10022. };
  10023. static int
  10024. pgetc_top(struct synstack *stack)
  10025. {
  10026. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  10027. }
  10028. static void
  10029. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  10030. {
  10031. memset(next, 0, sizeof(*next));
  10032. next->syntax = syntax;
  10033. next->next = *stack;
  10034. (*stack)->prev = next;
  10035. *stack = next;
  10036. }
  10037. static ALWAYS_INLINE void
  10038. synstack_pop(struct synstack **stack)
  10039. {
  10040. *stack = (*stack)->next;
  10041. }
  10042. /*
  10043. * To handle the "." command, a stack of input files is used. Pushfile
  10044. * adds a new entry to the stack and popfile restores the previous level.
  10045. */
  10046. static void
  10047. pushfile(void)
  10048. {
  10049. struct parsefile *pf;
  10050. pf = ckzalloc(sizeof(*pf));
  10051. pf->prev = g_parsefile;
  10052. pf->pf_fd = -1;
  10053. /*pf->strpush = NULL; - ckzalloc did it */
  10054. /*pf->basestrpush.prev = NULL;*/
  10055. /*pf->unget = 0;*/
  10056. g_parsefile = pf;
  10057. }
  10058. static void
  10059. popfile(void)
  10060. {
  10061. struct parsefile *pf = g_parsefile;
  10062. if (pf == &basepf)
  10063. return;
  10064. INT_OFF;
  10065. if (pf->pf_fd >= 0)
  10066. close(pf->pf_fd);
  10067. free(pf->buf);
  10068. while (pf->strpush)
  10069. popstring();
  10070. g_parsefile = pf->prev;
  10071. free(pf);
  10072. INT_ON;
  10073. }
  10074. static void
  10075. unwindfiles(struct parsefile *stop)
  10076. {
  10077. while (g_parsefile != stop)
  10078. popfile();
  10079. }
  10080. /*
  10081. * Return to top level.
  10082. */
  10083. static void
  10084. popallfiles(void)
  10085. {
  10086. unwindfiles(&basepf);
  10087. }
  10088. /*
  10089. * Close the file(s) that the shell is reading commands from. Called
  10090. * after a fork is done.
  10091. */
  10092. static void
  10093. closescript(void)
  10094. {
  10095. popallfiles();
  10096. if (g_parsefile->pf_fd > 0) {
  10097. close(g_parsefile->pf_fd);
  10098. g_parsefile->pf_fd = 0;
  10099. }
  10100. }
  10101. /*
  10102. * Like setinputfile, but takes an open file descriptor. Call this with
  10103. * interrupts off.
  10104. */
  10105. static void
  10106. setinputfd(int fd, int push)
  10107. {
  10108. if (push) {
  10109. pushfile();
  10110. g_parsefile->buf = NULL;
  10111. }
  10112. g_parsefile->pf_fd = fd;
  10113. if (g_parsefile->buf == NULL)
  10114. g_parsefile->buf = ckmalloc(IBUFSIZ);
  10115. g_parsefile->left_in_buffer = 0;
  10116. g_parsefile->left_in_line = 0;
  10117. g_parsefile->linno = 1;
  10118. }
  10119. /*
  10120. * Set the input to take input from a file. If push is set, push the
  10121. * old input onto the stack first.
  10122. */
  10123. static int
  10124. setinputfile(const char *fname, int flags)
  10125. {
  10126. int fd;
  10127. INT_OFF;
  10128. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10129. if (fd < 0) {
  10130. if (flags & INPUT_NOFILE_OK)
  10131. goto out;
  10132. exitstatus = 127;
  10133. ash_msg_and_raise_perror("can't open '%s'", fname);
  10134. }
  10135. if (fd < 10)
  10136. fd = savefd(fd);
  10137. else if (O_CLOEXEC == 0) /* old libc */
  10138. close_on_exec_on(fd);
  10139. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10140. out:
  10141. INT_ON;
  10142. return fd;
  10143. }
  10144. /*
  10145. * Like setinputfile, but takes input from a string.
  10146. */
  10147. static void
  10148. setinputstring(char *string)
  10149. {
  10150. INT_OFF;
  10151. pushfile();
  10152. g_parsefile->next_to_pgetc = string;
  10153. g_parsefile->left_in_line = strlen(string);
  10154. g_parsefile->buf = NULL;
  10155. g_parsefile->linno = 1;
  10156. INT_ON;
  10157. }
  10158. /*
  10159. * Routines to check for mail.
  10160. */
  10161. #if ENABLE_ASH_MAIL
  10162. /* Hash of mtimes of mailboxes */
  10163. static unsigned mailtime_hash;
  10164. /* Set if MAIL or MAILPATH is changed. */
  10165. static smallint mail_var_path_changed;
  10166. /*
  10167. * Print appropriate message(s) if mail has arrived.
  10168. * If mail_var_path_changed is set,
  10169. * then the value of MAIL has mail_var_path_changed,
  10170. * so we just update the values.
  10171. */
  10172. static void
  10173. chkmail(void)
  10174. {
  10175. const char *mpath;
  10176. char *p;
  10177. char *q;
  10178. unsigned new_hash;
  10179. struct stackmark smark;
  10180. struct stat statb;
  10181. setstackmark(&smark);
  10182. mpath = mpathset() ? mpathval() : mailval();
  10183. new_hash = 0;
  10184. for (;;) {
  10185. int len;
  10186. len = padvance_magic(&mpath, nullstr, 2);
  10187. if (!len)
  10188. break;
  10189. p = stackblock();
  10190. break;
  10191. if (*p == '\0')
  10192. continue;
  10193. for (q = p; *q; q++)
  10194. continue;
  10195. #if DEBUG
  10196. if (q[-1] != '/')
  10197. abort();
  10198. #endif
  10199. q[-1] = '\0'; /* delete trailing '/' */
  10200. if (stat(p, &statb) < 0) {
  10201. continue;
  10202. }
  10203. /* Very simplistic "hash": just a sum of all mtimes */
  10204. new_hash += (unsigned)statb.st_mtime;
  10205. }
  10206. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10207. if (mailtime_hash != 0)
  10208. out2str("you have mail\n");
  10209. mailtime_hash = new_hash;
  10210. }
  10211. mail_var_path_changed = 0;
  10212. popstackmark(&smark);
  10213. }
  10214. static void FAST_FUNC
  10215. changemail(const char *val UNUSED_PARAM)
  10216. {
  10217. mail_var_path_changed = 1;
  10218. }
  10219. #endif /* ASH_MAIL */
  10220. /* ============ ??? */
  10221. /*
  10222. * Set the shell parameters.
  10223. */
  10224. static void
  10225. setparam(char **argv)
  10226. {
  10227. char **newparam;
  10228. char **ap;
  10229. int nparam;
  10230. for (nparam = 0; argv[nparam]; nparam++)
  10231. continue;
  10232. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10233. while (*argv) {
  10234. *ap++ = ckstrdup(*argv++);
  10235. }
  10236. *ap = NULL;
  10237. freeparam(&shellparam);
  10238. shellparam.malloced = 1;
  10239. shellparam.nparam = nparam;
  10240. shellparam.p = newparam;
  10241. #if ENABLE_ASH_GETOPTS
  10242. shellparam.optind = 1;
  10243. shellparam.optoff = -1;
  10244. #endif
  10245. }
  10246. /*
  10247. * Process shell options. The global variable argptr contains a pointer
  10248. * to the argument list; we advance it past the options.
  10249. *
  10250. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10251. * For a non-interactive shell, an error condition encountered
  10252. * by a special built-in ... shall cause the shell to write a diagnostic message
  10253. * to standard error and exit as shown in the following table:
  10254. * Error Special Built-In
  10255. * ...
  10256. * Utility syntax error (option or operand error) Shall exit
  10257. * ...
  10258. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10259. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10260. * and shell continues), and people rely on this behavior!
  10261. * Testcase:
  10262. * set -o barfoo 2>/dev/null
  10263. * echo $?
  10264. *
  10265. * Oh well. Let's mimic that.
  10266. */
  10267. static int
  10268. plus_minus_o(char *name, int val)
  10269. {
  10270. int i;
  10271. if (name) {
  10272. for (i = 0; i < NOPTS; i++) {
  10273. if (strcmp(name, optnames(i)) == 0) {
  10274. optlist[i] = val;
  10275. return 0;
  10276. }
  10277. }
  10278. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10279. return 1;
  10280. }
  10281. for (i = 0; i < NOPTS; i++) {
  10282. if (optnames(i)[0] == '\0')
  10283. continue;
  10284. if (val) {
  10285. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10286. } else {
  10287. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10288. }
  10289. }
  10290. return 0;
  10291. }
  10292. static void
  10293. setoption(int flag, int val)
  10294. {
  10295. int i;
  10296. for (i = 0; i < NOPTS; i++) {
  10297. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10298. optlist[i] = val;
  10299. return;
  10300. }
  10301. }
  10302. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10303. /* NOTREACHED */
  10304. }
  10305. /* If login_sh is not NULL, we are called to parse command line opts,
  10306. * not "set -opts"
  10307. */
  10308. static int
  10309. options(int *login_sh)
  10310. {
  10311. char *p;
  10312. int val;
  10313. int c;
  10314. if (login_sh)
  10315. minusc = NULL;
  10316. while ((p = *argptr) != NULL) {
  10317. c = *p++;
  10318. if (c != '-' && c != '+')
  10319. break;
  10320. argptr++;
  10321. val = 0; /* val = 0 if c == '+' */
  10322. if (c == '-') {
  10323. val = 1;
  10324. if (p[0] == '\0' || LONE_DASH(p)) {
  10325. if (!login_sh) {
  10326. /* "-" means turn off -x and -v */
  10327. if (p[0] == '\0')
  10328. xflag = vflag = 0;
  10329. /* "--" means reset params */
  10330. else if (*argptr == NULL)
  10331. setparam(argptr);
  10332. }
  10333. break; /* "-" or "--" terminates options */
  10334. }
  10335. }
  10336. /* first char was + or - */
  10337. while ((c = *p++) != '\0') {
  10338. if (login_sh) {
  10339. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10340. if (c == 'c') {
  10341. minusc = p; /* command is after shell args */
  10342. cflag = 1;
  10343. continue;
  10344. }
  10345. if (c == 's') { /* -s, +s */
  10346. sflag = 1;
  10347. continue;
  10348. }
  10349. if (c == 'i') { /* -i, +i */
  10350. iflag = 1;
  10351. continue;
  10352. }
  10353. if (c == 'l') {
  10354. *login_sh = 1; /* -l or +l == --login */
  10355. continue;
  10356. }
  10357. /* bash does not accept +-login, we also won't */
  10358. if (val && (c == '-')) { /* long options */
  10359. if (strcmp(p, "login") == 0) {
  10360. *login_sh = 1;
  10361. }
  10362. break;
  10363. }
  10364. }
  10365. if (c == 'o') {
  10366. if (plus_minus_o(*argptr, val)) {
  10367. /* it already printed err message */
  10368. return 1; /* error */
  10369. }
  10370. if (*argptr)
  10371. argptr++;
  10372. } else {
  10373. setoption(c, val);
  10374. }
  10375. }
  10376. }
  10377. return 0;
  10378. }
  10379. /*
  10380. * The shift builtin command.
  10381. */
  10382. static int FAST_FUNC
  10383. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10384. {
  10385. int n;
  10386. char **ap1, **ap2;
  10387. n = 1;
  10388. if (argv[1])
  10389. n = number(argv[1]);
  10390. if (n > shellparam.nparam)
  10391. return 1;
  10392. INT_OFF;
  10393. shellparam.nparam -= n;
  10394. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10395. if (shellparam.malloced)
  10396. free(*ap1);
  10397. }
  10398. ap2 = shellparam.p;
  10399. while ((*ap2++ = *ap1++) != NULL)
  10400. continue;
  10401. #if ENABLE_ASH_GETOPTS
  10402. shellparam.optind = 1;
  10403. shellparam.optoff = -1;
  10404. #endif
  10405. INT_ON;
  10406. return 0;
  10407. }
  10408. /*
  10409. * POSIX requires that 'set' (but not export or readonly) output the
  10410. * variables in lexicographic order - by the locale's collating order (sigh).
  10411. * Maybe we could keep them in an ordered balanced binary tree
  10412. * instead of hashed lists.
  10413. * For now just roll 'em through qsort for printing...
  10414. */
  10415. static int
  10416. showvars(const char *sep_prefix, int on, int off)
  10417. {
  10418. const char *sep;
  10419. char **ep, **epend;
  10420. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10421. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10422. sep = *sep_prefix ? " " : sep_prefix;
  10423. for (; ep < epend; ep++) {
  10424. const char *p;
  10425. const char *q;
  10426. p = endofname(*ep);
  10427. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10428. * makes "export -p" to have output not suitable for "eval":
  10429. * import os
  10430. * os.environ["test-test"]="test"
  10431. * if os.fork() == 0:
  10432. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10433. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10434. */
  10435. q = nullstr;
  10436. if (*p == '=')
  10437. q = single_quote(++p);
  10438. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10439. }
  10440. return 0;
  10441. }
  10442. /*
  10443. * The set command builtin.
  10444. */
  10445. static int FAST_FUNC
  10446. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10447. {
  10448. int retval;
  10449. if (!argv[1])
  10450. return showvars(nullstr, 0, VUNSET);
  10451. INT_OFF;
  10452. retval = options(/*login_sh:*/ NULL);
  10453. if (retval == 0) { /* if no parse error... */
  10454. optschanged();
  10455. if (*argptr != NULL) {
  10456. setparam(argptr);
  10457. }
  10458. }
  10459. INT_ON;
  10460. return retval;
  10461. }
  10462. #if ENABLE_ASH_RANDOM_SUPPORT
  10463. static void FAST_FUNC
  10464. change_random(const char *value)
  10465. {
  10466. uint32_t t;
  10467. if (value == NULL) {
  10468. /* "get", generate */
  10469. t = next_random(&random_gen);
  10470. /* set without recursion */
  10471. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10472. vrandom.flags &= ~VNOFUNC;
  10473. } else {
  10474. /* set/reset */
  10475. t = strtoul(value, NULL, 10);
  10476. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10477. }
  10478. }
  10479. #endif
  10480. #if BASH_EPOCH_VARS
  10481. static void FAST_FUNC
  10482. change_epoch(struct var *vepoch, const char *fmt)
  10483. {
  10484. struct timeval tv;
  10485. char buffer[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  10486. xgettimeofday(&tv);
  10487. sprintf(buffer, fmt, (unsigned long long)tv.tv_sec, (unsigned)tv.tv_usec);
  10488. setvar(vepoch->var_text, buffer, VNOFUNC);
  10489. vepoch->flags &= ~VNOFUNC;
  10490. }
  10491. static void FAST_FUNC
  10492. change_seconds(const char *value UNUSED_PARAM)
  10493. {
  10494. change_epoch(&vepochs, "%llu");
  10495. }
  10496. static void FAST_FUNC
  10497. change_realtime(const char *value UNUSED_PARAM)
  10498. {
  10499. change_epoch(&vepochr, "%llu.%06u");
  10500. }
  10501. #endif
  10502. #if ENABLE_ASH_GETOPTS
  10503. static int
  10504. getopts(char *optstr, char *optvar, char **optfirst)
  10505. {
  10506. char *p, *q;
  10507. char c = '?';
  10508. int done = 0;
  10509. char sbuf[2];
  10510. char **optnext;
  10511. int ind = shellparam.optind;
  10512. int off = shellparam.optoff;
  10513. sbuf[1] = '\0';
  10514. shellparam.optind = -1;
  10515. optnext = optfirst + ind - 1;
  10516. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10517. p = NULL;
  10518. else
  10519. p = optnext[-1] + off;
  10520. if (p == NULL || *p == '\0') {
  10521. /* Current word is done, advance */
  10522. p = *optnext;
  10523. if (p == NULL || *p != '-' || *++p == '\0') {
  10524. atend:
  10525. unsetvar("OPTARG");
  10526. p = NULL;
  10527. done = 1;
  10528. goto out;
  10529. }
  10530. optnext++;
  10531. if (LONE_DASH(p)) /* check for "--" */
  10532. goto atend;
  10533. }
  10534. c = *p++;
  10535. for (q = optstr; *q != c;) {
  10536. if (*q == '\0') {
  10537. /* OPTERR is a bashism */
  10538. const char *cp = lookupvar("OPTERR");
  10539. if ((cp && LONE_CHAR(cp, '0'))
  10540. || (optstr[0] == ':')
  10541. ) {
  10542. sbuf[0] = c;
  10543. /*sbuf[1] = '\0'; - already is */
  10544. setvar0("OPTARG", sbuf);
  10545. } else {
  10546. fprintf(stderr, "Illegal option -%c\n", c);
  10547. unsetvar("OPTARG");
  10548. }
  10549. c = '?';
  10550. goto out;
  10551. }
  10552. if (*++q == ':')
  10553. q++;
  10554. }
  10555. if (*++q == ':') {
  10556. if (*p == '\0' && (p = *optnext) == NULL) {
  10557. /* OPTERR is a bashism */
  10558. const char *cp = lookupvar("OPTERR");
  10559. if ((cp && LONE_CHAR(cp, '0'))
  10560. || (optstr[0] == ':')
  10561. ) {
  10562. sbuf[0] = c;
  10563. /*sbuf[1] = '\0'; - already is */
  10564. setvar0("OPTARG", sbuf);
  10565. c = ':';
  10566. } else {
  10567. fprintf(stderr, "No arg for -%c option\n", c);
  10568. unsetvar("OPTARG");
  10569. c = '?';
  10570. }
  10571. goto out;
  10572. }
  10573. if (p == *optnext)
  10574. optnext++;
  10575. setvar0("OPTARG", p);
  10576. p = NULL;
  10577. } else
  10578. setvar0("OPTARG", nullstr);
  10579. out:
  10580. ind = optnext - optfirst + 1;
  10581. setvar("OPTIND", itoa(ind), VNOFUNC);
  10582. sbuf[0] = c;
  10583. /*sbuf[1] = '\0'; - already is */
  10584. setvar0(optvar, sbuf);
  10585. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10586. shellparam.optind = ind;
  10587. return done;
  10588. }
  10589. /*
  10590. * The getopts builtin. Shellparam.optnext points to the next argument
  10591. * to be processed. Shellparam.optptr points to the next character to
  10592. * be processed in the current argument. If shellparam.optnext is NULL,
  10593. * then it's the first time getopts has been called.
  10594. */
  10595. static int FAST_FUNC
  10596. getoptscmd(int argc, char **argv)
  10597. {
  10598. char **optbase;
  10599. if (argc < 3)
  10600. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10601. if (argc == 3) {
  10602. optbase = shellparam.p;
  10603. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10604. shellparam.optind = 1;
  10605. shellparam.optoff = -1;
  10606. }
  10607. } else {
  10608. optbase = &argv[3];
  10609. if ((unsigned)shellparam.optind > argc - 2) {
  10610. shellparam.optind = 1;
  10611. shellparam.optoff = -1;
  10612. }
  10613. }
  10614. return getopts(argv[1], argv[2], optbase);
  10615. }
  10616. #endif /* ASH_GETOPTS */
  10617. /* ============ Shell parser */
  10618. struct heredoc {
  10619. struct heredoc *next; /* next here document in list */
  10620. union node *here; /* redirection node */
  10621. char *eofmark; /* string indicating end of input */
  10622. smallint striptabs; /* if set, strip leading tabs */
  10623. };
  10624. static smallint tokpushback; /* last token pushed back */
  10625. static smallint quoteflag; /* set if (part of) last token was quoted */
  10626. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10627. static struct heredoc *heredoclist; /* list of here documents to read */
  10628. static char *wordtext; /* text of last word returned by readtoken */
  10629. static struct nodelist *backquotelist;
  10630. static union node *redirnode;
  10631. static struct heredoc *heredoc;
  10632. static const char *
  10633. tokname(char *buf, int tok)
  10634. {
  10635. if (tok < TSEMI)
  10636. return tokname_array[tok];
  10637. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10638. return buf;
  10639. }
  10640. /* raise_error_unexpected_syntax:
  10641. * Called when an unexpected token is read during the parse. The argument
  10642. * is the token that is expected, or -1 if more than one type of token can
  10643. * occur at this point.
  10644. */
  10645. static void raise_error_unexpected_syntax(int) NORETURN;
  10646. static void
  10647. raise_error_unexpected_syntax(int token)
  10648. {
  10649. char msg[64];
  10650. char buf[16];
  10651. int l;
  10652. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10653. if (token >= 0)
  10654. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10655. raise_error_syntax(msg);
  10656. /* NOTREACHED */
  10657. }
  10658. /* parsing is heavily cross-recursive, need these forward decls */
  10659. static union node *andor(void);
  10660. static union node *pipeline(void);
  10661. static union node *parse_command(void);
  10662. static void parseheredoc(void);
  10663. static int peektoken(void);
  10664. static int readtoken(void);
  10665. static union node *
  10666. list(int nlflag)
  10667. {
  10668. union node *n1, *n2, *n3;
  10669. int tok;
  10670. n1 = NULL;
  10671. for (;;) {
  10672. switch (readtoken()) {
  10673. case TNL:
  10674. if (!(nlflag & 1))
  10675. break;
  10676. parseheredoc();
  10677. return n1;
  10678. case TEOF:
  10679. if (!n1 && (nlflag & 1))
  10680. n1 = NODE_EOF;
  10681. parseheredoc();
  10682. tokpushback++;
  10683. lasttoken = TEOF;
  10684. return n1;
  10685. }
  10686. tokpushback++;
  10687. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10688. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10689. return n1;
  10690. nlflag |= 2;
  10691. n2 = andor();
  10692. tok = readtoken();
  10693. if (tok == TBACKGND) {
  10694. if (n2->type == NPIPE) {
  10695. n2->npipe.pipe_backgnd = 1;
  10696. } else {
  10697. if (n2->type != NREDIR) {
  10698. n3 = stzalloc(sizeof(struct nredir));
  10699. n3->nredir.n = n2;
  10700. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10701. n2 = n3;
  10702. }
  10703. n2->type = NBACKGND;
  10704. }
  10705. }
  10706. if (n1 == NULL) {
  10707. n1 = n2;
  10708. } else {
  10709. n3 = stzalloc(sizeof(struct nbinary));
  10710. n3->type = NSEMI;
  10711. n3->nbinary.ch1 = n1;
  10712. n3->nbinary.ch2 = n2;
  10713. n1 = n3;
  10714. }
  10715. switch (tok) {
  10716. case TNL:
  10717. case TEOF:
  10718. tokpushback = 1;
  10719. /* fall through */
  10720. case TBACKGND:
  10721. case TSEMI:
  10722. break;
  10723. default:
  10724. if ((nlflag & 1))
  10725. raise_error_unexpected_syntax(-1);
  10726. tokpushback = 1;
  10727. return n1;
  10728. }
  10729. }
  10730. }
  10731. static union node *
  10732. andor(void)
  10733. {
  10734. union node *n1, *n2, *n3;
  10735. int t;
  10736. n1 = pipeline();
  10737. for (;;) {
  10738. t = readtoken();
  10739. if (t == TAND) {
  10740. t = NAND;
  10741. } else if (t == TOR) {
  10742. t = NOR;
  10743. } else {
  10744. tokpushback = 1;
  10745. return n1;
  10746. }
  10747. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10748. n2 = pipeline();
  10749. n3 = stzalloc(sizeof(struct nbinary));
  10750. n3->type = t;
  10751. n3->nbinary.ch1 = n1;
  10752. n3->nbinary.ch2 = n2;
  10753. n1 = n3;
  10754. }
  10755. }
  10756. static union node *
  10757. pipeline(void)
  10758. {
  10759. union node *n1, *n2, *pipenode;
  10760. struct nodelist *lp, *prev;
  10761. int negate;
  10762. negate = 0;
  10763. TRACE(("pipeline: entered\n"));
  10764. if (readtoken() == TNOT) {
  10765. negate = !negate;
  10766. checkkwd = CHKKWD | CHKALIAS;
  10767. } else
  10768. tokpushback = 1;
  10769. n1 = parse_command();
  10770. if (readtoken() == TPIPE) {
  10771. pipenode = stzalloc(sizeof(struct npipe));
  10772. pipenode->type = NPIPE;
  10773. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10774. lp = stzalloc(sizeof(struct nodelist));
  10775. pipenode->npipe.cmdlist = lp;
  10776. lp->n = n1;
  10777. do {
  10778. prev = lp;
  10779. lp = stzalloc(sizeof(struct nodelist));
  10780. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10781. lp->n = parse_command();
  10782. prev->next = lp;
  10783. } while (readtoken() == TPIPE);
  10784. lp->next = NULL;
  10785. n1 = pipenode;
  10786. }
  10787. tokpushback = 1;
  10788. if (negate) {
  10789. n2 = stzalloc(sizeof(struct nnot));
  10790. n2->type = NNOT;
  10791. n2->nnot.com = n1;
  10792. return n2;
  10793. }
  10794. return n1;
  10795. }
  10796. static union node *
  10797. makename(void)
  10798. {
  10799. union node *n;
  10800. n = stzalloc(sizeof(struct narg));
  10801. n->type = NARG;
  10802. /*n->narg.next = NULL; - stzalloc did it */
  10803. n->narg.text = wordtext;
  10804. n->narg.backquote = backquotelist;
  10805. return n;
  10806. }
  10807. static void
  10808. fixredir(union node *n, const char *text, int err)
  10809. {
  10810. int fd;
  10811. TRACE(("Fix redir %s %d\n", text, err));
  10812. if (!err)
  10813. n->ndup.vname = NULL;
  10814. fd = bb_strtou(text, NULL, 10);
  10815. if (!errno && fd >= 0)
  10816. n->ndup.dupfd = fd;
  10817. else if (LONE_DASH(text))
  10818. n->ndup.dupfd = -1;
  10819. else {
  10820. if (err)
  10821. raise_error_syntax("bad fd number");
  10822. n->ndup.vname = makename();
  10823. }
  10824. }
  10825. static void
  10826. parsefname(void)
  10827. {
  10828. union node *n = redirnode;
  10829. if (n->type == NHERE)
  10830. checkkwd = CHKEOFMARK;
  10831. if (readtoken() != TWORD)
  10832. raise_error_unexpected_syntax(-1);
  10833. if (n->type == NHERE) {
  10834. struct heredoc *here = heredoc;
  10835. struct heredoc *p;
  10836. if (quoteflag == 0)
  10837. n->type = NXHERE;
  10838. TRACE(("Here document %d\n", n->type));
  10839. rmescapes(wordtext, 0, NULL);
  10840. here->eofmark = wordtext;
  10841. here->next = NULL;
  10842. if (heredoclist == NULL)
  10843. heredoclist = here;
  10844. else {
  10845. for (p = heredoclist; p->next; p = p->next)
  10846. continue;
  10847. p->next = here;
  10848. }
  10849. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10850. fixredir(n, wordtext, 0);
  10851. } else {
  10852. n->nfile.fname = makename();
  10853. }
  10854. }
  10855. static union node *
  10856. simplecmd(void)
  10857. {
  10858. union node *args, **app;
  10859. union node *n = NULL;
  10860. union node *vars, **vpp;
  10861. union node **rpp, *redir;
  10862. int savecheckkwd;
  10863. int savelinno;
  10864. #if BASH_TEST2
  10865. smallint double_brackets_flag = 0;
  10866. #endif
  10867. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10868. args = NULL;
  10869. app = &args;
  10870. vars = NULL;
  10871. vpp = &vars;
  10872. redir = NULL;
  10873. rpp = &redir;
  10874. savecheckkwd = CHKALIAS;
  10875. savelinno = g_parsefile->linno;
  10876. for (;;) {
  10877. int t;
  10878. checkkwd = savecheckkwd;
  10879. t = readtoken();
  10880. switch (t) {
  10881. #if BASH_FUNCTION
  10882. case TFUNCTION:
  10883. if (peektoken() != TWORD)
  10884. raise_error_unexpected_syntax(TWORD);
  10885. function_flag = 1;
  10886. break;
  10887. #endif
  10888. #if BASH_TEST2
  10889. case TAND: /* "&&" */
  10890. case TOR: /* "||" */
  10891. if (!double_brackets_flag) {
  10892. tokpushback = 1;
  10893. goto out;
  10894. }
  10895. /* pass "&&" or "||" to [[ ]] as literal args */
  10896. wordtext = (char *) (t == TAND ? "&&" : "||");
  10897. #endif
  10898. case TWORD:
  10899. n = stzalloc(sizeof(struct narg));
  10900. n->type = NARG;
  10901. /*n->narg.next = NULL; - stzalloc did it */
  10902. n->narg.text = wordtext;
  10903. #if BASH_TEST2
  10904. if (strcmp("[[", wordtext) == 0)
  10905. double_brackets_flag = 1;
  10906. else if (strcmp("]]", wordtext) == 0)
  10907. double_brackets_flag = 0;
  10908. #endif
  10909. n->narg.backquote = backquotelist;
  10910. if (savecheckkwd && isassignment(wordtext)) {
  10911. *vpp = n;
  10912. vpp = &n->narg.next;
  10913. } else {
  10914. *app = n;
  10915. app = &n->narg.next;
  10916. savecheckkwd = 0;
  10917. }
  10918. #if BASH_FUNCTION
  10919. if (function_flag) {
  10920. checkkwd = CHKNL | CHKKWD;
  10921. switch (peektoken()) {
  10922. case TBEGIN:
  10923. case TIF:
  10924. case TCASE:
  10925. case TUNTIL:
  10926. case TWHILE:
  10927. case TFOR:
  10928. goto do_func;
  10929. case TLP:
  10930. function_flag = 0;
  10931. break;
  10932. # if BASH_TEST2
  10933. case TWORD:
  10934. if (strcmp("[[", wordtext) == 0)
  10935. goto do_func;
  10936. /* fall through */
  10937. # endif
  10938. default:
  10939. raise_error_unexpected_syntax(-1);
  10940. }
  10941. }
  10942. #endif
  10943. break;
  10944. case TREDIR:
  10945. *rpp = n = redirnode;
  10946. rpp = &n->nfile.next;
  10947. parsefname(); /* read name of redirection file */
  10948. break;
  10949. case TLP:
  10950. IF_BASH_FUNCTION(do_func:)
  10951. if (args && app == &args->narg.next
  10952. && !vars && !redir
  10953. ) {
  10954. struct builtincmd *bcmd;
  10955. const char *name;
  10956. /* We have a function */
  10957. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10958. raise_error_unexpected_syntax(TRP);
  10959. name = n->narg.text;
  10960. if (!goodname(name)
  10961. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10962. ) {
  10963. raise_error_syntax("bad function name");
  10964. }
  10965. n->type = NDEFUN;
  10966. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10967. n->ndefun.text = n->narg.text;
  10968. n->ndefun.linno = g_parsefile->linno;
  10969. n->ndefun.body = parse_command();
  10970. return n;
  10971. }
  10972. IF_BASH_FUNCTION(function_flag = 0;)
  10973. /* fall through */
  10974. default:
  10975. tokpushback = 1;
  10976. goto out;
  10977. }
  10978. }
  10979. out:
  10980. *app = NULL;
  10981. *vpp = NULL;
  10982. *rpp = NULL;
  10983. n = stzalloc(sizeof(struct ncmd));
  10984. if (NCMD != 0)
  10985. n->type = NCMD;
  10986. n->ncmd.linno = savelinno;
  10987. n->ncmd.args = args;
  10988. n->ncmd.assign = vars;
  10989. n->ncmd.redirect = redir;
  10990. return n;
  10991. }
  10992. static union node *
  10993. parse_command(void)
  10994. {
  10995. union node *n1, *n2;
  10996. union node *ap, **app;
  10997. union node *cp, **cpp;
  10998. union node *redir, **rpp;
  10999. union node **rpp2;
  11000. int t;
  11001. int savelinno;
  11002. redir = NULL;
  11003. rpp2 = &redir;
  11004. savelinno = g_parsefile->linno;
  11005. switch (readtoken()) {
  11006. default:
  11007. raise_error_unexpected_syntax(-1);
  11008. /* NOTREACHED */
  11009. case TIF:
  11010. n1 = stzalloc(sizeof(struct nif));
  11011. n1->type = NIF;
  11012. n1->nif.test = list(0);
  11013. if (readtoken() != TTHEN)
  11014. raise_error_unexpected_syntax(TTHEN);
  11015. n1->nif.ifpart = list(0);
  11016. n2 = n1;
  11017. while (readtoken() == TELIF) {
  11018. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  11019. n2 = n2->nif.elsepart;
  11020. n2->type = NIF;
  11021. n2->nif.test = list(0);
  11022. if (readtoken() != TTHEN)
  11023. raise_error_unexpected_syntax(TTHEN);
  11024. n2->nif.ifpart = list(0);
  11025. }
  11026. if (lasttoken == TELSE)
  11027. n2->nif.elsepart = list(0);
  11028. else {
  11029. n2->nif.elsepart = NULL;
  11030. tokpushback = 1;
  11031. }
  11032. t = TFI;
  11033. break;
  11034. case TWHILE:
  11035. case TUNTIL: {
  11036. int got;
  11037. n1 = stzalloc(sizeof(struct nbinary));
  11038. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  11039. n1->nbinary.ch1 = list(0);
  11040. got = readtoken();
  11041. if (got != TDO) {
  11042. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  11043. got == TWORD ? wordtext : ""));
  11044. raise_error_unexpected_syntax(TDO);
  11045. }
  11046. n1->nbinary.ch2 = list(0);
  11047. t = TDONE;
  11048. break;
  11049. }
  11050. case TFOR:
  11051. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  11052. raise_error_syntax("bad for loop variable");
  11053. n1 = stzalloc(sizeof(struct nfor));
  11054. n1->type = NFOR;
  11055. n1->nfor.linno = savelinno;
  11056. n1->nfor.var = wordtext;
  11057. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11058. if (readtoken() == TIN) {
  11059. app = &ap;
  11060. while (readtoken() == TWORD) {
  11061. n2 = stzalloc(sizeof(struct narg));
  11062. n2->type = NARG;
  11063. /*n2->narg.next = NULL; - stzalloc did it */
  11064. n2->narg.text = wordtext;
  11065. n2->narg.backquote = backquotelist;
  11066. *app = n2;
  11067. app = &n2->narg.next;
  11068. }
  11069. *app = NULL;
  11070. n1->nfor.args = ap;
  11071. if (lasttoken != TNL && lasttoken != TSEMI)
  11072. raise_error_unexpected_syntax(-1);
  11073. } else {
  11074. n2 = stzalloc(sizeof(struct narg));
  11075. n2->type = NARG;
  11076. /*n2->narg.next = NULL; - stzalloc did it */
  11077. n2->narg.text = (char *)dolatstr;
  11078. /*n2->narg.backquote = NULL;*/
  11079. n1->nfor.args = n2;
  11080. /*
  11081. * Newline or semicolon here is optional (but note
  11082. * that the original Bourne shell only allowed NL).
  11083. */
  11084. if (lasttoken != TSEMI)
  11085. tokpushback = 1;
  11086. }
  11087. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11088. if (readtoken() != TDO)
  11089. raise_error_unexpected_syntax(TDO);
  11090. n1->nfor.body = list(0);
  11091. t = TDONE;
  11092. break;
  11093. case TCASE:
  11094. n1 = stzalloc(sizeof(struct ncase));
  11095. n1->type = NCASE;
  11096. n1->ncase.linno = savelinno;
  11097. if (readtoken() != TWORD)
  11098. raise_error_unexpected_syntax(TWORD);
  11099. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  11100. n2->type = NARG;
  11101. /*n2->narg.next = NULL; - stzalloc did it */
  11102. n2->narg.text = wordtext;
  11103. n2->narg.backquote = backquotelist;
  11104. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  11105. if (readtoken() != TIN)
  11106. raise_error_unexpected_syntax(TIN);
  11107. cpp = &n1->ncase.cases;
  11108. next_case:
  11109. checkkwd = CHKNL | CHKKWD;
  11110. t = readtoken();
  11111. while (t != TESAC) {
  11112. if (lasttoken == TLP)
  11113. readtoken();
  11114. *cpp = cp = stzalloc(sizeof(struct nclist));
  11115. cp->type = NCLIST;
  11116. app = &cp->nclist.pattern;
  11117. for (;;) {
  11118. *app = ap = stzalloc(sizeof(struct narg));
  11119. ap->type = NARG;
  11120. /*ap->narg.next = NULL; - stzalloc did it */
  11121. ap->narg.text = wordtext;
  11122. ap->narg.backquote = backquotelist;
  11123. if (readtoken() != TPIPE)
  11124. break;
  11125. app = &ap->narg.next;
  11126. readtoken();
  11127. }
  11128. //ap->narg.next = NULL;
  11129. if (lasttoken != TRP)
  11130. raise_error_unexpected_syntax(TRP);
  11131. cp->nclist.body = list(2);
  11132. cpp = &cp->nclist.next;
  11133. checkkwd = CHKNL | CHKKWD;
  11134. t = readtoken();
  11135. if (t != TESAC) {
  11136. if (t != TENDCASE)
  11137. raise_error_unexpected_syntax(TENDCASE);
  11138. goto next_case;
  11139. }
  11140. }
  11141. *cpp = NULL;
  11142. goto redir;
  11143. case TLP:
  11144. n1 = stzalloc(sizeof(struct nredir));
  11145. n1->type = NSUBSHELL;
  11146. n1->nredir.linno = savelinno;
  11147. n1->nredir.n = list(0);
  11148. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11149. t = TRP;
  11150. break;
  11151. case TBEGIN:
  11152. n1 = list(0);
  11153. t = TEND;
  11154. break;
  11155. IF_BASH_FUNCTION(case TFUNCTION:)
  11156. case TWORD:
  11157. case TREDIR:
  11158. tokpushback = 1;
  11159. return simplecmd();
  11160. }
  11161. if (readtoken() != t)
  11162. raise_error_unexpected_syntax(t);
  11163. redir:
  11164. /* Now check for redirection which may follow command */
  11165. checkkwd = CHKKWD | CHKALIAS;
  11166. rpp = rpp2;
  11167. while (readtoken() == TREDIR) {
  11168. *rpp = n2 = redirnode;
  11169. rpp = &n2->nfile.next;
  11170. parsefname();
  11171. }
  11172. tokpushback = 1;
  11173. *rpp = NULL;
  11174. if (redir) {
  11175. if (n1->type != NSUBSHELL) {
  11176. n2 = stzalloc(sizeof(struct nredir));
  11177. n2->type = NREDIR;
  11178. n2->nredir.linno = savelinno;
  11179. n2->nredir.n = n1;
  11180. n1 = n2;
  11181. }
  11182. n1->nredir.redirect = redir;
  11183. }
  11184. return n1;
  11185. }
  11186. #if BASH_DOLLAR_SQUOTE
  11187. static int
  11188. decode_dollar_squote(void)
  11189. {
  11190. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11191. int c, cnt;
  11192. char *p;
  11193. char buf[4];
  11194. c = pgetc();
  11195. p = strchr(C_escapes, c);
  11196. if (p) {
  11197. buf[0] = c;
  11198. p = buf;
  11199. cnt = 3;
  11200. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11201. do {
  11202. c = pgetc();
  11203. *++p = c;
  11204. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11205. pungetc();
  11206. } else if (c == 'x') { /* \xHH */
  11207. do {
  11208. c = pgetc();
  11209. *++p = c;
  11210. } while (isxdigit(c) && --cnt);
  11211. pungetc();
  11212. if (cnt == 3) { /* \x but next char is "bad" */
  11213. c = 'x';
  11214. goto unrecognized;
  11215. }
  11216. } else { /* simple seq like \\ or \t */
  11217. p++;
  11218. }
  11219. *p = '\0';
  11220. p = buf;
  11221. c = bb_process_escape_sequence((void*)&p);
  11222. } else { /* unrecognized "\z": print both chars unless ' or " */
  11223. if (c != '\'' && c != '"') {
  11224. unrecognized:
  11225. c |= 0x100; /* "please encode \, then me" */
  11226. }
  11227. }
  11228. return c;
  11229. }
  11230. #endif
  11231. /* Used by expandstr to get here-doc like behaviour. */
  11232. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11233. static ALWAYS_INLINE int
  11234. realeofmark(const char *eofmark)
  11235. {
  11236. return eofmark && eofmark != FAKEEOFMARK;
  11237. }
  11238. /*
  11239. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11240. * is not NULL, read a here document. In the latter case, eofmark is the
  11241. * word which marks the end of the document and striptabs is true if
  11242. * leading tabs should be stripped from the document. The argument c
  11243. * is the first character of the input token or document.
  11244. *
  11245. * Because C does not have internal subroutines, I have simulated them
  11246. * using goto's to implement the subroutine linkage. The following macros
  11247. * will run code that appears at the end of readtoken1.
  11248. */
  11249. #define CHECKEND() {goto checkend; checkend_return:;}
  11250. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11251. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11252. #define PARSEBACKQOLD() {style = OLD; goto parsebackq; parsebackq_oldreturn:;}
  11253. #define PARSEBACKQNEW() {style = NEW; goto parsebackq; parsebackq_newreturn:;}
  11254. #define PARSEPROCSUB() {style = PSUB; goto parsebackq; parsebackq_psreturn:;}
  11255. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11256. static int
  11257. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11258. {
  11259. /* NB: syntax parameter fits into smallint */
  11260. /* c parameter is an unsigned char or PEOF or PEOA */
  11261. char *out;
  11262. size_t len;
  11263. struct nodelist *bqlist;
  11264. smallint quotef;
  11265. smallint style;
  11266. enum { OLD, NEW, PSUB };
  11267. #define oldstyle (style == OLD)
  11268. smallint pssyntax; /* we are expanding a prompt string */
  11269. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11270. /* syntax stack */
  11271. struct synstack synbase = { };
  11272. struct synstack *synstack = &synbase;
  11273. #if ENABLE_ASH_EXPAND_PRMT
  11274. pssyntax = (syntax == PSSYNTAX);
  11275. if (pssyntax)
  11276. syntax = DQSYNTAX;
  11277. #else
  11278. pssyntax = 0; /* constant */
  11279. #endif
  11280. synstack->syntax = syntax;
  11281. if (syntax == DQSYNTAX)
  11282. synstack->dblquote = 1;
  11283. quotef = 0;
  11284. bqlist = NULL;
  11285. STARTSTACKSTR(out);
  11286. loop:
  11287. /* For each line, until end of word */
  11288. CHECKEND(); /* set c to PEOF if at end of here document */
  11289. for (;;) { /* until end of line or end of word */
  11290. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11291. switch (SIT(c, synstack->syntax)) {
  11292. case CNL: /* '\n' */
  11293. if (synstack->syntax == BASESYNTAX
  11294. && !synstack->varnest
  11295. ) {
  11296. goto endword; /* exit outer loop */
  11297. }
  11298. USTPUTC(c, out);
  11299. nlprompt();
  11300. c = pgetc_top(synstack);
  11301. goto loop; /* continue outer loop */
  11302. case CWORD:
  11303. USTPUTC(c, out);
  11304. break;
  11305. case CCTL:
  11306. #if BASH_DOLLAR_SQUOTE
  11307. if (c == '\\' && bash_dollar_squote) {
  11308. c = decode_dollar_squote();
  11309. if (c == '\0') {
  11310. /* skip $'\000', $'\x00' (like bash) */
  11311. break;
  11312. }
  11313. if (c & 0x100) {
  11314. /* Unknown escape. Encode as '\z' */
  11315. c = (unsigned char)c;
  11316. if (eofmark == NULL || synstack->dblquote)
  11317. USTPUTC(CTLESC, out);
  11318. USTPUTC('\\', out);
  11319. }
  11320. }
  11321. #endif
  11322. if (!eofmark || synstack->dblquote || synstack->varnest)
  11323. USTPUTC(CTLESC, out);
  11324. USTPUTC(c, out);
  11325. break;
  11326. case CBACK: /* backslash */
  11327. c = pgetc_without_PEOA();
  11328. if (c == PEOF) {
  11329. USTPUTC(CTLESC, out);
  11330. USTPUTC('\\', out);
  11331. pungetc();
  11332. } else {
  11333. if (pssyntax && c == '$') {
  11334. USTPUTC(CTLESC, out);
  11335. USTPUTC('\\', out);
  11336. }
  11337. /* Backslash is retained if we are in "str"
  11338. * and next char isn't dquote-special.
  11339. */
  11340. if (synstack->dblquote
  11341. && c != '\\'
  11342. && c != '`'
  11343. && c != '$'
  11344. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11345. && (c != '}' || !synstack->varnest)
  11346. ) {
  11347. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11348. USTPUTC('\\', out);
  11349. }
  11350. USTPUTC(CTLESC, out);
  11351. USTPUTC(c, out);
  11352. quotef = 1;
  11353. }
  11354. break;
  11355. case CSQUOTE:
  11356. synstack->syntax = SQSYNTAX;
  11357. quotemark:
  11358. if (eofmark == NULL) {
  11359. USTPUTC(CTLQUOTEMARK, out);
  11360. }
  11361. break;
  11362. case CDQUOTE:
  11363. synstack->syntax = DQSYNTAX;
  11364. synstack->dblquote = 1;
  11365. toggledq:
  11366. if (synstack->varnest)
  11367. synstack->innerdq ^= 1;
  11368. goto quotemark;
  11369. case CENDQUOTE:
  11370. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11371. if (eofmark != NULL && synstack->varnest == 0) {
  11372. USTPUTC(c, out);
  11373. break;
  11374. }
  11375. if (synstack->dqvarnest == 0) {
  11376. synstack->syntax = BASESYNTAX;
  11377. synstack->dblquote = 0;
  11378. }
  11379. quotef = 1;
  11380. if (c == '"')
  11381. goto toggledq;
  11382. goto quotemark;
  11383. case CVAR: /* '$' */
  11384. PARSESUB(); /* parse substitution */
  11385. break;
  11386. case CENDVAR: /* '}' */
  11387. if (!synstack->innerdq && synstack->varnest > 0) {
  11388. if (!--synstack->varnest && synstack->varpushed)
  11389. synstack_pop(&synstack);
  11390. else if (synstack->dqvarnest > 0)
  11391. synstack->dqvarnest--;
  11392. c = CTLENDVAR;
  11393. }
  11394. USTPUTC(c, out);
  11395. break;
  11396. #if ENABLE_FEATURE_SH_MATH
  11397. case CLP: /* '(' in arithmetic */
  11398. synstack->parenlevel++;
  11399. USTPUTC(c, out);
  11400. break;
  11401. case CRP: /* ')' in arithmetic */
  11402. if (synstack->parenlevel > 0) {
  11403. synstack->parenlevel--;
  11404. } else {
  11405. if (pgetc_eatbnl() == ')') {
  11406. c = CTLENDARI;
  11407. synstack_pop(&synstack);
  11408. } else {
  11409. /*
  11410. * unbalanced parens
  11411. * (don't 2nd guess - no error)
  11412. */
  11413. pungetc();
  11414. }
  11415. }
  11416. USTPUTC(c, out);
  11417. break;
  11418. #endif
  11419. case CBQUOTE: /* '`' */
  11420. if (checkkwd & CHKEOFMARK) {
  11421. quotef = 1;
  11422. USTPUTC('`', out);
  11423. break;
  11424. }
  11425. PARSEBACKQOLD();
  11426. break;
  11427. case CENDFILE:
  11428. goto endword; /* exit outer loop */
  11429. case CIGN:
  11430. break;
  11431. default:
  11432. if (synstack->varnest == 0) {
  11433. #if BASH_REDIR_OUTPUT
  11434. if (c == '&') {
  11435. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11436. if (pgetc() == '>')
  11437. c = 0x100 + '>'; /* flag &> */
  11438. pungetc();
  11439. }
  11440. #endif
  11441. #if BASH_PROCESS_SUBST
  11442. if (c == '<' || c == '>') {
  11443. if (pgetc() == '(') {
  11444. PARSEPROCSUB();
  11445. break;
  11446. }
  11447. pungetc();
  11448. }
  11449. #endif
  11450. goto endword; /* exit outer loop */
  11451. }
  11452. IF_ASH_ALIAS(if (c != PEOA))
  11453. USTPUTC(c, out);
  11454. }
  11455. c = pgetc_top(synstack);
  11456. } /* for (;;) */
  11457. endword:
  11458. #if ENABLE_FEATURE_SH_MATH
  11459. if (synstack->syntax == ARISYNTAX)
  11460. raise_error_syntax("missing '))'");
  11461. #endif
  11462. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11463. raise_error_syntax("unterminated quoted string");
  11464. if (synstack->varnest != 0) {
  11465. /* { */
  11466. raise_error_syntax("missing '}'");
  11467. }
  11468. USTPUTC('\0', out);
  11469. len = out - (char *)stackblock();
  11470. out = stackblock();
  11471. if (eofmark == NULL) {
  11472. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11473. && quotef == 0
  11474. ) {
  11475. if (isdigit_str9(out)) {
  11476. PARSEREDIR(); /* passed as params: out, c */
  11477. lasttoken = TREDIR;
  11478. return lasttoken;
  11479. }
  11480. /* else: non-number X seen, interpret it
  11481. * as "NNNX>file" = "NNNX >file" */
  11482. }
  11483. pungetc();
  11484. }
  11485. quoteflag = quotef;
  11486. backquotelist = bqlist;
  11487. grabstackblock(len);
  11488. wordtext = out;
  11489. lasttoken = TWORD;
  11490. return lasttoken;
  11491. /* end of readtoken routine */
  11492. /*
  11493. * Check to see whether we are at the end of the here document. When this
  11494. * is called, c is set to the first character of the next input line. If
  11495. * we are at the end of the here document, this routine sets the c to PEOF.
  11496. */
  11497. checkend: {
  11498. if (realeofmark(eofmark)) {
  11499. int markloc;
  11500. char *p;
  11501. #if ENABLE_ASH_ALIAS
  11502. if (c == PEOA)
  11503. c = pgetc_without_PEOA();
  11504. #endif
  11505. if (striptabs) {
  11506. while (c == '\t') {
  11507. c = pgetc_without_PEOA();
  11508. }
  11509. }
  11510. markloc = out - (char *)stackblock();
  11511. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11512. if (c != *p)
  11513. goto more_heredoc;
  11514. /* FIXME: fails for backslash-newlined terminator:
  11515. * cat <<EOF
  11516. * ...
  11517. * EO\
  11518. * F
  11519. * (see heredoc_bkslash_newline2.tests)
  11520. */
  11521. c = pgetc_without_PEOA();
  11522. }
  11523. if (c == '\n' || c == PEOF) {
  11524. c = PEOF;
  11525. g_parsefile->linno++;
  11526. needprompt = doprompt;
  11527. } else {
  11528. int len_here;
  11529. more_heredoc:
  11530. p = (char *)stackblock() + markloc + 1;
  11531. len_here = out - p;
  11532. if (len_here) {
  11533. len_here -= (c >= PEOF);
  11534. c = p[-1];
  11535. if (len_here) {
  11536. char *str;
  11537. str = alloca(len_here + 1);
  11538. *(char *)mempcpy(str, p, len_here) = '\0';
  11539. pushstring(str, NULL);
  11540. }
  11541. }
  11542. }
  11543. STADJUST((char *)stackblock() + markloc - out, out);
  11544. }
  11545. goto checkend_return;
  11546. }
  11547. /*
  11548. * Parse a redirection operator. The variable "out" points to a string
  11549. * specifying the fd to be redirected. The variable "c" contains the
  11550. * first character of the redirection operator.
  11551. */
  11552. parseredir: {
  11553. /* out is already checked to be a valid number or "" */
  11554. int fd = (*out == '\0' ? -1 : atoi(out));
  11555. union node *np;
  11556. np = stzalloc(sizeof(struct nfile));
  11557. if (c == '>') {
  11558. np->nfile.fd = 1;
  11559. c = pgetc_eatbnl();
  11560. if (c == '>')
  11561. np->type = NAPPEND;
  11562. else if (c == '|')
  11563. np->type = NCLOBBER;
  11564. else if (c == '&')
  11565. np->type = NTOFD;
  11566. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11567. else {
  11568. np->type = NTO;
  11569. pungetc();
  11570. }
  11571. }
  11572. #if BASH_REDIR_OUTPUT
  11573. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11574. np->nfile.fd = 1;
  11575. pgetc(); /* this is '>', no need to check */
  11576. np->type = NTO2;
  11577. }
  11578. #endif
  11579. else { /* c == '<' */
  11580. /*np->nfile.fd = 0; - stzalloc did it */
  11581. c = pgetc_eatbnl();
  11582. switch (c) {
  11583. case '<':
  11584. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11585. np = stzalloc(sizeof(struct nhere));
  11586. /*np->nfile.fd = 0; - stzalloc did it */
  11587. }
  11588. np->type = NHERE;
  11589. heredoc = stzalloc(sizeof(struct heredoc));
  11590. heredoc->here = np;
  11591. c = pgetc_eatbnl();
  11592. if (c == '-') {
  11593. heredoc->striptabs = 1;
  11594. } else {
  11595. /*heredoc->striptabs = 0; - stzalloc did it */
  11596. pungetc();
  11597. }
  11598. break;
  11599. case '&':
  11600. np->type = NFROMFD;
  11601. break;
  11602. case '>':
  11603. np->type = NFROMTO;
  11604. break;
  11605. default:
  11606. np->type = NFROM;
  11607. pungetc();
  11608. break;
  11609. }
  11610. }
  11611. if (fd >= 0)
  11612. np->nfile.fd = fd;
  11613. redirnode = np;
  11614. goto parseredir_return;
  11615. }
  11616. /*
  11617. * Parse a substitution. At this point, we have read the dollar sign
  11618. * and nothing else.
  11619. */
  11620. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11621. * (assuming ascii char codes, as the original implementation did) */
  11622. #define is_special(c) \
  11623. (((unsigned)(c) - 33 < 32) \
  11624. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11625. parsesub: {
  11626. unsigned char subtype;
  11627. int typeloc;
  11628. c = pgetc_eatbnl();
  11629. if ((checkkwd & CHKEOFMARK)
  11630. || c > 255 /* PEOA or PEOF */
  11631. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11632. ) {
  11633. #if BASH_DOLLAR_SQUOTE
  11634. if (synstack->syntax != DQSYNTAX && c == '\'')
  11635. bash_dollar_squote = 1;
  11636. else
  11637. #endif
  11638. USTPUTC('$', out);
  11639. pungetc();
  11640. } else if (c == '(') {
  11641. /* $(command) or $((arith)) */
  11642. if (pgetc_eatbnl() == '(') {
  11643. #if ENABLE_FEATURE_SH_MATH
  11644. PARSEARITH();
  11645. #else
  11646. raise_error_syntax("support for $((arith)) is disabled");
  11647. #endif
  11648. } else {
  11649. pungetc();
  11650. PARSEBACKQNEW();
  11651. }
  11652. } else {
  11653. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11654. smalluint newsyn = synstack->syntax;
  11655. USTPUTC(CTLVAR, out);
  11656. typeloc = out - (char *)stackblock();
  11657. STADJUST(1, out);
  11658. subtype = VSNORMAL;
  11659. if (c == '{') {
  11660. c = pgetc_eatbnl();
  11661. subtype = 0;
  11662. }
  11663. varname:
  11664. if (is_name(c)) {
  11665. /* $[{[#]]NAME[}] */
  11666. do {
  11667. STPUTC(c, out);
  11668. c = pgetc_eatbnl();
  11669. } while (is_in_name(c));
  11670. } else if (isdigit(c)) {
  11671. /* $[{[#]]NUM[}] */
  11672. do {
  11673. STPUTC(c, out);
  11674. c = pgetc_eatbnl();
  11675. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11676. } else if (c != '}') {
  11677. /* $[{[#]]<specialchar>[}] */
  11678. int cc = c;
  11679. c = pgetc_eatbnl();
  11680. if (!subtype && cc == '#') {
  11681. subtype = VSLENGTH;
  11682. if (c == '_' || isalnum(c))
  11683. goto varname;
  11684. cc = c;
  11685. c = pgetc_eatbnl();
  11686. if (cc == '}' || c != '}') {
  11687. pungetc();
  11688. subtype = 0;
  11689. c = cc;
  11690. cc = '#';
  11691. }
  11692. }
  11693. if (!is_special(cc)) {
  11694. if (subtype == VSLENGTH)
  11695. subtype = 0;
  11696. goto badsub;
  11697. }
  11698. USTPUTC(cc, out);
  11699. } else
  11700. goto badsub;
  11701. if (subtype == 0) {
  11702. static const char types[] ALIGN1 = "}-+?=";
  11703. /* ${VAR...} but not $VAR or ${#VAR} */
  11704. /* c == first char after VAR */
  11705. int cc = c;
  11706. switch (c) {
  11707. case ':':
  11708. c = pgetc_eatbnl();
  11709. #if BASH_SUBSTR
  11710. /* This check is only needed to not misinterpret
  11711. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11712. * constructs.
  11713. */
  11714. if (!strchr(types, c)) {
  11715. subtype = VSSUBSTR;
  11716. pungetc();
  11717. break; /* "goto badsub" is bigger (!) */
  11718. }
  11719. #endif
  11720. subtype = VSNUL;
  11721. /*FALLTHROUGH*/
  11722. default: {
  11723. const char *p = strchr(types, c);
  11724. if (p == NULL)
  11725. break;
  11726. subtype |= p - types + VSNORMAL;
  11727. break;
  11728. }
  11729. case '%':
  11730. case '#':
  11731. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11732. c = pgetc_eatbnl();
  11733. if (c == cc)
  11734. subtype++;
  11735. else
  11736. pungetc();
  11737. newsyn = BASESYNTAX;
  11738. break;
  11739. #if BASH_PATTERN_SUBST
  11740. case '/':
  11741. /* ${v/[/]pattern/repl} */
  11742. //TODO: encode pattern and repl separately.
  11743. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11744. // are broken (should print "ONE")
  11745. subtype = VSREPLACE;
  11746. newsyn = BASESYNTAX;
  11747. c = pgetc_eatbnl();
  11748. if (c != '/')
  11749. goto badsub;
  11750. subtype++; /* VSREPLACEALL */
  11751. break;
  11752. #endif
  11753. }
  11754. } else {
  11755. if (subtype == VSLENGTH && c != '}')
  11756. subtype = 0;
  11757. badsub:
  11758. pungetc();
  11759. }
  11760. if (newsyn == ARISYNTAX)
  11761. newsyn = DQSYNTAX;
  11762. if ((newsyn != synstack->syntax || synstack->innerdq)
  11763. && subtype != VSNORMAL
  11764. ) {
  11765. synstack_push(&synstack,
  11766. synstack->prev ?: alloca(sizeof(*synstack)),
  11767. newsyn);
  11768. synstack->varpushed = 1;
  11769. synstack->dblquote = newsyn != BASESYNTAX;
  11770. }
  11771. ((unsigned char *)stackblock())[typeloc] = subtype;
  11772. if (subtype != VSNORMAL) {
  11773. synstack->varnest++;
  11774. if (synstack->dblquote)
  11775. synstack->dqvarnest++;
  11776. }
  11777. STPUTC('=', out);
  11778. }
  11779. goto parsesub_return;
  11780. }
  11781. /*
  11782. * Called to parse command substitutions. Newstyle is set if the command
  11783. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11784. * list of commands (passed by reference), and savelen is the number of
  11785. * characters on the top of the stack which must be preserved.
  11786. */
  11787. parsebackq: {
  11788. struct nodelist **nlpp;
  11789. union node *n;
  11790. char *str;
  11791. size_t savelen;
  11792. struct heredoc *saveheredoclist;
  11793. smallint saveprompt = 0;
  11794. str = NULL;
  11795. savelen = out - (char *)stackblock();
  11796. if (savelen > 0) {
  11797. /*
  11798. * FIXME: this can allocate very large block on stack and SEGV.
  11799. * Example:
  11800. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11801. * allocates 100kb for every command subst. With about
  11802. * a hundred command substitutions stack overflows.
  11803. * With larger prepended string, SEGV happens sooner.
  11804. */
  11805. str = alloca(savelen);
  11806. memcpy(str, stackblock(), savelen);
  11807. }
  11808. if (oldstyle) {
  11809. /* We must read until the closing backquote, giving special
  11810. * treatment to some slashes, and then push the string and
  11811. * reread it as input, interpreting it normally.
  11812. */
  11813. char *pout;
  11814. size_t psavelen;
  11815. char *pstr;
  11816. STARTSTACKSTR(pout);
  11817. for (;;) {
  11818. int pc;
  11819. setprompt_if(needprompt, 2);
  11820. pc = pgetc_eatbnl();
  11821. switch (pc) {
  11822. case '`':
  11823. goto done;
  11824. case '\\':
  11825. pc = pgetc(); /* not pgetc_eatbnl! */
  11826. if (pc != '\\' && pc != '`' && pc != '$'
  11827. && (!synstack->dblquote || pc != '"')
  11828. ) {
  11829. STPUTC('\\', pout);
  11830. }
  11831. if (pc <= 255 /* not PEOA or PEOF */) {
  11832. break;
  11833. }
  11834. /* fall through */
  11835. case PEOF:
  11836. IF_ASH_ALIAS(case PEOA:)
  11837. raise_error_syntax("EOF in backquote substitution");
  11838. case '\n':
  11839. nlnoprompt();
  11840. break;
  11841. default:
  11842. break;
  11843. }
  11844. STPUTC(pc, pout);
  11845. }
  11846. done:
  11847. STPUTC('\0', pout);
  11848. psavelen = pout - (char *)stackblock();
  11849. if (psavelen > 0) {
  11850. pstr = grabstackstr(pout);
  11851. setinputstring(pstr);
  11852. }
  11853. }
  11854. nlpp = &bqlist;
  11855. while (*nlpp)
  11856. nlpp = &(*nlpp)->next;
  11857. *nlpp = stzalloc(sizeof(**nlpp));
  11858. /* (*nlpp)->next = NULL; - stzalloc did it */
  11859. saveheredoclist = heredoclist;
  11860. heredoclist = NULL;
  11861. if (oldstyle) {
  11862. saveprompt = doprompt;
  11863. doprompt = 0;
  11864. }
  11865. n = list(2);
  11866. if (oldstyle)
  11867. doprompt = saveprompt;
  11868. else {
  11869. if (readtoken() != TRP)
  11870. raise_error_unexpected_syntax(TRP);
  11871. setinputstring(nullstr);
  11872. }
  11873. parseheredoc();
  11874. heredoclist = saveheredoclist;
  11875. (*nlpp)->n = n;
  11876. /* Start reading from old file again. */
  11877. popfile();
  11878. /* Ignore any pushed back tokens left from the backquote parsing. */
  11879. if (oldstyle)
  11880. tokpushback = 0;
  11881. out = growstackto(savelen + 1);
  11882. if (str) {
  11883. memcpy(out, str, savelen);
  11884. STADJUST(savelen, out);
  11885. }
  11886. #if BASH_PROCESS_SUBST
  11887. if (style == PSUB)
  11888. USTPUTC(c == '<' ? CTLFROMPROC : CTLTOPROC, out);
  11889. else
  11890. #endif
  11891. USTPUTC(CTLBACKQ, out);
  11892. if (oldstyle)
  11893. goto parsebackq_oldreturn;
  11894. #if BASH_PROCESS_SUBST
  11895. else if (style == PSUB)
  11896. goto parsebackq_psreturn;
  11897. #endif
  11898. goto parsebackq_newreturn;
  11899. }
  11900. #if ENABLE_FEATURE_SH_MATH
  11901. /*
  11902. * Parse an arithmetic expansion (indicate start of one and set state)
  11903. */
  11904. parsearith: {
  11905. synstack_push(&synstack,
  11906. synstack->prev ?: alloca(sizeof(*synstack)),
  11907. ARISYNTAX);
  11908. synstack->dblquote = 1;
  11909. USTPUTC(CTLARI, out);
  11910. goto parsearith_return;
  11911. }
  11912. #endif
  11913. } /* end of readtoken */
  11914. /*
  11915. * Read the next input token.
  11916. * If the token is a word, we set backquotelist to the list of cmds in
  11917. * backquotes. We set quoteflag to true if any part of the word was
  11918. * quoted.
  11919. * If the token is TREDIR, then we set redirnode to a structure containing
  11920. * the redirection.
  11921. *
  11922. * [Change comment: here documents and internal procedures]
  11923. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11924. * word parsing code into a separate routine. In this case, readtoken
  11925. * doesn't need to have any internal procedures, but parseword does.
  11926. * We could also make parseoperator in essence the main routine, and
  11927. * have parseword (readtoken1?) handle both words and redirection.]
  11928. */
  11929. #define NEW_xxreadtoken
  11930. #ifdef NEW_xxreadtoken
  11931. /* singles must be first! */
  11932. static const char xxreadtoken_chars[7] ALIGN1 = {
  11933. '\n', '(', ')', /* singles */
  11934. '&', '|', ';', /* doubles */
  11935. 0
  11936. };
  11937. #define xxreadtoken_singles 3
  11938. #define xxreadtoken_doubles 3
  11939. static const char xxreadtoken_tokens[] ALIGN1 = {
  11940. TNL, TLP, TRP, /* only single occurrence allowed */
  11941. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11942. TEOF, /* corresponds to trailing nul */
  11943. TAND, TOR, TENDCASE /* if double occurrence */
  11944. };
  11945. static int
  11946. xxreadtoken(void)
  11947. {
  11948. int c;
  11949. if (tokpushback) {
  11950. tokpushback = 0;
  11951. return lasttoken;
  11952. }
  11953. setprompt_if(needprompt, 2);
  11954. for (;;) { /* until token or start of word found */
  11955. c = pgetc_eatbnl();
  11956. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11957. continue;
  11958. if (c == '#') {
  11959. while ((c = pgetc()) != '\n' && c != PEOF)
  11960. continue;
  11961. pungetc();
  11962. } else if (c == '\\') {
  11963. break; /* return readtoken1(...) */
  11964. } else {
  11965. const char *p;
  11966. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11967. if (c != PEOF) {
  11968. if (c == '\n') {
  11969. nlnoprompt();
  11970. }
  11971. p = strchr(xxreadtoken_chars, c);
  11972. if (p == NULL)
  11973. break; /* return readtoken1(...) */
  11974. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11975. int cc = pgetc_eatbnl();
  11976. if (cc == c) { /* double occurrence? */
  11977. p += xxreadtoken_doubles + 1;
  11978. } else {
  11979. pungetc();
  11980. #if BASH_REDIR_OUTPUT
  11981. if (c == '&' && cc == '>') /* &> */
  11982. break; /* return readtoken1(...) */
  11983. #endif
  11984. }
  11985. }
  11986. }
  11987. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11988. return lasttoken;
  11989. }
  11990. } /* for (;;) */
  11991. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11992. }
  11993. #else /* old xxreadtoken */
  11994. #define RETURN(token) return lasttoken = token
  11995. static int
  11996. xxreadtoken(void)
  11997. {
  11998. int c;
  11999. if (tokpushback) {
  12000. tokpushback = 0;
  12001. return lasttoken;
  12002. }
  12003. setprompt_if(needprompt, 2);
  12004. for (;;) { /* until token or start of word found */
  12005. c = pgetc_eatbnl();
  12006. switch (c) {
  12007. case ' ': case '\t':
  12008. IF_ASH_ALIAS(case PEOA:)
  12009. continue;
  12010. case '#':
  12011. while ((c = pgetc()) != '\n' && c != PEOF)
  12012. continue;
  12013. pungetc();
  12014. continue;
  12015. case '\n':
  12016. nlnoprompt();
  12017. RETURN(TNL);
  12018. case PEOF:
  12019. RETURN(TEOF);
  12020. case '&':
  12021. if (pgetc_eatbnl() == '&')
  12022. RETURN(TAND);
  12023. pungetc();
  12024. RETURN(TBACKGND);
  12025. case '|':
  12026. if (pgetc_eatbnl() == '|')
  12027. RETURN(TOR);
  12028. pungetc();
  12029. RETURN(TPIPE);
  12030. case ';':
  12031. if (pgetc_eatbnl() == ';')
  12032. RETURN(TENDCASE);
  12033. pungetc();
  12034. RETURN(TSEMI);
  12035. case '(':
  12036. RETURN(TLP);
  12037. case ')':
  12038. RETURN(TRP);
  12039. }
  12040. break;
  12041. }
  12042. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  12043. #undef RETURN
  12044. }
  12045. #endif /* old xxreadtoken */
  12046. static int
  12047. readtoken(void)
  12048. {
  12049. int t;
  12050. int kwd = checkkwd;
  12051. #if DEBUG
  12052. smallint alreadyseen = tokpushback;
  12053. #endif
  12054. #if ENABLE_ASH_ALIAS
  12055. top:
  12056. #endif
  12057. t = xxreadtoken();
  12058. /*
  12059. * eat newlines
  12060. */
  12061. if (kwd & CHKNL) {
  12062. while (t == TNL) {
  12063. parseheredoc();
  12064. t = xxreadtoken();
  12065. }
  12066. }
  12067. if (t != TWORD || quoteflag) {
  12068. goto out;
  12069. }
  12070. /*
  12071. * check for keywords
  12072. */
  12073. if (kwd & CHKKWD) {
  12074. const char *const *pp;
  12075. pp = findkwd(wordtext);
  12076. if (pp) {
  12077. lasttoken = t = pp - tokname_array;
  12078. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  12079. goto out;
  12080. }
  12081. }
  12082. if (checkkwd & CHKALIAS) {
  12083. #if ENABLE_ASH_ALIAS
  12084. struct alias *ap;
  12085. ap = lookupalias(wordtext, 1);
  12086. if (ap != NULL) {
  12087. if (*ap->val) {
  12088. pushstring(ap->val, ap);
  12089. }
  12090. goto top;
  12091. }
  12092. #endif
  12093. }
  12094. out:
  12095. checkkwd = 0;
  12096. #if DEBUG
  12097. if (!alreadyseen)
  12098. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12099. else
  12100. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  12101. #endif
  12102. return t;
  12103. }
  12104. static int
  12105. peektoken(void)
  12106. {
  12107. int t;
  12108. t = readtoken();
  12109. tokpushback = 1;
  12110. return t;
  12111. }
  12112. /*
  12113. * Read and parse a command. Returns NODE_EOF on end of file.
  12114. * (NULL is a valid parse tree indicating a blank line.)
  12115. */
  12116. static union node *
  12117. parsecmd(int interact)
  12118. {
  12119. tokpushback = 0;
  12120. checkkwd = 0;
  12121. heredoclist = 0;
  12122. doprompt = interact;
  12123. setprompt_if(doprompt, doprompt);
  12124. needprompt = 0;
  12125. return list(1);
  12126. }
  12127. /*
  12128. * Input any here documents.
  12129. */
  12130. static void
  12131. parseheredoc(void)
  12132. {
  12133. struct heredoc *here;
  12134. union node *n;
  12135. here = heredoclist;
  12136. heredoclist = NULL;
  12137. while (here) {
  12138. tokpushback = 0;
  12139. setprompt_if(needprompt, 2);
  12140. if (here->here->type == NHERE)
  12141. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  12142. else
  12143. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  12144. n = stzalloc(sizeof(struct narg));
  12145. n->narg.type = NARG;
  12146. /*n->narg.next = NULL; - stzalloc did it */
  12147. n->narg.text = wordtext;
  12148. n->narg.backquote = backquotelist;
  12149. here->here->nhere.doc = n;
  12150. here = here->next;
  12151. }
  12152. }
  12153. static const char *
  12154. expandstr(const char *ps, int syntax_type)
  12155. {
  12156. union node n;
  12157. int saveprompt;
  12158. struct parsefile *file_stop = g_parsefile;
  12159. volatile int saveint;
  12160. struct jmploc *volatile savehandler = exception_handler;
  12161. struct jmploc jmploc;
  12162. const char *volatile result;
  12163. int err;
  12164. /* XXX Fix (char *) cast. */
  12165. setinputstring((char *)ps);
  12166. saveprompt = doprompt;
  12167. doprompt = 0;
  12168. result = ps;
  12169. SAVE_INT(saveint);
  12170. err = setjmp(jmploc.loc);
  12171. if (err)
  12172. goto out;
  12173. /* readtoken1() might die horribly.
  12174. * Try a prompt with syntactically wrong command:
  12175. * PS1='$(date "+%H:%M:%S) > '
  12176. */
  12177. exception_handler = &jmploc;
  12178. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  12179. n.narg.type = NARG;
  12180. n.narg.next = NULL;
  12181. n.narg.text = wordtext;
  12182. n.narg.backquote = backquotelist;
  12183. /* expandarg() might fail too:
  12184. * PS1='$((123+))'
  12185. */
  12186. expandarg(&n, NULL, EXP_QUOTED);
  12187. result = stackblock();
  12188. out:
  12189. exception_handler = savehandler;
  12190. if (err && exception_type != EXERROR)
  12191. longjmp(exception_handler->loc, 1);
  12192. RESTORE_INT(saveint);
  12193. doprompt = saveprompt;
  12194. /* Try: PS1='`xxx(`' */
  12195. unwindfiles(file_stop);
  12196. return result;
  12197. }
  12198. static inline int
  12199. parser_eof(void)
  12200. {
  12201. return tokpushback && lasttoken == TEOF;
  12202. }
  12203. /*
  12204. * Execute a command or commands contained in a string.
  12205. */
  12206. static int
  12207. evalstring(char *s, int flags)
  12208. {
  12209. struct jmploc *volatile savehandler;
  12210. struct jmploc jmploc;
  12211. int ex;
  12212. union node *n;
  12213. struct stackmark smark;
  12214. int status;
  12215. s = sstrdup(s);
  12216. setinputstring(s);
  12217. setstackmark(&smark);
  12218. status = 0;
  12219. /* On exception inside execution loop, we must popfile().
  12220. * Try interactively:
  12221. * readonly a=a
  12222. * command eval "a=b" # throws "is read only" error
  12223. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12224. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12225. */
  12226. savehandler = exception_handler;
  12227. ex = setjmp(jmploc.loc);
  12228. if (ex)
  12229. goto out;
  12230. exception_handler = &jmploc;
  12231. while ((n = parsecmd(0)) != NODE_EOF) {
  12232. int i;
  12233. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12234. if (n)
  12235. status = i;
  12236. popstackmark(&smark);
  12237. if (evalskip)
  12238. break;
  12239. }
  12240. out:
  12241. popstackmark(&smark);
  12242. popfile();
  12243. stunalloc(s);
  12244. exception_handler = savehandler;
  12245. if (ex)
  12246. longjmp(exception_handler->loc, ex);
  12247. return status;
  12248. }
  12249. /*
  12250. * The eval command.
  12251. */
  12252. static int FAST_FUNC
  12253. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12254. {
  12255. char *p;
  12256. char *concat;
  12257. if (argv[1]) {
  12258. p = argv[1];
  12259. argv += 2;
  12260. if (argv[0]) {
  12261. STARTSTACKSTR(concat);
  12262. for (;;) {
  12263. concat = stack_putstr(p, concat);
  12264. p = *argv++;
  12265. if (p == NULL)
  12266. break;
  12267. STPUTC(' ', concat);
  12268. }
  12269. STPUTC('\0', concat);
  12270. p = grabstackstr(concat);
  12271. }
  12272. return evalstring(p, flags & EV_TESTED);
  12273. }
  12274. return 0;
  12275. }
  12276. /*
  12277. * Read and execute commands.
  12278. * "Top" is nonzero for the top level command loop;
  12279. * it turns on prompting if the shell is interactive.
  12280. */
  12281. static int
  12282. cmdloop(int top)
  12283. {
  12284. union node *n;
  12285. struct stackmark smark;
  12286. int inter;
  12287. int status = 0;
  12288. int numeof = 0;
  12289. TRACE(("cmdloop(%d) called\n", top));
  12290. for (;;) {
  12291. int skip;
  12292. setstackmark(&smark);
  12293. #if JOBS
  12294. if (doing_jobctl)
  12295. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12296. #endif
  12297. inter = 0;
  12298. if (iflag && top) {
  12299. inter++;
  12300. chkmail();
  12301. }
  12302. n = parsecmd(inter);
  12303. #if DEBUG
  12304. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12305. showtree(n);
  12306. #endif
  12307. if (n == NODE_EOF) {
  12308. if (!top || numeof >= 50)
  12309. break;
  12310. if (!stoppedjobs()) {
  12311. if (!Iflag) {
  12312. if (iflag) {
  12313. newline_and_flush(stderr);
  12314. }
  12315. break;
  12316. }
  12317. out2str("\nUse \"exit\" to leave shell.\n");
  12318. }
  12319. numeof++;
  12320. } else if (nflag == 0) {
  12321. int i;
  12322. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12323. job_warning >>= 1;
  12324. numeof = 0;
  12325. i = evaltree(n, 0);
  12326. if (n)
  12327. status = i;
  12328. }
  12329. popstackmark(&smark);
  12330. skip = evalskip;
  12331. if (skip) {
  12332. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12333. break;
  12334. }
  12335. }
  12336. return status;
  12337. }
  12338. /*
  12339. * Take commands from a file. To be compatible we should do a path
  12340. * search for the file, which is necessary to find sub-commands.
  12341. */
  12342. static char *
  12343. find_dot_file(char *basename)
  12344. {
  12345. char *fullname;
  12346. const char *path = pathval();
  12347. struct stat statb;
  12348. int len;
  12349. /* don't try this for absolute or relative paths */
  12350. if (strchr(basename, '/'))
  12351. return basename;
  12352. while ((len = padvance(&path, basename)) >= 0) {
  12353. fullname = stackblock();
  12354. if ((!pathopt || *pathopt == 'f')
  12355. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12356. ) {
  12357. /* This will be freed by the caller. */
  12358. return stalloc(len);
  12359. }
  12360. }
  12361. /* not found in PATH */
  12362. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12363. return basename;
  12364. #else
  12365. ash_msg_and_raise_error("%s: not found", basename);
  12366. /* NOTREACHED */
  12367. #endif
  12368. }
  12369. static int FAST_FUNC
  12370. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12371. {
  12372. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12373. int status = 0;
  12374. char *fullname;
  12375. char **argv;
  12376. char *args_need_save;
  12377. volatile struct shparam saveparam;
  12378. //???
  12379. // struct strlist *sp;
  12380. // for (sp = cmdenviron; sp; sp = sp->next)
  12381. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12382. nextopt(nullstr); /* handle possible "--" */
  12383. argv = argptr;
  12384. if (!argv[0]) {
  12385. /* bash says: "bash: .: filename argument required" */
  12386. return 2; /* bash compat */
  12387. }
  12388. /* This aborts if file isn't found, which is POSIXly correct.
  12389. * bash returns exitcode 1 instead.
  12390. */
  12391. fullname = find_dot_file(argv[0]);
  12392. argv++;
  12393. args_need_save = argv[0];
  12394. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12395. int argc;
  12396. saveparam = shellparam;
  12397. shellparam.malloced = 0;
  12398. argc = 1;
  12399. while (argv[argc])
  12400. argc++;
  12401. shellparam.nparam = argc;
  12402. shellparam.p = argv;
  12403. };
  12404. /* This aborts if file can't be opened, which is POSIXly correct.
  12405. * bash returns exitcode 1 instead.
  12406. */
  12407. setinputfile(fullname, INPUT_PUSH_FILE);
  12408. commandname = fullname;
  12409. status = cmdloop(0);
  12410. popfile();
  12411. if (args_need_save) {
  12412. freeparam(&shellparam);
  12413. shellparam = saveparam;
  12414. };
  12415. return status;
  12416. }
  12417. static int FAST_FUNC
  12418. exitcmd(int argc UNUSED_PARAM, char **argv)
  12419. {
  12420. if (stoppedjobs())
  12421. return 0;
  12422. if (argv[1])
  12423. savestatus = number(argv[1]);
  12424. raise_exception(EXEXIT);
  12425. /* NOTREACHED */
  12426. }
  12427. /*
  12428. * Read a file containing shell functions.
  12429. */
  12430. static void
  12431. readcmdfile(char *name)
  12432. {
  12433. setinputfile(name, INPUT_PUSH_FILE);
  12434. cmdloop(0);
  12435. popfile();
  12436. }
  12437. /* ============ find_command inplementation */
  12438. /*
  12439. * Resolve a command name. If you change this routine, you may have to
  12440. * change the shellexec routine as well.
  12441. */
  12442. static void
  12443. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12444. {
  12445. struct tblentry *cmdp;
  12446. int idx;
  12447. int prev;
  12448. char *fullname;
  12449. struct stat statb;
  12450. int e;
  12451. int updatetbl;
  12452. struct builtincmd *bcmd;
  12453. int len;
  12454. /* If name contains a slash, don't use PATH or hash table */
  12455. if (strchr(name, '/') != NULL) {
  12456. entry->u.index = -1;
  12457. if (act & DO_ABS) {
  12458. while (stat(name, &statb) < 0) {
  12459. #ifdef SYSV
  12460. if (errno == EINTR)
  12461. continue;
  12462. #endif
  12463. entry->cmdtype = CMDUNKNOWN;
  12464. return;
  12465. }
  12466. }
  12467. entry->cmdtype = CMDNORMAL;
  12468. return;
  12469. }
  12470. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12471. updatetbl = (path == pathval());
  12472. if (!updatetbl)
  12473. act |= DO_ALTPATH;
  12474. /* If name is in the table, check answer will be ok */
  12475. cmdp = cmdlookup(name, 0);
  12476. if (cmdp != NULL) {
  12477. int bit;
  12478. switch (cmdp->cmdtype) {
  12479. default:
  12480. #if DEBUG
  12481. abort();
  12482. #endif
  12483. case CMDNORMAL:
  12484. bit = DO_ALTPATH | DO_REGBLTIN;
  12485. break;
  12486. case CMDFUNCTION:
  12487. bit = DO_NOFUNC;
  12488. break;
  12489. case CMDBUILTIN:
  12490. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12491. break;
  12492. }
  12493. if (act & bit) {
  12494. if (act & bit & DO_REGBLTIN)
  12495. goto fail;
  12496. updatetbl = 0;
  12497. cmdp = NULL;
  12498. } else if (cmdp->rehash == 0)
  12499. /* if not invalidated by cd, we're done */
  12500. goto success;
  12501. }
  12502. /* If %builtin not in path, check for builtin next */
  12503. bcmd = find_builtin(name);
  12504. if (bcmd) {
  12505. if (IS_BUILTIN_REGULAR(bcmd))
  12506. goto builtin_success;
  12507. if (act & DO_ALTPATH)
  12508. goto builtin_success;
  12509. if (builtinloc <= 0)
  12510. goto builtin_success;
  12511. }
  12512. if (act & DO_REGBLTIN)
  12513. goto fail;
  12514. #if ENABLE_FEATURE_SH_STANDALONE
  12515. {
  12516. int applet_no = find_applet_by_name(name);
  12517. if (applet_no >= 0) {
  12518. entry->cmdtype = CMDNORMAL;
  12519. entry->u.index = -2 - applet_no;
  12520. return;
  12521. }
  12522. }
  12523. #endif
  12524. /* We have to search path. */
  12525. prev = -1; /* where to start */
  12526. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12527. if (cmdp->cmdtype == CMDBUILTIN)
  12528. prev = builtinloc;
  12529. else
  12530. prev = cmdp->param.index;
  12531. }
  12532. e = ENOENT;
  12533. idx = -1;
  12534. loop:
  12535. while ((len = padvance(&path, name)) >= 0) {
  12536. const char *lpathopt = pathopt;
  12537. fullname = stackblock();
  12538. idx++;
  12539. if (lpathopt) {
  12540. if (*lpathopt == 'b') {
  12541. if (bcmd)
  12542. goto builtin_success;
  12543. continue;
  12544. } else if (!(act & DO_NOFUNC)) {
  12545. /* handled below */
  12546. } else {
  12547. /* ignore unimplemented options */
  12548. continue;
  12549. }
  12550. }
  12551. /* if rehash, don't redo absolute path names */
  12552. if (fullname[0] == '/' && idx <= prev) {
  12553. if (idx < prev)
  12554. continue;
  12555. TRACE(("searchexec \"%s\": no change\n", name));
  12556. goto success;
  12557. }
  12558. while (stat(fullname, &statb) < 0) {
  12559. #ifdef SYSV
  12560. if (errno == EINTR)
  12561. continue;
  12562. #endif
  12563. if (errno != ENOENT && errno != ENOTDIR)
  12564. e = errno;
  12565. goto loop;
  12566. }
  12567. e = EACCES; /* if we fail, this will be the error */
  12568. if (!S_ISREG(statb.st_mode))
  12569. continue;
  12570. if (lpathopt) { /* this is a %func directory */
  12571. stalloc(len);
  12572. /* NB: stalloc will return space pointed by fullname
  12573. * (because we don't have any intervening allocations
  12574. * between stunalloc above and this stalloc) */
  12575. readcmdfile(fullname);
  12576. cmdp = cmdlookup(name, 0);
  12577. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12578. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12579. stunalloc(fullname);
  12580. goto success;
  12581. }
  12582. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12583. if (!updatetbl) {
  12584. entry->cmdtype = CMDNORMAL;
  12585. entry->u.index = idx;
  12586. return;
  12587. }
  12588. INT_OFF;
  12589. cmdp = cmdlookup(name, 1);
  12590. cmdp->cmdtype = CMDNORMAL;
  12591. cmdp->param.index = idx;
  12592. INT_ON;
  12593. goto success;
  12594. }
  12595. /* We failed. If there was an entry for this command, delete it */
  12596. if (cmdp && updatetbl)
  12597. delete_cmd_entry();
  12598. if (act & DO_ERR) {
  12599. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12600. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12601. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12602. char *argv[3];
  12603. argv[0] = (char*) "command_not_found_handle";
  12604. argv[1] = name;
  12605. argv[2] = NULL;
  12606. evalfun(hookp->param.func, 2, argv, 0);
  12607. entry->cmdtype = CMDUNKNOWN;
  12608. return;
  12609. }
  12610. #endif
  12611. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12612. }
  12613. fail:
  12614. entry->cmdtype = CMDUNKNOWN;
  12615. return;
  12616. builtin_success:
  12617. if (!updatetbl) {
  12618. entry->cmdtype = CMDBUILTIN;
  12619. entry->u.cmd = bcmd;
  12620. return;
  12621. }
  12622. INT_OFF;
  12623. cmdp = cmdlookup(name, 1);
  12624. cmdp->cmdtype = CMDBUILTIN;
  12625. cmdp->param.cmd = bcmd;
  12626. INT_ON;
  12627. success:
  12628. cmdp->rehash = 0;
  12629. entry->cmdtype = cmdp->cmdtype;
  12630. entry->u = cmdp->param;
  12631. }
  12632. /*
  12633. * The trap builtin.
  12634. */
  12635. static int FAST_FUNC
  12636. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12637. {
  12638. char *action;
  12639. char **ap;
  12640. int signo, exitcode;
  12641. nextopt(nullstr);
  12642. ap = argptr;
  12643. if (!*ap) {
  12644. for (signo = 0; signo < NSIG; signo++) {
  12645. char *tr = trap_ptr[signo];
  12646. if (tr) {
  12647. /* note: bash adds "SIG", but only if invoked
  12648. * as "bash". If called as "sh", or if set -o posix,
  12649. * then it prints short signal names.
  12650. * We are printing short names: */
  12651. out1fmt("trap -- %s %s\n",
  12652. single_quote(tr),
  12653. get_signame(signo));
  12654. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12655. * In this case, we will exit very soon, no need to free(). */
  12656. /* if (trap_ptr != trap && tp[0]) */
  12657. /* free(tr); */
  12658. }
  12659. }
  12660. /*
  12661. if (trap_ptr != trap) {
  12662. free(trap_ptr);
  12663. trap_ptr = trap;
  12664. }
  12665. */
  12666. return 0;
  12667. }
  12668. /* Why the second check?
  12669. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12670. * In this case, NUM is signal no, not an action.
  12671. */
  12672. action = NULL;
  12673. if (ap[1] && !is_number(ap[0]))
  12674. action = *ap++;
  12675. exitcode = 0;
  12676. while (*ap) {
  12677. signo = get_signum(*ap);
  12678. if (signo < 0) {
  12679. /* Mimic bash message exactly */
  12680. ash_msg("%s: invalid signal specification", *ap);
  12681. exitcode = 1;
  12682. goto next;
  12683. }
  12684. INT_OFF;
  12685. if (action) {
  12686. if (LONE_DASH(action))
  12687. action = NULL;
  12688. else {
  12689. if (action[0]) /* not NULL and not "" and not "-" */
  12690. may_have_traps = 1;
  12691. action = ckstrdup(action);
  12692. }
  12693. }
  12694. free(trap[signo]);
  12695. trap[signo] = action;
  12696. if (signo != 0)
  12697. setsignal(signo);
  12698. INT_ON;
  12699. next:
  12700. ap++;
  12701. }
  12702. return exitcode;
  12703. }
  12704. /* ============ Builtins */
  12705. #if ENABLE_ASH_HELP
  12706. static int FAST_FUNC
  12707. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12708. {
  12709. unsigned col;
  12710. unsigned i;
  12711. out1fmt(
  12712. "Built-in commands:\n"
  12713. "------------------\n");
  12714. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12715. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12716. builtintab[i].name + 1);
  12717. if (col > 60) {
  12718. out1fmt("\n");
  12719. col = 0;
  12720. }
  12721. }
  12722. # if ENABLE_FEATURE_SH_STANDALONE
  12723. {
  12724. const char *a = applet_names;
  12725. while (*a) {
  12726. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12727. if (col > 60) {
  12728. out1fmt("\n");
  12729. col = 0;
  12730. }
  12731. while (*a++ != '\0')
  12732. continue;
  12733. }
  12734. }
  12735. # endif
  12736. newline_and_flush(stdout);
  12737. return EXIT_SUCCESS;
  12738. }
  12739. #endif
  12740. #if MAX_HISTORY
  12741. static int FAST_FUNC
  12742. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12743. {
  12744. show_history(line_input_state);
  12745. return EXIT_SUCCESS;
  12746. }
  12747. #endif
  12748. /*
  12749. * The export and readonly commands.
  12750. */
  12751. static int FAST_FUNC
  12752. exportcmd(int argc UNUSED_PARAM, char **argv)
  12753. {
  12754. struct var *vp;
  12755. char *name;
  12756. const char *p;
  12757. char **aptr;
  12758. char opt;
  12759. int flag;
  12760. int flag_off;
  12761. /* "readonly" in bash accepts, but ignores -n.
  12762. * We do the same: it saves a conditional in nextopt's param.
  12763. */
  12764. flag_off = 0;
  12765. while ((opt = nextopt("np")) != '\0') {
  12766. if (opt == 'n')
  12767. flag_off = VEXPORT;
  12768. }
  12769. flag = VEXPORT;
  12770. if (argv[0][0] == 'r') {
  12771. flag = VREADONLY;
  12772. flag_off = 0; /* readonly ignores -n */
  12773. }
  12774. flag_off = ~flag_off;
  12775. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12776. {
  12777. aptr = argptr;
  12778. name = *aptr;
  12779. if (name) {
  12780. do {
  12781. p = strchr(name, '=');
  12782. if (p != NULL) {
  12783. p++;
  12784. } else {
  12785. vp = *findvar(hashvar(name), name);
  12786. if (vp) {
  12787. vp->flags = ((vp->flags | flag) & flag_off);
  12788. continue;
  12789. }
  12790. }
  12791. setvar(name, p, (flag & flag_off));
  12792. } while ((name = *++aptr) != NULL);
  12793. return 0;
  12794. }
  12795. }
  12796. /* No arguments. Show the list of exported or readonly vars.
  12797. * -n is ignored.
  12798. */
  12799. showvars(argv[0], flag, 0);
  12800. return 0;
  12801. }
  12802. /*
  12803. * Delete a function if it exists.
  12804. */
  12805. static void
  12806. unsetfunc(const char *name)
  12807. {
  12808. struct tblentry *cmdp;
  12809. cmdp = cmdlookup(name, 0);
  12810. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12811. delete_cmd_entry();
  12812. }
  12813. /*
  12814. * The unset builtin command. We unset the function before we unset the
  12815. * variable to allow a function to be unset when there is a readonly variable
  12816. * with the same name.
  12817. */
  12818. static int FAST_FUNC
  12819. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12820. {
  12821. char **ap;
  12822. int i;
  12823. int flag = 0;
  12824. while ((i = nextopt("vf")) != 0) {
  12825. flag = i;
  12826. }
  12827. for (ap = argptr; *ap; ap++) {
  12828. if (flag != 'f') {
  12829. unsetvar(*ap);
  12830. continue;
  12831. }
  12832. if (flag != 'v')
  12833. unsetfunc(*ap);
  12834. }
  12835. return 0;
  12836. }
  12837. static const unsigned char timescmd_str[] ALIGN1 = {
  12838. ' ', offsetof(struct tms, tms_utime),
  12839. '\n', offsetof(struct tms, tms_stime),
  12840. ' ', offsetof(struct tms, tms_cutime),
  12841. '\n', offsetof(struct tms, tms_cstime),
  12842. 0
  12843. };
  12844. static int FAST_FUNC
  12845. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12846. {
  12847. unsigned clk_tck;
  12848. const unsigned char *p;
  12849. struct tms buf;
  12850. clk_tck = bb_clk_tck();
  12851. times(&buf);
  12852. p = timescmd_str;
  12853. do {
  12854. unsigned sec, frac;
  12855. unsigned long t;
  12856. t = *(clock_t *)(((char *) &buf) + p[1]);
  12857. sec = t / clk_tck;
  12858. frac = t % clk_tck;
  12859. out1fmt("%um%u.%03us%c",
  12860. sec / 60, sec % 60,
  12861. (frac * 1000) / clk_tck,
  12862. p[0]);
  12863. p += 2;
  12864. } while (*p);
  12865. return 0;
  12866. }
  12867. #if ENABLE_FEATURE_SH_MATH
  12868. /*
  12869. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12870. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12871. *
  12872. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12873. */
  12874. static int FAST_FUNC
  12875. letcmd(int argc UNUSED_PARAM, char **argv)
  12876. {
  12877. arith_t i;
  12878. argv++;
  12879. if (!*argv)
  12880. ash_msg_and_raise_error("expression expected");
  12881. do {
  12882. i = ash_arith(*argv);
  12883. } while (*++argv);
  12884. return !i;
  12885. }
  12886. #endif
  12887. /*
  12888. * The read builtin. Options:
  12889. * -r Do not interpret '\' specially
  12890. * -s Turn off echo (tty only)
  12891. * -n NCHARS Read NCHARS max
  12892. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12893. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12894. * -u FD Read from given FD instead of fd 0
  12895. * -d DELIM End on DELIM char, not newline
  12896. * This uses unbuffered input, which may be avoidable in some cases.
  12897. * TODO: bash also has:
  12898. * -a ARRAY Read into array[0],[1],etc
  12899. * -e Use line editing (tty only)
  12900. */
  12901. static int FAST_FUNC
  12902. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12903. {
  12904. struct builtin_read_params params;
  12905. const char *r;
  12906. int i;
  12907. memset(&params, 0, sizeof(params));
  12908. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12909. switch (i) {
  12910. case 'p':
  12911. params.opt_p = optionarg;
  12912. break;
  12913. case 'n':
  12914. params.opt_n = optionarg;
  12915. break;
  12916. case 's':
  12917. params.read_flags |= BUILTIN_READ_SILENT;
  12918. break;
  12919. case 't':
  12920. params.opt_t = optionarg;
  12921. break;
  12922. case 'r':
  12923. params.read_flags |= BUILTIN_READ_RAW;
  12924. break;
  12925. case 'u':
  12926. params.opt_u = optionarg;
  12927. break;
  12928. #if BASH_READ_D
  12929. case 'd':
  12930. params.opt_d = optionarg;
  12931. break;
  12932. #endif
  12933. default:
  12934. break;
  12935. }
  12936. }
  12937. if (!ENABLE_ASH_BASH_COMPAT && !argptr) {
  12938. bb_simple_error_msg("read: need variable name");
  12939. return 1;
  12940. }
  12941. params.argv = argptr;
  12942. params.setvar = setvar0;
  12943. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12944. /* "read -s" needs to save/restore termios, can't allow ^C
  12945. * to jump out of it.
  12946. */
  12947. again:
  12948. INT_OFF;
  12949. r = shell_builtin_read(&params);
  12950. INT_ON;
  12951. if ((uintptr_t)r == 1 && errno == EINTR) {
  12952. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12953. * Correct behavior is to not exit "read"
  12954. */
  12955. if (pending_sig == 0)
  12956. goto again;
  12957. }
  12958. if ((uintptr_t)r > 1)
  12959. ash_msg_and_raise_error(r);
  12960. return (uintptr_t)r;
  12961. }
  12962. static int FAST_FUNC
  12963. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12964. {
  12965. static const char permuser[3] ALIGN1 = "ogu";
  12966. mode_t mask;
  12967. int symbolic_mode = 0;
  12968. while (nextopt("S") != '\0') {
  12969. symbolic_mode = 1;
  12970. }
  12971. INT_OFF;
  12972. mask = umask(0);
  12973. umask(mask);
  12974. INT_ON;
  12975. if (*argptr == NULL) {
  12976. if (symbolic_mode) {
  12977. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12978. char *p = buf;
  12979. int i;
  12980. i = 2;
  12981. for (;;) {
  12982. *p++ = ',';
  12983. *p++ = permuser[i];
  12984. *p++ = '=';
  12985. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12986. if (!(mask & 0400)) *p++ = 'r';
  12987. if (!(mask & 0200)) *p++ = 'w';
  12988. if (!(mask & 0100)) *p++ = 'x';
  12989. mask <<= 3;
  12990. if (--i < 0)
  12991. break;
  12992. }
  12993. *p = '\0';
  12994. puts(buf + 1);
  12995. } else {
  12996. out1fmt("%04o\n", mask);
  12997. }
  12998. } else {
  12999. char *modestr = *argptr;
  13000. /* numeric umasks are taken as-is */
  13001. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  13002. if (!isdigit(modestr[0]))
  13003. mask ^= 0777;
  13004. mask = bb_parse_mode(modestr, mask);
  13005. if ((unsigned)mask > 0777) {
  13006. ash_msg_and_raise_error("illegal mode: %s", modestr);
  13007. }
  13008. if (!isdigit(modestr[0]))
  13009. mask ^= 0777;
  13010. umask(mask);
  13011. }
  13012. return 0;
  13013. }
  13014. static int FAST_FUNC
  13015. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  13016. {
  13017. return shell_builtin_ulimit(argv);
  13018. }
  13019. /* ============ main() and helpers */
  13020. /*
  13021. * This routine is called when an error or an interrupt occurs in an
  13022. * interactive shell and control is returned to the main command loop
  13023. * but prior to exitshell.
  13024. */
  13025. static void
  13026. exitreset(void)
  13027. {
  13028. /* from eval.c: */
  13029. if (savestatus >= 0) {
  13030. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  13031. exitstatus = savestatus;
  13032. savestatus = -1;
  13033. }
  13034. evalskip = 0;
  13035. loopnest = 0;
  13036. /* from expand.c: */
  13037. ifsfree();
  13038. /* from redir.c: */
  13039. unwindredir(NULL);
  13040. }
  13041. /*
  13042. * This routine is called when an error or an interrupt occurs in an
  13043. * interactive shell and control is returned to the main command loop.
  13044. * (In dash, this function is auto-generated by build machinery).
  13045. */
  13046. static void
  13047. reset(void)
  13048. {
  13049. /* from input.c: */
  13050. g_parsefile->left_in_buffer = 0;
  13051. g_parsefile->left_in_line = 0; /* clear input buffer */
  13052. g_parsefile->unget = 0;
  13053. popallfiles();
  13054. /* from var.c: */
  13055. unwindlocalvars(NULL);
  13056. }
  13057. /*
  13058. * Called to exit the shell.
  13059. */
  13060. static void
  13061. exitshell(void)
  13062. {
  13063. struct jmploc loc;
  13064. char *p;
  13065. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  13066. save_history(line_input_state); /* may be NULL */
  13067. #endif
  13068. savestatus = exitstatus;
  13069. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  13070. if (setjmp(loc.loc))
  13071. goto out;
  13072. exception_handler = &loc;
  13073. p = trap[0];
  13074. if (p) {
  13075. trap[0] = NULL;
  13076. evalskip = 0;
  13077. evalstring(p, 0);
  13078. evalskip = SKIPFUNCDEF;
  13079. /*free(p); - we'll exit soon */
  13080. }
  13081. out:
  13082. exitreset();
  13083. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  13084. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  13085. */
  13086. setjobctl(0);
  13087. flush_stdout_stderr();
  13088. _exit(exitstatus);
  13089. /* NOTREACHED */
  13090. }
  13091. /* Don't inline: conserve stack of caller from having our locals too */
  13092. static NOINLINE void
  13093. init(void)
  13094. {
  13095. /* we will never free this */
  13096. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  13097. basepf.linno = 1;
  13098. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  13099. setsignal(SIGCHLD);
  13100. {
  13101. char **envp;
  13102. const char *p;
  13103. initvar();
  13104. for (envp = environ; envp && *envp; envp++) {
  13105. /* Used to have
  13106. * p = endofname(*envp);
  13107. * if (p != *envp && *p == '=') {
  13108. * here to weed out badly-named variables, but this breaks
  13109. * scenarios where people do want them passed to children:
  13110. * import os
  13111. * os.environ["test-test"]="test"
  13112. * if os.fork() == 0:
  13113. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  13114. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  13115. */
  13116. if (strchr(*envp, '=')) {
  13117. setvareq(*envp, VEXPORT|VTEXTFIXED);
  13118. }
  13119. }
  13120. setvareq((char*)defifsvar, VTEXTFIXED);
  13121. setvareq((char*)defoptindvar, VTEXTFIXED);
  13122. setvar0("PPID", utoa(getppid()));
  13123. #if BASH_SHLVL_VAR
  13124. p = lookupvar("SHLVL");
  13125. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  13126. #endif
  13127. #if BASH_HOSTNAME_VAR
  13128. if (!lookupvar("HOSTNAME")) {
  13129. struct utsname uts;
  13130. uname(&uts);
  13131. setvar0("HOSTNAME", uts.nodename);
  13132. }
  13133. #endif
  13134. p = lookupvar("PWD");
  13135. if (p) {
  13136. struct stat st1, st2;
  13137. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  13138. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  13139. ) {
  13140. p = NULL;
  13141. }
  13142. }
  13143. setpwd(p, 0);
  13144. }
  13145. }
  13146. //usage:#define ash_trivial_usage
  13147. //usage: "[-il] [-|+Cabefmnuvx] [-|+o OPT]... [-c 'SCRIPT' [ARG0 ARGS] | FILE [ARGS] | -s [ARGS]]"
  13148. //////// comes from ^^^^^^^^^^optletters
  13149. //usage:#define ash_full_usage "\n\n"
  13150. //usage: "Unix shell interpreter"
  13151. /*
  13152. * Process the shell command line arguments.
  13153. */
  13154. static int
  13155. procargs(char **argv)
  13156. {
  13157. int i;
  13158. const char *xminusc;
  13159. char **xargv;
  13160. int login_sh;
  13161. xargv = argv;
  13162. login_sh = xargv[0] && xargv[0][0] == '-';
  13163. #if NUM_SCRIPTS > 0
  13164. if (minusc)
  13165. goto setarg0;
  13166. #endif
  13167. arg0 = xargv[0];
  13168. /* if (xargv[0]) - mmm, this is always true! */
  13169. xargv++;
  13170. argptr = xargv;
  13171. for (i = 0; i < NOPTS; i++)
  13172. optlist[i] = 2;
  13173. if (options(&login_sh)) {
  13174. /* it already printed err message */
  13175. raise_exception(EXERROR);
  13176. }
  13177. xargv = argptr;
  13178. xminusc = minusc;
  13179. if (*xargv == NULL) {
  13180. if (xminusc)
  13181. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13182. sflag = 1;
  13183. }
  13184. if (iflag == 2 /* no explicit -i given */
  13185. && sflag == 1 /* -s given (or implied) */
  13186. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13187. && isatty(0) && isatty(1) /* we are on tty */
  13188. ) {
  13189. iflag = 1;
  13190. }
  13191. if (mflag == 2)
  13192. mflag = iflag;
  13193. /* Unset options which weren't explicitly set or unset */
  13194. for (i = 0; i < NOPTS; i++)
  13195. optlist[i] &= 1; /* same effect as "if (optlist[i] == 2) optlist[i] = 0;" */
  13196. #if DEBUG == 2
  13197. debug = 1;
  13198. #endif
  13199. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13200. if (xminusc) {
  13201. minusc = *xargv++;
  13202. if (*xargv)
  13203. goto setarg0;
  13204. } else if (!sflag) {
  13205. setinputfile(*xargv, 0);
  13206. setarg0:
  13207. arg0 = *xargv++;
  13208. commandname = arg0;
  13209. }
  13210. shellparam.p = xargv;
  13211. #if ENABLE_ASH_GETOPTS
  13212. shellparam.optind = 1;
  13213. shellparam.optoff = -1;
  13214. #endif
  13215. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13216. while (*xargv) {
  13217. shellparam.nparam++;
  13218. xargv++;
  13219. }
  13220. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13221. * Try:
  13222. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13223. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13224. * NB: must do it before setting up signals (in optschanged())
  13225. * and reading .profile etc (after we return from here):
  13226. */
  13227. if (iflag)
  13228. signal(SIGHUP, SIG_DFL);
  13229. optschanged();
  13230. return login_sh;
  13231. }
  13232. /*
  13233. * Read /etc/profile, ~/.profile, $ENV.
  13234. */
  13235. static void
  13236. read_profile(const char *name)
  13237. {
  13238. name = expandstr(name, DQSYNTAX);
  13239. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13240. return;
  13241. cmdloop(0);
  13242. popfile();
  13243. }
  13244. #if PROFILE
  13245. static short profile_buf[16384];
  13246. extern int etext();
  13247. #endif
  13248. /*
  13249. * Main routine. We initialize things, parse the arguments, execute
  13250. * profiles if we're a login shell, and then call cmdloop to execute
  13251. * commands. The setjmp call sets up the location to jump to when an
  13252. * exception occurs. When an exception occurs the variable "state"
  13253. * is used to figure out how far we had gotten.
  13254. */
  13255. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13256. #if NUM_SCRIPTS > 0
  13257. int ash_main(int argc, char **argv)
  13258. #else
  13259. int ash_main(int argc UNUSED_PARAM, char **argv)
  13260. #endif
  13261. /* note: 'argc' is used only if embedded scripts are enabled */
  13262. {
  13263. volatile smallint state;
  13264. struct jmploc jmploc;
  13265. struct stackmark smark;
  13266. int login_sh;
  13267. /* Initialize global data */
  13268. INIT_G_misc();
  13269. INIT_G_memstack();
  13270. INIT_G_var();
  13271. #if ENABLE_ASH_ALIAS
  13272. INIT_G_alias();
  13273. #endif
  13274. INIT_G_cmdtable();
  13275. #if PROFILE
  13276. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13277. #endif
  13278. state = 0;
  13279. if (setjmp(jmploc.loc)) {
  13280. smallint e;
  13281. smallint s;
  13282. exitreset();
  13283. e = exception_type;
  13284. s = state;
  13285. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13286. exitshell();
  13287. }
  13288. reset();
  13289. if (e == EXINT) {
  13290. newline_and_flush(stderr);
  13291. }
  13292. popstackmark(&smark);
  13293. FORCE_INT_ON; /* enable interrupts */
  13294. if (s == 1)
  13295. goto state1;
  13296. if (s == 2)
  13297. goto state2;
  13298. if (s == 3)
  13299. goto state3;
  13300. goto state4;
  13301. }
  13302. exception_handler = &jmploc;
  13303. rootpid = getpid();
  13304. init();
  13305. setstackmark(&smark);
  13306. #if NUM_SCRIPTS > 0
  13307. if (argc < 0)
  13308. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13309. minusc = get_script_content(-argc - 1);
  13310. #endif
  13311. login_sh = procargs(argv);
  13312. #if DEBUG
  13313. TRACE(("Shell args: "));
  13314. trace_puts_args(argv);
  13315. #endif
  13316. if (login_sh) {
  13317. const char *hp;
  13318. state = 1;
  13319. read_profile("/etc/profile");
  13320. state1:
  13321. state = 2;
  13322. hp = lookupvar("HOME");
  13323. if (hp)
  13324. read_profile("$HOME/.profile");
  13325. }
  13326. state2:
  13327. state = 3;
  13328. if (
  13329. #ifndef linux
  13330. getuid() == geteuid() && getgid() == getegid() &&
  13331. #endif
  13332. iflag
  13333. ) {
  13334. const char *shinit = lookupvar("ENV");
  13335. if (shinit != NULL && *shinit != '\0')
  13336. read_profile(shinit);
  13337. }
  13338. popstackmark(&smark);
  13339. state3:
  13340. state = 4;
  13341. if (minusc) {
  13342. /* evalstring pushes parsefile stack.
  13343. * Ensure we don't falsely claim that 0 (stdin)
  13344. * is one of stacked source fds.
  13345. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13346. // if (!sflag) g_parsefile->pf_fd = -1;
  13347. // ^^ not necessary since now we special-case fd 0
  13348. // in save_fd_on_redirect()
  13349. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13350. // The above makes
  13351. // ash -sc 'echo $-'
  13352. // continue reading input from stdin after running 'echo'.
  13353. // bash does not do this: it prints "hBcs" and exits.
  13354. evalstring(minusc, EV_EXIT);
  13355. }
  13356. if (sflag || minusc == NULL) {
  13357. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13358. if (line_input_state) {
  13359. const char *hp = lookupvar("HISTFILE");
  13360. if (!hp) {
  13361. hp = lookupvar("HOME");
  13362. if (hp) {
  13363. INT_OFF;
  13364. hp = concat_path_file(hp, ".ash_history");
  13365. setvar0("HISTFILE", hp);
  13366. free((char*)hp);
  13367. INT_ON;
  13368. hp = lookupvar("HISTFILE");
  13369. }
  13370. }
  13371. if (hp)
  13372. line_input_state->hist_file = xstrdup(hp);
  13373. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13374. hp = lookupvar("HISTFILESIZE");
  13375. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13376. # endif
  13377. }
  13378. #endif
  13379. state4: /* XXX ??? - why isn't this before the "if" statement */
  13380. cmdloop(1);
  13381. }
  13382. #if PROFILE
  13383. monitor(0);
  13384. #endif
  13385. #ifdef GPROF
  13386. {
  13387. extern void _mcleanup(void);
  13388. _mcleanup();
  13389. }
  13390. #endif
  13391. TRACE(("End of main reached\n"));
  13392. exitshell();
  13393. /* NOTREACHED */
  13394. }
  13395. /*-
  13396. * Copyright (c) 1989, 1991, 1993, 1994
  13397. * The Regents of the University of California. All rights reserved.
  13398. *
  13399. * This code is derived from software contributed to Berkeley by
  13400. * Kenneth Almquist.
  13401. *
  13402. * Redistribution and use in source and binary forms, with or without
  13403. * modification, are permitted provided that the following conditions
  13404. * are met:
  13405. * 1. Redistributions of source code must retain the above copyright
  13406. * notice, this list of conditions and the following disclaimer.
  13407. * 2. Redistributions in binary form must reproduce the above copyright
  13408. * notice, this list of conditions and the following disclaimer in the
  13409. * documentation and/or other materials provided with the distribution.
  13410. * 3. Neither the name of the University nor the names of its contributors
  13411. * may be used to endorse or promote products derived from this software
  13412. * without specific prior written permission.
  13413. *
  13414. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13415. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13416. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13417. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13418. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13419. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13420. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13421. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13422. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13423. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13424. * SUCH DAMAGE.
  13425. */