ash.c 326 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569
  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. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  226. /* Bionic at least up to version 24 has no glob() */
  227. # undef ENABLE_ASH_INTERNAL_GLOB
  228. # define ENABLE_ASH_INTERNAL_GLOB 1
  229. #endif
  230. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  231. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  232. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  233. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  234. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  235. # error fails to match dirname, subsequently not expanding <pattern> in it.
  236. // Testcase:
  237. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  238. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  239. #endif
  240. #if !ENABLE_ASH_INTERNAL_GLOB
  241. # include <glob.h>
  242. #endif
  243. #include "unicode.h"
  244. #include "shell_common.h"
  245. #if ENABLE_FEATURE_SH_MATH
  246. # include "math.h"
  247. #else
  248. typedef long arith_t;
  249. # define ARITH_FMT "%ld"
  250. #endif
  251. #if ENABLE_ASH_RANDOM_SUPPORT
  252. # include "random.h"
  253. #else
  254. # define CLEAR_RANDOM_T(rnd) ((void)0)
  255. #endif
  256. #include "NUM_APPLETS.h"
  257. #if NUM_APPLETS == 1
  258. /* STANDALONE does not make sense, and won't compile */
  259. # undef CONFIG_FEATURE_SH_STANDALONE
  260. # undef ENABLE_FEATURE_SH_STANDALONE
  261. # undef IF_FEATURE_SH_STANDALONE
  262. # undef IF_NOT_FEATURE_SH_STANDALONE
  263. # define ENABLE_FEATURE_SH_STANDALONE 0
  264. # define IF_FEATURE_SH_STANDALONE(...)
  265. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  266. #endif
  267. #ifndef F_DUPFD_CLOEXEC
  268. # define F_DUPFD_CLOEXEC F_DUPFD
  269. #endif
  270. #ifndef O_CLOEXEC
  271. # define O_CLOEXEC 0
  272. #endif
  273. #ifndef PIPE_BUF
  274. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  275. #endif
  276. #if !BB_MMU
  277. # error "Do not even bother, ash will not run on NOMMU machine"
  278. #endif
  279. /* We use a trick to have more optimized code (fewer pointer reloads):
  280. * ash.c: extern struct globals *const ash_ptr_to_globals;
  281. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  282. * This way, compiler in ash.c knows the pointer can not change.
  283. *
  284. * However, this may break on weird arches or toolchains. In this case,
  285. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  286. * this optimization.
  287. */
  288. #ifndef BB_GLOBAL_CONST
  289. # define BB_GLOBAL_CONST const
  290. #endif
  291. /* ============ Hash table sizes. Configurable. */
  292. #define VTABSIZE 39
  293. #define ATABSIZE 39
  294. #define CMDTABLESIZE 31 /* should be prime */
  295. /* ============ Shell options */
  296. static const char *const optletters_optnames[] = {
  297. "e" "errexit",
  298. "f" "noglob",
  299. "I" "ignoreeof",
  300. /* The below allowed this invocation:
  301. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  302. * to be ^C-ed and get to interactive ash prompt.
  303. * bash does not support such "set -i".
  304. * In our code, this is denoted by empty long name:
  305. */
  306. "i" "",
  307. "m" "monitor",
  308. "n" "noexec",
  309. /* Ditto: bash has no "set -s" */
  310. "s" "",
  311. "c" "",
  312. "x" "xtrace",
  313. "v" "verbose",
  314. "C" "noclobber",
  315. "a" "allexport",
  316. "b" "notify",
  317. "u" "nounset",
  318. "\0" "vi"
  319. #if BASH_PIPEFAIL
  320. ,"\0" "pipefail"
  321. #endif
  322. #if DEBUG
  323. ,"\0" "nolog"
  324. ,"\0" "debug"
  325. #endif
  326. };
  327. //bash 4.4.23 also has these opts (with these defaults):
  328. //braceexpand on
  329. //emacs on
  330. //errtrace off
  331. //functrace off
  332. //hashall on
  333. //histexpand off
  334. //history on
  335. //interactive-comments on
  336. //keyword off
  337. //onecmd off
  338. //physical off
  339. //posix off
  340. //privileged off
  341. #define optletters(n) optletters_optnames[n][0]
  342. #define optnames(n) (optletters_optnames[n] + 1)
  343. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  344. /* ============ Misc data */
  345. #define msg_illnum "Illegal number: %s"
  346. /*
  347. * We enclose jmp_buf in a structure so that we can declare pointers to
  348. * jump locations. The global variable handler contains the location to
  349. * jump to when an exception occurs, and the global variable exception_type
  350. * contains a code identifying the exception. To implement nested
  351. * exception handlers, the user should save the value of handler on entry
  352. * to an inner scope, set handler to point to a jmploc structure for the
  353. * inner scope, and restore handler on exit from the scope.
  354. */
  355. struct jmploc {
  356. jmp_buf loc;
  357. };
  358. struct globals_misc {
  359. uint8_t exitstatus; /* exit status of last command */
  360. uint8_t back_exitstatus;/* exit status of backquoted command */
  361. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  362. int savestatus; /* exit status of last command outside traps */
  363. int rootpid; /* pid of main shell */
  364. /* shell level: 0 for the main shell, 1 for its children, and so on */
  365. int shlvl;
  366. #define rootshell (!shlvl)
  367. int errlinno;
  368. char *minusc; /* argument to -c option */
  369. char *curdir; // = nullstr; /* current working directory */
  370. char *physdir; // = nullstr; /* physical working directory */
  371. char *arg0; /* value of $0 */
  372. struct jmploc *exception_handler;
  373. volatile int suppress_int; /* counter */
  374. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  375. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  376. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  377. smallint exception_type; /* kind of exception: */
  378. #define EXINT 0 /* SIGINT received */
  379. #define EXERROR 1 /* a generic error */
  380. #define EXEND 3 /* exit the shell */
  381. #define EXEXIT 4 /* exit the shell via exitcmd */
  382. char nullstr[1]; /* zero length string */
  383. char optlist[NOPTS];
  384. #define eflag optlist[0]
  385. #define fflag optlist[1]
  386. #define Iflag optlist[2]
  387. #define iflag optlist[3]
  388. #define mflag optlist[4]
  389. #define nflag optlist[5]
  390. #define sflag optlist[6]
  391. #define cflag optlist[7]
  392. #define xflag optlist[8]
  393. #define vflag optlist[9]
  394. #define Cflag optlist[10]
  395. #define aflag optlist[11]
  396. #define bflag optlist[12]
  397. #define uflag optlist[13]
  398. #define viflag optlist[14]
  399. #if BASH_PIPEFAIL
  400. # define pipefail optlist[15]
  401. #else
  402. # define pipefail 0
  403. #endif
  404. #if DEBUG
  405. # define nolog optlist[15 + BASH_PIPEFAIL]
  406. # define debug optlist[16 + BASH_PIPEFAIL]
  407. #endif
  408. /* trap handler commands */
  409. /*
  410. * Sigmode records the current value of the signal handlers for the various
  411. * modes. A value of zero means that the current handler is not known.
  412. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  413. */
  414. char sigmode[NSIG - 1];
  415. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  416. #define S_CATCH 2 /* signal is caught */
  417. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  418. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  419. /* indicates specified signal received */
  420. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  421. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  422. char *trap[NSIG];
  423. char **trap_ptr; /* used only by "trap hack" */
  424. /* Rarely referenced stuff */
  425. #if ENABLE_ASH_RANDOM_SUPPORT
  426. random_t random_gen;
  427. #endif
  428. pid_t backgndpid; /* pid of last background process */
  429. };
  430. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  431. #define G_misc (*ash_ptr_to_globals_misc)
  432. #define exitstatus (G_misc.exitstatus )
  433. #define back_exitstatus (G_misc.back_exitstatus )
  434. #define job_warning (G_misc.job_warning)
  435. #define savestatus (G_misc.savestatus )
  436. #define rootpid (G_misc.rootpid )
  437. #define shlvl (G_misc.shlvl )
  438. #define errlinno (G_misc.errlinno )
  439. #define minusc (G_misc.minusc )
  440. #define curdir (G_misc.curdir )
  441. #define physdir (G_misc.physdir )
  442. #define arg0 (G_misc.arg0 )
  443. #define exception_handler (G_misc.exception_handler)
  444. #define exception_type (G_misc.exception_type )
  445. #define suppress_int (G_misc.suppress_int )
  446. #define pending_int (G_misc.pending_int )
  447. #define got_sigchld (G_misc.got_sigchld )
  448. #define pending_sig (G_misc.pending_sig )
  449. #define nullstr (G_misc.nullstr )
  450. #define optlist (G_misc.optlist )
  451. #define sigmode (G_misc.sigmode )
  452. #define gotsig (G_misc.gotsig )
  453. #define may_have_traps (G_misc.may_have_traps )
  454. #define trap (G_misc.trap )
  455. #define trap_ptr (G_misc.trap_ptr )
  456. #define random_gen (G_misc.random_gen )
  457. #define backgndpid (G_misc.backgndpid )
  458. #define INIT_G_misc() do { \
  459. (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
  460. barrier(); \
  461. savestatus = -1; \
  462. curdir = nullstr; \
  463. physdir = nullstr; \
  464. trap_ptr = trap; \
  465. } while (0)
  466. /* ============ DEBUG */
  467. #if DEBUG
  468. static void trace_printf(const char *fmt, ...);
  469. static void trace_vprintf(const char *fmt, va_list va);
  470. # define TRACE(param) trace_printf param
  471. # define TRACEV(param) trace_vprintf param
  472. # define close(fd) do { \
  473. int dfd = (fd); \
  474. if (close(dfd) < 0) \
  475. bb_error_msg("bug on %d: closing %d(0x%x)", \
  476. __LINE__, dfd, dfd); \
  477. } while (0)
  478. #else
  479. # define TRACE(param)
  480. # define TRACEV(param)
  481. #endif
  482. /* ============ Utility functions */
  483. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  484. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  485. static int
  486. isdigit_str9(const char *str)
  487. {
  488. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  489. while (--maxlen && isdigit(*str))
  490. str++;
  491. return (*str == '\0');
  492. }
  493. static const char *
  494. var_end(const char *var)
  495. {
  496. while (*var)
  497. if (*var++ == '=')
  498. break;
  499. return var;
  500. }
  501. /* ============ Parser data */
  502. /*
  503. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  504. */
  505. struct strlist {
  506. struct strlist *next;
  507. char *text;
  508. };
  509. struct alias;
  510. struct strpush {
  511. struct strpush *prev; /* preceding string on stack */
  512. char *prev_string;
  513. int prev_left_in_line;
  514. #if ENABLE_ASH_ALIAS
  515. struct alias *ap; /* if push was associated with an alias */
  516. #endif
  517. char *string; /* remember the string since it may change */
  518. /* Remember last two characters for pungetc. */
  519. int lastc[2];
  520. /* Number of outstanding calls to pungetc. */
  521. int unget;
  522. };
  523. /*
  524. * The parsefile structure pointed to by the global variable parsefile
  525. * contains information about the current file being read.
  526. */
  527. struct parsefile {
  528. struct parsefile *prev; /* preceding file on stack */
  529. int linno; /* current line */
  530. int pf_fd; /* file descriptor (or -1 if string) */
  531. int left_in_line; /* number of chars left in this line */
  532. int left_in_buffer; /* number of chars left in this buffer past the line */
  533. char *next_to_pgetc; /* next char in buffer */
  534. char *buf; /* input buffer */
  535. struct strpush *strpush; /* for pushing strings at this level */
  536. struct strpush basestrpush; /* so pushing one is fast */
  537. /* Remember last two characters for pungetc. */
  538. int lastc[2];
  539. /* Number of outstanding calls to pungetc. */
  540. int unget;
  541. };
  542. static struct parsefile basepf; /* top level input file */
  543. static struct parsefile *g_parsefile = &basepf; /* current input file */
  544. static char *commandname; /* currently executing command */
  545. /* ============ Interrupts / exceptions */
  546. static void exitshell(void) NORETURN;
  547. /*
  548. * These macros allow the user to suspend the handling of interrupt signals
  549. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  550. * much more efficient and portable. (But hacking the kernel is so much
  551. * more fun than worrying about efficiency and portability. :-))
  552. */
  553. #if DEBUG_INTONOFF
  554. # define INT_OFF do { \
  555. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  556. suppress_int++; \
  557. barrier(); \
  558. } while (0)
  559. #else
  560. # define INT_OFF do { \
  561. suppress_int++; \
  562. barrier(); \
  563. } while (0)
  564. #endif
  565. /*
  566. * Called to raise an exception. Since C doesn't include exceptions, we
  567. * just do a longjmp to the exception handler. The type of exception is
  568. * stored in the global variable "exception_type".
  569. */
  570. static void raise_exception(int) NORETURN;
  571. static void
  572. raise_exception(int e)
  573. {
  574. #if DEBUG
  575. if (exception_handler == NULL)
  576. abort();
  577. #endif
  578. INT_OFF;
  579. exception_type = e;
  580. longjmp(exception_handler->loc, 1);
  581. }
  582. #if DEBUG
  583. #define raise_exception(e) do { \
  584. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  585. raise_exception(e); \
  586. } while (0)
  587. #endif
  588. /*
  589. * Called when a SIGINT is received. (If the user specifies
  590. * that SIGINT is to be trapped or ignored using the trap builtin, then
  591. * this routine is not called.) Suppressint is nonzero when interrupts
  592. * are held using the INT_OFF macro. (The test for iflag is just
  593. * defensive programming.)
  594. */
  595. static void raise_interrupt(void) NORETURN;
  596. static void
  597. raise_interrupt(void)
  598. {
  599. pending_int = 0;
  600. /* Signal is not automatically unmasked after it is raised,
  601. * do it ourself - unmask all signals */
  602. sigprocmask_allsigs(SIG_UNBLOCK);
  603. /* pending_sig = 0; - now done in signal_handler() */
  604. if (!(rootshell && iflag)) {
  605. /* Kill ourself with SIGINT */
  606. signal(SIGINT, SIG_DFL);
  607. raise(SIGINT);
  608. }
  609. /* bash: ^C even on empty command line sets $? */
  610. exitstatus = SIGINT + 128;
  611. raise_exception(EXINT);
  612. /* NOTREACHED */
  613. }
  614. #if DEBUG
  615. #define raise_interrupt() do { \
  616. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  617. raise_interrupt(); \
  618. } while (0)
  619. #endif
  620. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  621. int_on(void)
  622. {
  623. barrier();
  624. if (--suppress_int == 0 && pending_int) {
  625. raise_interrupt();
  626. }
  627. }
  628. #if DEBUG_INTONOFF
  629. # define INT_ON do { \
  630. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  631. int_on(); \
  632. } while (0)
  633. #else
  634. # define INT_ON int_on()
  635. #endif
  636. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  637. force_int_on(void)
  638. {
  639. barrier();
  640. suppress_int = 0;
  641. if (pending_int)
  642. raise_interrupt();
  643. }
  644. #define FORCE_INT_ON force_int_on()
  645. #define SAVE_INT(v) ((v) = suppress_int)
  646. #define RESTORE_INT(v) do { \
  647. barrier(); \
  648. suppress_int = (v); \
  649. if (suppress_int == 0 && pending_int) \
  650. raise_interrupt(); \
  651. } while (0)
  652. /* ============ Stdout/stderr output */
  653. static void
  654. outstr(const char *p, FILE *file)
  655. {
  656. INT_OFF;
  657. fputs(p, file);
  658. INT_ON;
  659. }
  660. static void
  661. flush_stdout_stderr(void)
  662. {
  663. INT_OFF;
  664. fflush_all();
  665. INT_ON;
  666. }
  667. /* Was called outcslow(c,FILE*), but c was always '\n' */
  668. static void
  669. newline_and_flush(FILE *dest)
  670. {
  671. INT_OFF;
  672. putc('\n', dest);
  673. fflush(dest);
  674. INT_ON;
  675. }
  676. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  677. static int
  678. out1fmt(const char *fmt, ...)
  679. {
  680. va_list ap;
  681. int r;
  682. INT_OFF;
  683. va_start(ap, fmt);
  684. r = vprintf(fmt, ap);
  685. va_end(ap);
  686. INT_ON;
  687. return r;
  688. }
  689. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  690. static int
  691. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  692. {
  693. va_list ap;
  694. int ret;
  695. INT_OFF;
  696. va_start(ap, fmt);
  697. ret = vsnprintf(outbuf, length, fmt, ap);
  698. va_end(ap);
  699. INT_ON;
  700. return ret > (int)length ? length : ret;
  701. }
  702. static void
  703. out1str(const char *p)
  704. {
  705. outstr(p, stdout);
  706. }
  707. static void
  708. out2str(const char *p)
  709. {
  710. outstr(p, stderr);
  711. flush_stdout_stderr();
  712. }
  713. /* ============ Parser structures */
  714. /* control characters in argument strings */
  715. #define CTL_FIRST CTLESC
  716. #define CTLESC ((unsigned char)'\201') /* escape next character */
  717. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  718. #define CTLENDVAR ((unsigned char)'\203')
  719. #define CTLBACKQ ((unsigned char)'\204')
  720. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  721. #define CTLENDARI ((unsigned char)'\207')
  722. #define CTLQUOTEMARK ((unsigned char)'\210')
  723. #define CTL_LAST CTLQUOTEMARK
  724. /* variable substitution byte (follows CTLVAR) */
  725. #define VSTYPE 0x0f /* type of variable substitution */
  726. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  727. /* values of VSTYPE field */
  728. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  729. #define VSMINUS 0x2 /* ${var-text} */
  730. #define VSPLUS 0x3 /* ${var+text} */
  731. #define VSQUESTION 0x4 /* ${var?message} */
  732. #define VSASSIGN 0x5 /* ${var=text} */
  733. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  734. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  735. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  736. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  737. #define VSLENGTH 0xa /* ${#var} */
  738. #if BASH_SUBSTR
  739. #define VSSUBSTR 0xc /* ${var:position:length} */
  740. #endif
  741. #if BASH_PATTERN_SUBST
  742. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  743. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  744. #endif
  745. static const char dolatstr[] ALIGN1 = {
  746. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  747. };
  748. #define DOLATSTRLEN 6
  749. #define NCMD 0
  750. #define NPIPE 1
  751. #define NREDIR 2
  752. #define NBACKGND 3
  753. #define NSUBSHELL 4
  754. #define NAND 5
  755. #define NOR 6
  756. #define NSEMI 7
  757. #define NIF 8
  758. #define NWHILE 9
  759. #define NUNTIL 10
  760. #define NFOR 11
  761. #define NCASE 12
  762. #define NCLIST 13
  763. #define NDEFUN 14
  764. #define NARG 15
  765. #define NTO 16
  766. #if BASH_REDIR_OUTPUT
  767. #define NTO2 17
  768. #endif
  769. #define NCLOBBER 18
  770. #define NFROM 19
  771. #define NFROMTO 20
  772. #define NAPPEND 21
  773. #define NTOFD 22
  774. #define NFROMFD 23
  775. #define NHERE 24
  776. #define NXHERE 25
  777. #define NNOT 26
  778. #define N_NUMBER 27
  779. union node;
  780. struct ncmd {
  781. smallint type; /* Nxxxx */
  782. int linno;
  783. union node *assign;
  784. union node *args;
  785. union node *redirect;
  786. };
  787. struct npipe {
  788. smallint type;
  789. smallint pipe_backgnd;
  790. struct nodelist *cmdlist;
  791. };
  792. struct nredir {
  793. smallint type;
  794. int linno;
  795. union node *n;
  796. union node *redirect;
  797. };
  798. struct nbinary {
  799. smallint type;
  800. union node *ch1;
  801. union node *ch2;
  802. };
  803. struct nif {
  804. smallint type;
  805. union node *test;
  806. union node *ifpart;
  807. union node *elsepart;
  808. };
  809. struct nfor {
  810. smallint type;
  811. int linno;
  812. union node *args;
  813. union node *body;
  814. char *var;
  815. };
  816. struct ncase {
  817. smallint type;
  818. int linno;
  819. union node *expr;
  820. union node *cases;
  821. };
  822. struct nclist {
  823. smallint type;
  824. union node *next;
  825. union node *pattern;
  826. union node *body;
  827. };
  828. struct ndefun {
  829. smallint type;
  830. int linno;
  831. char *text;
  832. union node *body;
  833. };
  834. struct narg {
  835. smallint type;
  836. union node *next;
  837. char *text;
  838. struct nodelist *backquote;
  839. };
  840. /* nfile and ndup layout must match!
  841. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  842. * that it is actually NTO2 (>&file), and change its type.
  843. */
  844. struct nfile {
  845. smallint type;
  846. union node *next;
  847. int fd;
  848. int _unused_dupfd;
  849. union node *fname;
  850. char *expfname;
  851. };
  852. struct ndup {
  853. smallint type;
  854. union node *next;
  855. int fd;
  856. int dupfd;
  857. union node *vname;
  858. char *_unused_expfname;
  859. };
  860. struct nhere {
  861. smallint type;
  862. union node *next;
  863. int fd;
  864. union node *doc;
  865. };
  866. struct nnot {
  867. smallint type;
  868. union node *com;
  869. };
  870. union node {
  871. smallint type;
  872. struct ncmd ncmd;
  873. struct npipe npipe;
  874. struct nredir nredir;
  875. struct nbinary nbinary;
  876. struct nif nif;
  877. struct nfor nfor;
  878. struct ncase ncase;
  879. struct nclist nclist;
  880. struct ndefun ndefun;
  881. struct narg narg;
  882. struct nfile nfile;
  883. struct ndup ndup;
  884. struct nhere nhere;
  885. struct nnot nnot;
  886. };
  887. /*
  888. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  889. * It must be distinct from NULL.
  890. */
  891. #define NODE_EOF ((union node *) -1L)
  892. struct nodelist {
  893. struct nodelist *next;
  894. union node *n;
  895. };
  896. struct funcnode {
  897. int count;
  898. union node n;
  899. };
  900. /*
  901. * Free a parse tree.
  902. */
  903. static void
  904. freefunc(struct funcnode *f)
  905. {
  906. if (f && --f->count < 0)
  907. free(f);
  908. }
  909. /* ============ Debugging output */
  910. #if DEBUG
  911. static FILE *tracefile;
  912. static void
  913. trace_printf(const char *fmt, ...)
  914. {
  915. va_list va;
  916. if (debug != 1)
  917. return;
  918. if (DEBUG_TIME)
  919. fprintf(tracefile, "%u ", (int) time(NULL));
  920. if (DEBUG_PID)
  921. fprintf(tracefile, "[%u] ", (int) getpid());
  922. if (DEBUG_SIG)
  923. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  924. va_start(va, fmt);
  925. vfprintf(tracefile, fmt, va);
  926. va_end(va);
  927. }
  928. static void
  929. trace_vprintf(const char *fmt, va_list va)
  930. {
  931. if (debug != 1)
  932. return;
  933. vfprintf(tracefile, fmt, va);
  934. fprintf(tracefile, "\n");
  935. }
  936. static void
  937. trace_puts(const char *s)
  938. {
  939. if (debug != 1)
  940. return;
  941. fputs(s, tracefile);
  942. }
  943. static void
  944. trace_puts_quoted(char *s)
  945. {
  946. char *p;
  947. char c;
  948. if (debug != 1)
  949. return;
  950. putc('"', tracefile);
  951. for (p = s; *p; p++) {
  952. switch ((unsigned char)*p) {
  953. case '\n': c = 'n'; goto backslash;
  954. case '\t': c = 't'; goto backslash;
  955. case '\r': c = 'r'; goto backslash;
  956. case '\"': c = '\"'; goto backslash;
  957. case '\\': c = '\\'; goto backslash;
  958. case CTLESC: c = 'e'; goto backslash;
  959. case CTLVAR: c = 'v'; goto backslash;
  960. case CTLBACKQ: c = 'q'; goto backslash;
  961. backslash:
  962. putc('\\', tracefile);
  963. putc(c, tracefile);
  964. break;
  965. default:
  966. if (*p >= ' ' && *p <= '~')
  967. putc(*p, tracefile);
  968. else {
  969. putc('\\', tracefile);
  970. putc((*p >> 6) & 03, tracefile);
  971. putc((*p >> 3) & 07, tracefile);
  972. putc(*p & 07, tracefile);
  973. }
  974. break;
  975. }
  976. }
  977. putc('"', tracefile);
  978. }
  979. static void
  980. trace_puts_args(char **ap)
  981. {
  982. if (debug != 1)
  983. return;
  984. if (!*ap)
  985. return;
  986. while (1) {
  987. trace_puts_quoted(*ap);
  988. if (!*++ap) {
  989. putc('\n', tracefile);
  990. break;
  991. }
  992. putc(' ', tracefile);
  993. }
  994. }
  995. static void
  996. opentrace(void)
  997. {
  998. char s[100];
  999. #ifdef O_APPEND
  1000. int flags;
  1001. #endif
  1002. if (debug != 1) {
  1003. if (tracefile)
  1004. fflush(tracefile);
  1005. /* leave open because libedit might be using it */
  1006. return;
  1007. }
  1008. strcpy(s, "./trace");
  1009. if (tracefile) {
  1010. if (!freopen(s, "a", tracefile)) {
  1011. fprintf(stderr, "Can't re-open %s\n", s);
  1012. debug = 0;
  1013. return;
  1014. }
  1015. } else {
  1016. tracefile = fopen(s, "a");
  1017. if (tracefile == NULL) {
  1018. fprintf(stderr, "Can't open %s\n", s);
  1019. debug = 0;
  1020. return;
  1021. }
  1022. }
  1023. #ifdef O_APPEND
  1024. flags = fcntl(fileno(tracefile), F_GETFL);
  1025. if (flags >= 0)
  1026. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  1027. #endif
  1028. setlinebuf(tracefile);
  1029. fputs("\nTracing started.\n", tracefile);
  1030. }
  1031. static void
  1032. indent(int amount, char *pfx, FILE *fp)
  1033. {
  1034. int i;
  1035. for (i = 0; i < amount; i++) {
  1036. if (pfx && i == amount - 1)
  1037. fputs(pfx, fp);
  1038. putc('\t', fp);
  1039. }
  1040. }
  1041. /* little circular references here... */
  1042. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  1043. static void
  1044. sharg(union node *arg, FILE *fp)
  1045. {
  1046. char *p;
  1047. struct nodelist *bqlist;
  1048. unsigned char subtype;
  1049. if (arg->type != NARG) {
  1050. out1fmt("<node type %d>\n", arg->type);
  1051. abort();
  1052. }
  1053. bqlist = arg->narg.backquote;
  1054. for (p = arg->narg.text; *p; p++) {
  1055. switch ((unsigned char)*p) {
  1056. case CTLESC:
  1057. p++;
  1058. putc(*p, fp);
  1059. break;
  1060. case CTLVAR:
  1061. putc('$', fp);
  1062. putc('{', fp);
  1063. subtype = *++p;
  1064. if (subtype == VSLENGTH)
  1065. putc('#', fp);
  1066. while (*p != '=') {
  1067. putc(*p, fp);
  1068. p++;
  1069. }
  1070. if (subtype & VSNUL)
  1071. putc(':', fp);
  1072. switch (subtype & VSTYPE) {
  1073. case VSNORMAL:
  1074. putc('}', fp);
  1075. break;
  1076. case VSMINUS:
  1077. putc('-', fp);
  1078. break;
  1079. case VSPLUS:
  1080. putc('+', fp);
  1081. break;
  1082. case VSQUESTION:
  1083. putc('?', fp);
  1084. break;
  1085. case VSASSIGN:
  1086. putc('=', fp);
  1087. break;
  1088. case VSTRIMLEFT:
  1089. putc('#', fp);
  1090. break;
  1091. case VSTRIMLEFTMAX:
  1092. putc('#', fp);
  1093. putc('#', fp);
  1094. break;
  1095. case VSTRIMRIGHT:
  1096. putc('%', fp);
  1097. break;
  1098. case VSTRIMRIGHTMAX:
  1099. putc('%', fp);
  1100. putc('%', fp);
  1101. break;
  1102. case VSLENGTH:
  1103. break;
  1104. default:
  1105. out1fmt("<subtype %d>", subtype);
  1106. }
  1107. break;
  1108. case CTLENDVAR:
  1109. putc('}', fp);
  1110. break;
  1111. case CTLBACKQ:
  1112. putc('$', fp);
  1113. putc('(', fp);
  1114. shtree(bqlist->n, -1, NULL, fp);
  1115. putc(')', fp);
  1116. break;
  1117. default:
  1118. putc(*p, fp);
  1119. break;
  1120. }
  1121. }
  1122. }
  1123. static void
  1124. shcmd(union node *cmd, FILE *fp)
  1125. {
  1126. union node *np;
  1127. int first;
  1128. const char *s;
  1129. int dftfd;
  1130. first = 1;
  1131. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1132. if (!first)
  1133. putc(' ', fp);
  1134. sharg(np, fp);
  1135. first = 0;
  1136. }
  1137. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1138. if (!first)
  1139. putc(' ', fp);
  1140. dftfd = 0;
  1141. switch (np->nfile.type) {
  1142. case NTO: s = ">>"+1; dftfd = 1; break;
  1143. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1144. case NAPPEND: s = ">>"; dftfd = 1; break;
  1145. #if BASH_REDIR_OUTPUT
  1146. case NTO2:
  1147. #endif
  1148. case NTOFD: s = ">&"; dftfd = 1; break;
  1149. case NFROM: s = "<"; break;
  1150. case NFROMFD: s = "<&"; break;
  1151. case NFROMTO: s = "<>"; break;
  1152. default: s = "*error*"; break;
  1153. }
  1154. if (np->nfile.fd != dftfd)
  1155. fprintf(fp, "%d", np->nfile.fd);
  1156. fputs(s, fp);
  1157. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1158. fprintf(fp, "%d", np->ndup.dupfd);
  1159. } else {
  1160. sharg(np->nfile.fname, fp);
  1161. }
  1162. first = 0;
  1163. }
  1164. }
  1165. static void
  1166. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1167. {
  1168. struct nodelist *lp;
  1169. const char *s;
  1170. if (n == NULL)
  1171. return;
  1172. indent(ind, pfx, fp);
  1173. if (n == NODE_EOF) {
  1174. fputs("<EOF>", fp);
  1175. return;
  1176. }
  1177. switch (n->type) {
  1178. case NSEMI:
  1179. s = "; ";
  1180. goto binop;
  1181. case NAND:
  1182. s = " && ";
  1183. goto binop;
  1184. case NOR:
  1185. s = " || ";
  1186. binop:
  1187. shtree(n->nbinary.ch1, ind, NULL, fp);
  1188. /* if (ind < 0) */
  1189. fputs(s, fp);
  1190. shtree(n->nbinary.ch2, ind, NULL, fp);
  1191. break;
  1192. case NCMD:
  1193. shcmd(n, fp);
  1194. if (ind >= 0)
  1195. putc('\n', fp);
  1196. break;
  1197. case NPIPE:
  1198. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1199. shtree(lp->n, 0, NULL, fp);
  1200. if (lp->next)
  1201. fputs(" | ", fp);
  1202. }
  1203. if (n->npipe.pipe_backgnd)
  1204. fputs(" &", fp);
  1205. if (ind >= 0)
  1206. putc('\n', fp);
  1207. break;
  1208. default:
  1209. fprintf(fp, "<node type %d>", n->type);
  1210. if (ind >= 0)
  1211. putc('\n', fp);
  1212. break;
  1213. }
  1214. }
  1215. static void
  1216. showtree(union node *n)
  1217. {
  1218. trace_puts("showtree called\n");
  1219. shtree(n, 1, NULL, stderr);
  1220. }
  1221. #endif /* DEBUG */
  1222. /* ============ Message printing */
  1223. static void
  1224. ash_vmsg(const char *msg, va_list ap)
  1225. {
  1226. fprintf(stderr, "%s: ", arg0);
  1227. if (commandname) {
  1228. if (strcmp(arg0, commandname))
  1229. fprintf(stderr, "%s: ", commandname);
  1230. if (!iflag || g_parsefile->pf_fd > 0)
  1231. fprintf(stderr, "line %d: ", errlinno);
  1232. }
  1233. vfprintf(stderr, msg, ap);
  1234. newline_and_flush(stderr);
  1235. }
  1236. /*
  1237. * Exverror is called to raise the error exception. If the second argument
  1238. * is not NULL then error prints an error message using printf style
  1239. * formatting. It then raises the error exception.
  1240. */
  1241. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1242. static void
  1243. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1244. {
  1245. #if DEBUG
  1246. if (msg) {
  1247. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1248. TRACEV((msg, ap));
  1249. } else
  1250. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1251. if (msg)
  1252. #endif
  1253. ash_vmsg(msg, ap);
  1254. flush_stdout_stderr();
  1255. raise_exception(cond);
  1256. /* NOTREACHED */
  1257. }
  1258. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1259. static void
  1260. ash_msg_and_raise_error(const char *msg, ...)
  1261. {
  1262. va_list ap;
  1263. exitstatus = 2;
  1264. va_start(ap, msg);
  1265. ash_vmsg_and_raise(EXERROR, msg, ap);
  1266. /* NOTREACHED */
  1267. va_end(ap);
  1268. }
  1269. /*
  1270. * 'fmt' must be a string literal.
  1271. */
  1272. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1273. static void raise_error_syntax(const char *) NORETURN;
  1274. static void
  1275. raise_error_syntax(const char *msg)
  1276. {
  1277. errlinno = g_parsefile->linno;
  1278. ash_msg_and_raise_error("syntax error: %s", msg);
  1279. /* NOTREACHED */
  1280. }
  1281. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1282. static void
  1283. ash_msg_and_raise(int cond, const char *msg, ...)
  1284. {
  1285. va_list ap;
  1286. va_start(ap, msg);
  1287. ash_vmsg_and_raise(cond, msg, ap);
  1288. /* NOTREACHED */
  1289. va_end(ap);
  1290. }
  1291. /*
  1292. * error/warning routines for external builtins
  1293. */
  1294. static void
  1295. ash_msg(const char *fmt, ...)
  1296. {
  1297. va_list ap;
  1298. va_start(ap, fmt);
  1299. ash_vmsg(fmt, ap);
  1300. va_end(ap);
  1301. }
  1302. /*
  1303. * Return a string describing an error. The returned string may be a
  1304. * pointer to a static buffer that will be overwritten on the next call.
  1305. * Action describes the operation that got the error.
  1306. */
  1307. static const char *
  1308. errmsg(int e, const char *em)
  1309. {
  1310. if (e == ENOENT || e == ENOTDIR) {
  1311. return em;
  1312. }
  1313. return strerror(e);
  1314. }
  1315. /* ============ Memory allocation */
  1316. #if 0
  1317. /* I consider these wrappers nearly useless:
  1318. * ok, they return you to nearest exception handler, but
  1319. * how much memory do you leak in the process, making
  1320. * memory starvation worse?
  1321. */
  1322. static void *
  1323. ckrealloc(void * p, size_t nbytes)
  1324. {
  1325. p = realloc(p, nbytes);
  1326. if (!p)
  1327. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1328. return p;
  1329. }
  1330. static void *
  1331. ckmalloc(size_t nbytes)
  1332. {
  1333. return ckrealloc(NULL, nbytes);
  1334. }
  1335. static void *
  1336. ckzalloc(size_t nbytes)
  1337. {
  1338. return memset(ckmalloc(nbytes), 0, nbytes);
  1339. }
  1340. static char *
  1341. ckstrdup(const char *s)
  1342. {
  1343. char *p = strdup(s);
  1344. if (!p)
  1345. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1346. return p;
  1347. }
  1348. #else
  1349. /* Using bbox equivalents. They exit if out of memory */
  1350. # define ckrealloc xrealloc
  1351. # define ckmalloc xmalloc
  1352. # define ckzalloc xzalloc
  1353. # define ckstrdup xstrdup
  1354. #endif
  1355. /*
  1356. * It appears that grabstackstr() will barf with such alignments
  1357. * because stalloc() will return a string allocated in a new stackblock.
  1358. */
  1359. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1360. enum {
  1361. /* Most machines require the value returned from malloc to be aligned
  1362. * in some way. The following macro will get this right
  1363. * on many machines. */
  1364. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1365. /* Minimum size of a block */
  1366. MINSIZE = SHELL_ALIGN(504),
  1367. };
  1368. struct stack_block {
  1369. struct stack_block *prev;
  1370. char space[MINSIZE];
  1371. };
  1372. struct stackmark {
  1373. struct stack_block *stackp;
  1374. char *stacknxt;
  1375. size_t stacknleft;
  1376. };
  1377. struct globals_memstack {
  1378. struct stack_block *g_stackp; // = &stackbase;
  1379. char *g_stacknxt; // = stackbase.space;
  1380. char *sstrend; // = stackbase.space + MINSIZE;
  1381. size_t g_stacknleft; // = MINSIZE;
  1382. struct stack_block stackbase;
  1383. };
  1384. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1385. #define G_memstack (*ash_ptr_to_globals_memstack)
  1386. #define g_stackp (G_memstack.g_stackp )
  1387. #define g_stacknxt (G_memstack.g_stacknxt )
  1388. #define sstrend (G_memstack.sstrend )
  1389. #define g_stacknleft (G_memstack.g_stacknleft)
  1390. #define stackbase (G_memstack.stackbase )
  1391. #define INIT_G_memstack() do { \
  1392. (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
  1393. barrier(); \
  1394. g_stackp = &stackbase; \
  1395. g_stacknxt = stackbase.space; \
  1396. g_stacknleft = MINSIZE; \
  1397. sstrend = stackbase.space + MINSIZE; \
  1398. } while (0)
  1399. #define stackblock() ((void *)g_stacknxt)
  1400. #define stackblocksize() g_stacknleft
  1401. /*
  1402. * Parse trees for commands are allocated in lifo order, so we use a stack
  1403. * to make this more efficient, and also to avoid all sorts of exception
  1404. * handling code to handle interrupts in the middle of a parse.
  1405. *
  1406. * The size 504 was chosen because the Ultrix malloc handles that size
  1407. * well.
  1408. */
  1409. static void *
  1410. stalloc(size_t nbytes)
  1411. {
  1412. char *p;
  1413. size_t aligned;
  1414. aligned = SHELL_ALIGN(nbytes);
  1415. if (aligned > g_stacknleft) {
  1416. size_t len;
  1417. size_t blocksize;
  1418. struct stack_block *sp;
  1419. blocksize = aligned;
  1420. if (blocksize < MINSIZE)
  1421. blocksize = MINSIZE;
  1422. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1423. if (len < blocksize)
  1424. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1425. INT_OFF;
  1426. sp = ckmalloc(len);
  1427. sp->prev = g_stackp;
  1428. g_stacknxt = sp->space;
  1429. g_stacknleft = blocksize;
  1430. sstrend = g_stacknxt + blocksize;
  1431. g_stackp = sp;
  1432. INT_ON;
  1433. }
  1434. p = g_stacknxt;
  1435. g_stacknxt += aligned;
  1436. g_stacknleft -= aligned;
  1437. return p;
  1438. }
  1439. static void *
  1440. stzalloc(size_t nbytes)
  1441. {
  1442. return memset(stalloc(nbytes), 0, nbytes);
  1443. }
  1444. static void
  1445. stunalloc(void *p)
  1446. {
  1447. #if DEBUG
  1448. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1449. write(STDERR_FILENO, "stunalloc\n", 10);
  1450. abort();
  1451. }
  1452. #endif
  1453. g_stacknleft += g_stacknxt - (char *)p;
  1454. g_stacknxt = p;
  1455. }
  1456. /*
  1457. * Like strdup but works with the ash stack.
  1458. */
  1459. static char *
  1460. sstrdup(const char *p)
  1461. {
  1462. size_t len = strlen(p) + 1;
  1463. return memcpy(stalloc(len), p, len);
  1464. }
  1465. static ALWAYS_INLINE void
  1466. grabstackblock(size_t len)
  1467. {
  1468. stalloc(len);
  1469. }
  1470. static void
  1471. pushstackmark(struct stackmark *mark, size_t len)
  1472. {
  1473. mark->stackp = g_stackp;
  1474. mark->stacknxt = g_stacknxt;
  1475. mark->stacknleft = g_stacknleft;
  1476. grabstackblock(len);
  1477. }
  1478. static void
  1479. setstackmark(struct stackmark *mark)
  1480. {
  1481. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1482. }
  1483. static void
  1484. popstackmark(struct stackmark *mark)
  1485. {
  1486. struct stack_block *sp;
  1487. if (!mark->stackp)
  1488. return;
  1489. INT_OFF;
  1490. while (g_stackp != mark->stackp) {
  1491. sp = g_stackp;
  1492. g_stackp = sp->prev;
  1493. free(sp);
  1494. }
  1495. g_stacknxt = mark->stacknxt;
  1496. g_stacknleft = mark->stacknleft;
  1497. sstrend = mark->stacknxt + mark->stacknleft;
  1498. INT_ON;
  1499. }
  1500. /*
  1501. * When the parser reads in a string, it wants to stick the string on the
  1502. * stack and only adjust the stack pointer when it knows how big the
  1503. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1504. * of space on top of the stack and stackblocklen returns the length of
  1505. * this block. Growstackblock will grow this space by at least one byte,
  1506. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1507. * part of the block that has been used.
  1508. */
  1509. static void
  1510. growstackblock(size_t min)
  1511. {
  1512. size_t newlen;
  1513. newlen = g_stacknleft * 2;
  1514. if (newlen < g_stacknleft)
  1515. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1516. min = SHELL_ALIGN(min | 128);
  1517. if (newlen < min)
  1518. newlen += min;
  1519. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1520. struct stack_block *sp;
  1521. struct stack_block *prevstackp;
  1522. size_t grosslen;
  1523. INT_OFF;
  1524. sp = g_stackp;
  1525. prevstackp = sp->prev;
  1526. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1527. sp = ckrealloc(sp, grosslen);
  1528. sp->prev = prevstackp;
  1529. g_stackp = sp;
  1530. g_stacknxt = sp->space;
  1531. g_stacknleft = newlen;
  1532. sstrend = sp->space + newlen;
  1533. INT_ON;
  1534. } else {
  1535. char *oldspace = g_stacknxt;
  1536. size_t oldlen = g_stacknleft;
  1537. char *p = stalloc(newlen);
  1538. /* free the space we just allocated */
  1539. g_stacknxt = memcpy(p, oldspace, oldlen);
  1540. g_stacknleft += newlen;
  1541. }
  1542. }
  1543. /*
  1544. * The following routines are somewhat easier to use than the above.
  1545. * The user declares a variable of type STACKSTR, which may be declared
  1546. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1547. * the user uses the macro STPUTC to add characters to the string. In
  1548. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1549. * grown as necessary. When the user is done, she can just leave the
  1550. * string there and refer to it using stackblock(). Or she can allocate
  1551. * the space for it using grabstackstr(). If it is necessary to allow
  1552. * someone else to use the stack temporarily and then continue to grow
  1553. * the string, the user should use grabstack to allocate the space, and
  1554. * then call ungrabstr(p) to return to the previous mode of operation.
  1555. *
  1556. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1557. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1558. * is space for at least one character.
  1559. */
  1560. static void *
  1561. growstackstr(void)
  1562. {
  1563. size_t len = stackblocksize();
  1564. growstackblock(0);
  1565. return (char *)stackblock() + len;
  1566. }
  1567. static char *
  1568. growstackto(size_t len)
  1569. {
  1570. if (stackblocksize() < len)
  1571. growstackblock(len);
  1572. return stackblock();
  1573. }
  1574. /*
  1575. * Called from CHECKSTRSPACE.
  1576. */
  1577. static char *
  1578. makestrspace(size_t newlen, char *p)
  1579. {
  1580. size_t len = p - g_stacknxt;
  1581. return growstackto(len + newlen) + len;
  1582. }
  1583. static char *
  1584. stnputs(const char *s, size_t n, char *p)
  1585. {
  1586. p = makestrspace(n, p);
  1587. p = (char *)mempcpy(p, s, n);
  1588. return p;
  1589. }
  1590. static char *
  1591. stack_putstr(const char *s, char *p)
  1592. {
  1593. return stnputs(s, strlen(s), p);
  1594. }
  1595. static char *
  1596. _STPUTC(int c, char *p)
  1597. {
  1598. if (p == sstrend)
  1599. p = growstackstr();
  1600. *p++ = c;
  1601. return p;
  1602. }
  1603. #define STARTSTACKSTR(p) ((p) = stackblock())
  1604. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1605. #define CHECKSTRSPACE(n, p) do { \
  1606. char *q = (p); \
  1607. size_t l = (n); \
  1608. size_t m = sstrend - q; \
  1609. if (l > m) \
  1610. (p) = makestrspace(l, q); \
  1611. } while (0)
  1612. #define USTPUTC(c, p) (*(p)++ = (c))
  1613. #define STACKSTRNUL(p) do { \
  1614. if ((p) == sstrend) \
  1615. (p) = growstackstr(); \
  1616. *(p) = '\0'; \
  1617. } while (0)
  1618. #define STUNPUTC(p) (--(p))
  1619. #define STTOPC(p) ((p)[-1])
  1620. #define STADJUST(amount, p) ((p) += (amount))
  1621. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1622. #define ungrabstackstr(s, p) stunalloc(s)
  1623. #define stackstrend() ((void *)sstrend)
  1624. /* ============ String helpers */
  1625. /*
  1626. * prefix -- see if pfx is a prefix of string.
  1627. */
  1628. static char *
  1629. prefix(const char *string, const char *pfx)
  1630. {
  1631. while (*pfx) {
  1632. if (*pfx++ != *string++)
  1633. return NULL;
  1634. }
  1635. return (char *) string;
  1636. }
  1637. /*
  1638. * Check for a valid number. This should be elsewhere.
  1639. */
  1640. static int
  1641. is_number(const char *p)
  1642. {
  1643. do {
  1644. if (!isdigit(*p))
  1645. return 0;
  1646. } while (*++p != '\0');
  1647. return 1;
  1648. }
  1649. /*
  1650. * Convert a string of digits to an integer, printing an error message on
  1651. * failure.
  1652. */
  1653. static int
  1654. number(const char *s)
  1655. {
  1656. if (!is_number(s))
  1657. ash_msg_and_raise_error(msg_illnum, s);
  1658. return atoi(s);
  1659. }
  1660. /*
  1661. * Produce a single quoted string suitable as input to the shell.
  1662. * The return string is allocated on the stack.
  1663. */
  1664. static char *
  1665. single_quote(const char *s)
  1666. {
  1667. char *p;
  1668. STARTSTACKSTR(p);
  1669. do {
  1670. char *q;
  1671. size_t len;
  1672. len = strchrnul(s, '\'') - s;
  1673. q = p = makestrspace(len + 3, p);
  1674. *q++ = '\'';
  1675. q = (char *)mempcpy(q, s, len);
  1676. *q++ = '\'';
  1677. s += len;
  1678. STADJUST(q - p, p);
  1679. if (*s != '\'')
  1680. break;
  1681. len = 0;
  1682. do len++; while (*++s == '\'');
  1683. q = p = makestrspace(len + 3, p);
  1684. *q++ = '"';
  1685. q = (char *)mempcpy(q, s - len, len);
  1686. *q++ = '"';
  1687. STADJUST(q - p, p);
  1688. } while (*s);
  1689. USTPUTC('\0', p);
  1690. return stackblock();
  1691. }
  1692. /*
  1693. * Produce a possibly single quoted string suitable as input to the shell.
  1694. * If quoting was done, the return string is allocated on the stack,
  1695. * otherwise a pointer to the original string is returned.
  1696. */
  1697. static const char *
  1698. maybe_single_quote(const char *s)
  1699. {
  1700. const char *p = s;
  1701. while (*p) {
  1702. /* Assuming ACSII */
  1703. /* quote ctrl_chars space !"#$%&'()* */
  1704. if (*p < '+')
  1705. goto need_quoting;
  1706. /* quote ;<=>? */
  1707. if (*p >= ';' && *p <= '?')
  1708. goto need_quoting;
  1709. /* quote `[\ */
  1710. if (*p == '`')
  1711. goto need_quoting;
  1712. if (*p == '[')
  1713. goto need_quoting;
  1714. if (*p == '\\')
  1715. goto need_quoting;
  1716. /* quote {|}~ DEL and high bytes */
  1717. if (*p > 'z')
  1718. goto need_quoting;
  1719. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1720. /* TODO: maybe avoid quoting % */
  1721. p++;
  1722. }
  1723. return s;
  1724. need_quoting:
  1725. return single_quote(s);
  1726. }
  1727. /* ============ nextopt */
  1728. static char **argptr; /* argument list for builtin commands */
  1729. static char *optionarg; /* set by nextopt (like getopt) */
  1730. static char *optptr; /* used by nextopt */
  1731. /*
  1732. * XXX - should get rid of. Have all builtins use getopt(3).
  1733. * The library getopt must have the BSD extension static variable
  1734. * "optreset", otherwise it can't be used within the shell safely.
  1735. *
  1736. * Standard option processing (a la getopt) for builtin routines.
  1737. * The only argument that is passed to nextopt is the option string;
  1738. * the other arguments are unnecessary. It returns the character,
  1739. * or '\0' on end of input.
  1740. */
  1741. static int
  1742. nextopt(const char *optstring)
  1743. {
  1744. char *p;
  1745. const char *q;
  1746. char c;
  1747. p = optptr;
  1748. if (p == NULL || *p == '\0') {
  1749. /* We ate entire "-param", take next one */
  1750. p = *argptr;
  1751. if (p == NULL)
  1752. return '\0';
  1753. if (*p != '-')
  1754. return '\0';
  1755. if (*++p == '\0') /* just "-" ? */
  1756. return '\0';
  1757. argptr++;
  1758. if (LONE_DASH(p)) /* "--" ? */
  1759. return '\0';
  1760. /* p => next "-param" */
  1761. }
  1762. /* p => some option char in the middle of a "-param" */
  1763. c = *p++;
  1764. for (q = optstring; *q != c;) {
  1765. if (*q == '\0')
  1766. ash_msg_and_raise_error("illegal option -%c", c);
  1767. if (*++q == ':')
  1768. q++;
  1769. }
  1770. if (*++q == ':') {
  1771. if (*p == '\0') {
  1772. p = *argptr++;
  1773. if (p == NULL)
  1774. ash_msg_and_raise_error("no arg for -%c option", c);
  1775. }
  1776. optionarg = p;
  1777. p = NULL;
  1778. }
  1779. optptr = p;
  1780. return c;
  1781. }
  1782. /* ============ Shell variables */
  1783. struct shparam {
  1784. int nparam; /* # of positional parameters (without $0) */
  1785. #if ENABLE_ASH_GETOPTS
  1786. int optind; /* next parameter to be processed by getopts */
  1787. int optoff; /* used by getopts */
  1788. #endif
  1789. unsigned char malloced; /* if parameter list dynamically allocated */
  1790. char **p; /* parameter list */
  1791. };
  1792. /*
  1793. * Free the list of positional parameters.
  1794. */
  1795. static void
  1796. freeparam(volatile struct shparam *param)
  1797. {
  1798. if (param->malloced) {
  1799. char **ap, **ap1;
  1800. ap = ap1 = param->p;
  1801. while (*ap)
  1802. free(*ap++);
  1803. free(ap1);
  1804. }
  1805. }
  1806. #if ENABLE_ASH_GETOPTS
  1807. static void FAST_FUNC getoptsreset(const char *value);
  1808. #endif
  1809. struct var {
  1810. struct var *next; /* next entry in hash list */
  1811. int flags; /* flags are defined above */
  1812. const char *var_text; /* name=value */
  1813. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1814. /* the variable gets set/unset */
  1815. };
  1816. struct localvar {
  1817. struct localvar *next; /* next local variable in list */
  1818. struct var *vp; /* the variable that was made local */
  1819. int flags; /* saved flags */
  1820. const char *text; /* saved text */
  1821. };
  1822. /* flags */
  1823. #define VEXPORT 0x01 /* variable is exported */
  1824. #define VREADONLY 0x02 /* variable cannot be modified */
  1825. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1826. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1827. #define VSTACK 0x10 /* text is allocated on the stack */
  1828. #define VUNSET 0x20 /* the variable is not set */
  1829. #define VNOFUNC 0x40 /* don't call the callback function */
  1830. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1831. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1832. #if ENABLE_ASH_RANDOM_SUPPORT
  1833. # define VDYNAMIC 0x200 /* dynamic variable */
  1834. #else
  1835. # define VDYNAMIC 0
  1836. #endif
  1837. /* Need to be before varinit_data[] */
  1838. #if ENABLE_LOCALE_SUPPORT
  1839. static void FAST_FUNC
  1840. change_lc_all(const char *value)
  1841. {
  1842. if (value && *value != '\0')
  1843. setlocale(LC_ALL, value);
  1844. }
  1845. static void FAST_FUNC
  1846. change_lc_ctype(const char *value)
  1847. {
  1848. if (value && *value != '\0')
  1849. setlocale(LC_CTYPE, value);
  1850. }
  1851. #endif
  1852. #if ENABLE_ASH_MAIL
  1853. static void chkmail(void);
  1854. static void changemail(const char *var_value) FAST_FUNC;
  1855. #else
  1856. # define chkmail() ((void)0)
  1857. #endif
  1858. static void changepath(const char *) FAST_FUNC;
  1859. #if ENABLE_ASH_RANDOM_SUPPORT
  1860. static void change_random(const char *) FAST_FUNC;
  1861. #endif
  1862. #if BASH_EPOCH_VARS
  1863. static void change_seconds(const char *) FAST_FUNC;
  1864. static void change_realtime(const char *) FAST_FUNC;
  1865. #endif
  1866. static const struct {
  1867. int flags;
  1868. const char *var_text;
  1869. void (*var_func)(const char *) FAST_FUNC;
  1870. } varinit_data[] ALIGN_PTR = {
  1871. /*
  1872. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1873. * some environment strings may be constant.
  1874. */
  1875. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1876. #if ENABLE_ASH_MAIL
  1877. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1878. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1879. #endif
  1880. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1881. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1882. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1883. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1884. #if ENABLE_ASH_GETOPTS
  1885. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1886. #endif
  1887. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1888. #if ENABLE_ASH_RANDOM_SUPPORT
  1889. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1890. #endif
  1891. #if BASH_EPOCH_VARS
  1892. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1893. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1894. #endif
  1895. #if ENABLE_LOCALE_SUPPORT
  1896. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1897. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1898. #endif
  1899. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1900. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1901. #endif
  1902. };
  1903. struct redirtab;
  1904. struct globals_var {
  1905. struct shparam shellparam; /* $@ current positional parameters */
  1906. struct redirtab *redirlist;
  1907. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1908. struct var *vartab[VTABSIZE];
  1909. struct var varinit[ARRAY_SIZE(varinit_data)];
  1910. int lineno;
  1911. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1912. };
  1913. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1914. #define G_var (*ash_ptr_to_globals_var)
  1915. #define shellparam (G_var.shellparam )
  1916. //#define redirlist (G_var.redirlist )
  1917. #define preverrout_fd (G_var.preverrout_fd)
  1918. #define vartab (G_var.vartab )
  1919. #define varinit (G_var.varinit )
  1920. #define lineno (G_var.lineno )
  1921. #define linenovar (G_var.linenovar )
  1922. #define vifs varinit[0]
  1923. #if ENABLE_ASH_MAIL
  1924. # define vmail varinit[1]
  1925. # define vmpath varinit[2]
  1926. #endif
  1927. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1928. #define vpath varinit[VAR_OFFSET1 + 1]
  1929. #define vps1 varinit[VAR_OFFSET1 + 2]
  1930. #define vps2 varinit[VAR_OFFSET1 + 3]
  1931. #define vps4 varinit[VAR_OFFSET1 + 4]
  1932. #if ENABLE_ASH_GETOPTS
  1933. # define voptind varinit[VAR_OFFSET1 + 5]
  1934. #endif
  1935. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1936. #define vlineno varinit[VAR_OFFSET2 + 5]
  1937. #if ENABLE_ASH_RANDOM_SUPPORT
  1938. # define vrandom varinit[VAR_OFFSET2 + 6]
  1939. #endif
  1940. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1941. #if BASH_EPOCH_VARS
  1942. # define vepochs varinit[VAR_OFFSET3 + 6]
  1943. # define vepochr varinit[VAR_OFFSET3 + 7]
  1944. #endif
  1945. #define INIT_G_var() do { \
  1946. unsigned i; \
  1947. (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
  1948. barrier(); \
  1949. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1950. varinit[i].flags = varinit_data[i].flags; \
  1951. varinit[i].var_text = varinit_data[i].var_text; \
  1952. varinit[i].var_func = varinit_data[i].var_func; \
  1953. } \
  1954. strcpy(linenovar, "LINENO="); \
  1955. vlineno.var_text = linenovar; \
  1956. } while (0)
  1957. /*
  1958. * The following macros access the values of the above variables.
  1959. * They have to skip over the name. They return the null string
  1960. * for unset variables.
  1961. */
  1962. #define ifsval() (vifs.var_text + 4)
  1963. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1964. #if ENABLE_ASH_MAIL
  1965. # define mailval() (vmail.var_text + 5)
  1966. # define mpathval() (vmpath.var_text + 9)
  1967. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1968. #endif
  1969. #define pathval() (vpath.var_text + 5)
  1970. #define ps1val() (vps1.var_text + 4)
  1971. #define ps2val() (vps2.var_text + 4)
  1972. #define ps4val() (vps4.var_text + 4)
  1973. #if ENABLE_ASH_GETOPTS
  1974. # define optindval() (voptind.var_text + 7)
  1975. #endif
  1976. #if ENABLE_ASH_GETOPTS
  1977. static void FAST_FUNC
  1978. getoptsreset(const char *value)
  1979. {
  1980. shellparam.optind = 1;
  1981. if (is_number(value))
  1982. shellparam.optind = number(value) ?: 1;
  1983. shellparam.optoff = -1;
  1984. }
  1985. #endif
  1986. /*
  1987. * Compares two strings up to the first = or '\0'. The first
  1988. * string must be terminated by '='; the second may be terminated by
  1989. * either '=' or '\0'.
  1990. */
  1991. static int
  1992. varcmp(const char *p, const char *q)
  1993. {
  1994. int c, d;
  1995. while ((c = *p) == (d = *q)) {
  1996. if (c == '\0' || c == '=')
  1997. goto out;
  1998. p++;
  1999. q++;
  2000. }
  2001. if (c == '=')
  2002. c = '\0';
  2003. if (d == '=')
  2004. d = '\0';
  2005. out:
  2006. return c - d;
  2007. }
  2008. /*
  2009. * Find the appropriate entry in the hash table from the name.
  2010. */
  2011. static struct var **
  2012. hashvar(const char *p)
  2013. {
  2014. unsigned hashval;
  2015. hashval = ((unsigned char) *p) << 4;
  2016. while (*p && *p != '=')
  2017. hashval += (unsigned char) *p++;
  2018. return &vartab[hashval % VTABSIZE];
  2019. }
  2020. static int
  2021. vpcmp(const void *a, const void *b)
  2022. {
  2023. return varcmp(*(const char **)a, *(const char **)b);
  2024. }
  2025. /*
  2026. * This routine initializes the builtin variables.
  2027. */
  2028. static void
  2029. initvar(void)
  2030. {
  2031. struct var *vp;
  2032. struct var *end;
  2033. struct var **vpp;
  2034. /*
  2035. * PS1 depends on uid
  2036. */
  2037. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2038. vps1.var_text = "PS1=\\w \\$ ";
  2039. #else
  2040. if (!geteuid())
  2041. vps1.var_text = "PS1=# ";
  2042. #endif
  2043. vp = varinit;
  2044. end = vp + ARRAY_SIZE(varinit);
  2045. do {
  2046. vpp = hashvar(vp->var_text);
  2047. vp->next = *vpp;
  2048. *vpp = vp;
  2049. } while (++vp < end);
  2050. }
  2051. static struct var **
  2052. findvar(struct var **vpp, const char *name)
  2053. {
  2054. for (; *vpp; vpp = &(*vpp)->next) {
  2055. if (varcmp((*vpp)->var_text, name) == 0) {
  2056. break;
  2057. }
  2058. }
  2059. return vpp;
  2060. }
  2061. /*
  2062. * Find the value of a variable. Returns NULL if not set.
  2063. */
  2064. static const char* FAST_FUNC
  2065. lookupvar(const char *name)
  2066. {
  2067. struct var *v;
  2068. v = *findvar(hashvar(name), name);
  2069. if (v) {
  2070. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2071. /*
  2072. * Dynamic variables are implemented roughly the same way they are
  2073. * in bash. Namely, they're "special" so long as they aren't unset.
  2074. * As soon as they're unset, they're no longer dynamic, and dynamic
  2075. * lookup will no longer happen at that point. -- PFM.
  2076. */
  2077. if (v->flags & VDYNAMIC)
  2078. v->var_func(NULL);
  2079. #endif
  2080. if (!(v->flags & VUNSET)) {
  2081. if (v == &vlineno && v->var_text == linenovar) {
  2082. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2083. }
  2084. return var_end(v->var_text);
  2085. }
  2086. }
  2087. return NULL;
  2088. }
  2089. #if ENABLE_UNICODE_SUPPORT
  2090. static void
  2091. reinit_unicode_for_ash(void)
  2092. {
  2093. /* Unicode support should be activated even if LANG is set
  2094. * _during_ shell execution, not only if it was set when
  2095. * shell was started. Therefore, re-check LANG every time:
  2096. */
  2097. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2098. || ENABLE_UNICODE_USING_LOCALE
  2099. ) {
  2100. const char *s = lookupvar("LC_ALL");
  2101. if (!s) s = lookupvar("LC_CTYPE");
  2102. if (!s) s = lookupvar("LANG");
  2103. reinit_unicode(s);
  2104. }
  2105. }
  2106. #else
  2107. # define reinit_unicode_for_ash() ((void)0)
  2108. #endif
  2109. /*
  2110. * Search the environment of a builtin command.
  2111. */
  2112. static ALWAYS_INLINE const char *
  2113. bltinlookup(const char *name)
  2114. {
  2115. return lookupvar(name);
  2116. }
  2117. /*
  2118. * Same as setvar except that the variable and value are passed in
  2119. * the first argument as name=value. Since the first argument will
  2120. * be actually stored in the table, it should not be a string that
  2121. * will go away.
  2122. * Called with interrupts off.
  2123. */
  2124. static struct var *
  2125. setvareq(char *s, int flags)
  2126. {
  2127. struct var *vp, **vpp;
  2128. vpp = hashvar(s);
  2129. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2130. vpp = findvar(vpp, s);
  2131. vp = *vpp;
  2132. if (vp) {
  2133. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2134. const char *n;
  2135. if (flags & VNOSAVE)
  2136. free(s);
  2137. n = vp->var_text;
  2138. exitstatus = 1;
  2139. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2140. }
  2141. if (flags & VNOSET)
  2142. goto out;
  2143. if (vp->var_func && !(flags & VNOFUNC))
  2144. vp->var_func(var_end(s));
  2145. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2146. free((char*)vp->var_text);
  2147. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2148. *vpp = vp->next;
  2149. free(vp);
  2150. out_free:
  2151. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2152. free(s);
  2153. goto out;
  2154. }
  2155. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2156. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2157. if (flags & VUNSET)
  2158. flags &= ~VDYNAMIC;
  2159. #endif
  2160. } else {
  2161. /* variable s is not found */
  2162. if (flags & VNOSET)
  2163. goto out;
  2164. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2165. goto out_free;
  2166. vp = ckzalloc(sizeof(*vp));
  2167. vp->next = *vpp;
  2168. /*vp->func = NULL; - ckzalloc did it */
  2169. *vpp = vp;
  2170. }
  2171. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2172. s = ckstrdup(s);
  2173. vp->var_text = s;
  2174. vp->flags = flags;
  2175. out:
  2176. return vp;
  2177. }
  2178. /*
  2179. * Set the value of a variable. The flags argument is ored with the
  2180. * flags of the variable. If val is NULL, the variable is unset.
  2181. */
  2182. static struct var *
  2183. setvar(const char *name, const char *val, int flags)
  2184. {
  2185. const char *q;
  2186. char *p;
  2187. char *nameeq;
  2188. size_t namelen;
  2189. size_t vallen;
  2190. struct var *vp;
  2191. q = endofname(name);
  2192. p = strchrnul(q, '=');
  2193. namelen = p - name;
  2194. if (!namelen || p != q)
  2195. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2196. vallen = 0;
  2197. if (val == NULL) {
  2198. flags |= VUNSET;
  2199. } else {
  2200. vallen = strlen(val);
  2201. }
  2202. INT_OFF;
  2203. nameeq = ckzalloc(namelen + vallen + 2);
  2204. p = mempcpy(nameeq, name, namelen);
  2205. if (val) {
  2206. *p++ = '=';
  2207. memcpy(p, val, vallen);
  2208. }
  2209. vp = setvareq(nameeq, flags | VNOSAVE);
  2210. INT_ON;
  2211. return vp;
  2212. }
  2213. static void FAST_FUNC
  2214. setvar0(const char *name, const char *val)
  2215. {
  2216. setvar(name, val, 0);
  2217. }
  2218. /*
  2219. * Unset the specified variable.
  2220. */
  2221. static void
  2222. unsetvar(const char *s)
  2223. {
  2224. setvar(s, NULL, 0);
  2225. }
  2226. /*
  2227. * Generate a list of variables satisfying the given conditions.
  2228. */
  2229. #if !ENABLE_FEATURE_SH_NOFORK
  2230. # define listvars(on, off, lp, end) listvars(on, off, end)
  2231. #endif
  2232. static char **
  2233. listvars(int on, int off, struct strlist *lp, char ***end)
  2234. {
  2235. struct var **vpp;
  2236. struct var *vp;
  2237. char **ep;
  2238. int mask;
  2239. STARTSTACKSTR(ep);
  2240. vpp = vartab;
  2241. mask = on | off;
  2242. do {
  2243. for (vp = *vpp; vp; vp = vp->next) {
  2244. if ((vp->flags & mask) == on) {
  2245. #if ENABLE_FEATURE_SH_NOFORK
  2246. /* If variable with the same name is both
  2247. * exported and temporarily set for a command:
  2248. * export ZVAR=5
  2249. * ZVAR=6 printenv
  2250. * then "ZVAR=6" will be both in vartab and
  2251. * lp lists. Do not pass it twice to printenv.
  2252. */
  2253. struct strlist *lp1 = lp;
  2254. while (lp1) {
  2255. if (strcmp(lp1->text, vp->var_text) == 0)
  2256. goto skip;
  2257. lp1 = lp1->next;
  2258. }
  2259. #endif
  2260. if (ep == stackstrend())
  2261. ep = growstackstr();
  2262. *ep++ = (char*)vp->var_text;
  2263. #if ENABLE_FEATURE_SH_NOFORK
  2264. skip: ;
  2265. #endif
  2266. }
  2267. }
  2268. } while (++vpp < vartab + VTABSIZE);
  2269. #if ENABLE_FEATURE_SH_NOFORK
  2270. while (lp) {
  2271. if (ep == stackstrend())
  2272. ep = growstackstr();
  2273. *ep++ = lp->text;
  2274. lp = lp->next;
  2275. }
  2276. #endif
  2277. if (ep == stackstrend())
  2278. ep = growstackstr();
  2279. if (end)
  2280. *end = ep;
  2281. *ep++ = NULL;
  2282. return grabstackstr(ep);
  2283. }
  2284. /* ============ Path search helper */
  2285. static const char *
  2286. legal_pathopt(const char *opt, const char *term, int magic)
  2287. {
  2288. switch (magic) {
  2289. case 0:
  2290. opt = NULL;
  2291. break;
  2292. case 1:
  2293. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2294. break;
  2295. default:
  2296. opt += strcspn(opt, term);
  2297. break;
  2298. }
  2299. if (opt && *opt == '%')
  2300. opt++;
  2301. return opt;
  2302. }
  2303. /*
  2304. * The variable path (passed by reference) should be set to the start
  2305. * of the path before the first call; padvance will update
  2306. * this value as it proceeds. Successive calls to padvance will return
  2307. * the possible path expansions in sequence. If an option (indicated by
  2308. * a percent sign) appears in the path entry then the global variable
  2309. * pathopt will be set to point to it; otherwise pathopt will be set to
  2310. * NULL.
  2311. *
  2312. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2313. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2314. * pathopt.
  2315. */
  2316. static const char *pathopt; /* set by padvance */
  2317. static int
  2318. padvance_magic(const char **path, const char *name, int magic)
  2319. {
  2320. const char *term = "%:";
  2321. const char *lpathopt;
  2322. const char *p;
  2323. char *q;
  2324. const char *start;
  2325. size_t qlen;
  2326. size_t len;
  2327. if (*path == NULL)
  2328. return -1;
  2329. lpathopt = NULL;
  2330. start = *path;
  2331. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2332. lpathopt = start + 1;
  2333. start = p;
  2334. term = ":";
  2335. }
  2336. len = strcspn(start, term);
  2337. p = start + len;
  2338. if (*p == '%') {
  2339. size_t extra = strchrnul(p, ':') - p;
  2340. if (legal_pathopt(p + 1, term, magic))
  2341. lpathopt = p + 1;
  2342. else
  2343. len += extra;
  2344. p += extra;
  2345. }
  2346. pathopt = lpathopt;
  2347. *path = *p == ':' ? p + 1 : NULL;
  2348. /* "2" is for '/' and '\0' */
  2349. qlen = len + strlen(name) + 2;
  2350. q = growstackto(qlen);
  2351. if (len) {
  2352. q = mempcpy(q, start, len);
  2353. *q++ = '/';
  2354. }
  2355. strcpy(q, name);
  2356. return qlen;
  2357. }
  2358. static int
  2359. padvance(const char **path, const char *name)
  2360. {
  2361. return padvance_magic(path, name, 1);
  2362. }
  2363. /* ============ Prompt */
  2364. static smallint doprompt; /* if set, prompt the user */
  2365. static smallint needprompt; /* true if interactive and at start of line */
  2366. #if ENABLE_FEATURE_EDITING
  2367. static line_input_t *line_input_state;
  2368. static const char *cmdedit_prompt;
  2369. static void
  2370. putprompt(const char *s)
  2371. {
  2372. if (ENABLE_ASH_EXPAND_PRMT) {
  2373. free((char*)cmdedit_prompt);
  2374. cmdedit_prompt = ckstrdup(s);
  2375. return;
  2376. }
  2377. cmdedit_prompt = s;
  2378. }
  2379. #else
  2380. static void
  2381. putprompt(const char *s)
  2382. {
  2383. out2str(s);
  2384. }
  2385. #endif
  2386. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2387. static const char *expandstr(const char *ps, int syntax_type);
  2388. /* Values for syntax param */
  2389. #define BASESYNTAX 0 /* not in quotes */
  2390. #define DQSYNTAX 1 /* in double quotes */
  2391. #define SQSYNTAX 2 /* in single quotes */
  2392. #define ARISYNTAX 3 /* in arithmetic */
  2393. #if ENABLE_ASH_EXPAND_PRMT
  2394. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2395. #endif
  2396. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2397. /*
  2398. * called by editline -- any expansions to the prompt should be added here.
  2399. */
  2400. static void
  2401. setprompt_if(smallint do_set, int whichprompt)
  2402. {
  2403. const char *prompt;
  2404. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2405. if (!do_set)
  2406. return;
  2407. needprompt = 0;
  2408. switch (whichprompt) {
  2409. case 1:
  2410. prompt = ps1val();
  2411. break;
  2412. case 2:
  2413. prompt = ps2val();
  2414. break;
  2415. default: /* 0 */
  2416. prompt = nullstr;
  2417. }
  2418. #if ENABLE_ASH_EXPAND_PRMT
  2419. pushstackmark(&smark, stackblocksize());
  2420. putprompt(expandstr(prompt, PSSYNTAX));
  2421. popstackmark(&smark);
  2422. #else
  2423. putprompt(prompt);
  2424. #endif
  2425. }
  2426. /* ============ The cd and pwd commands */
  2427. #define CD_PHYSICAL 1
  2428. #define CD_PRINT 2
  2429. static int
  2430. cdopt(void)
  2431. {
  2432. int flags = 0;
  2433. int i, j;
  2434. j = 'L';
  2435. while ((i = nextopt("LP")) != '\0') {
  2436. if (i != j) {
  2437. flags ^= CD_PHYSICAL;
  2438. j = i;
  2439. }
  2440. }
  2441. return flags;
  2442. }
  2443. /*
  2444. * Update curdir (the name of the current directory) in response to a
  2445. * cd command.
  2446. */
  2447. static const char *
  2448. updatepwd(const char *dir)
  2449. {
  2450. char *new;
  2451. char *p;
  2452. char *cdcomppath;
  2453. const char *lim;
  2454. cdcomppath = sstrdup(dir);
  2455. STARTSTACKSTR(new);
  2456. if (*dir != '/') {
  2457. if (curdir == nullstr)
  2458. return 0;
  2459. new = stack_putstr(curdir, new);
  2460. }
  2461. new = makestrspace(strlen(dir) + 2, new);
  2462. lim = (char *)stackblock() + 1;
  2463. if (*dir != '/') {
  2464. if (new[-1] != '/')
  2465. USTPUTC('/', new);
  2466. if (new > lim && *lim == '/')
  2467. lim++;
  2468. } else {
  2469. USTPUTC('/', new);
  2470. cdcomppath++;
  2471. if (dir[1] == '/' && dir[2] != '/') {
  2472. USTPUTC('/', new);
  2473. cdcomppath++;
  2474. lim++;
  2475. }
  2476. }
  2477. p = strtok_r(cdcomppath, "/", &cdcomppath);
  2478. while (p) {
  2479. switch (*p) {
  2480. case '.':
  2481. if (p[1] == '.' && p[2] == '\0') {
  2482. while (new > lim) {
  2483. STUNPUTC(new);
  2484. if (new[-1] == '/')
  2485. break;
  2486. }
  2487. break;
  2488. }
  2489. if (p[1] == '\0')
  2490. break;
  2491. /* fall through */
  2492. default:
  2493. new = stack_putstr(p, new);
  2494. USTPUTC('/', new);
  2495. }
  2496. p = strtok_r(NULL, "/", &cdcomppath);
  2497. }
  2498. if (new > lim)
  2499. STUNPUTC(new);
  2500. *new = 0;
  2501. return stackblock();
  2502. }
  2503. /*
  2504. * Find out what the current directory is. If we already know the current
  2505. * directory, this routine returns immediately.
  2506. */
  2507. static char *
  2508. getpwd(void)
  2509. {
  2510. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2511. return dir ? dir : nullstr;
  2512. }
  2513. static void
  2514. setpwd(const char *val, int setold)
  2515. {
  2516. char *oldcur, *dir;
  2517. oldcur = dir = curdir;
  2518. if (setold) {
  2519. setvar("OLDPWD", oldcur, VEXPORT);
  2520. }
  2521. INT_OFF;
  2522. if (physdir != nullstr) {
  2523. if (physdir != oldcur)
  2524. free(physdir);
  2525. physdir = nullstr;
  2526. }
  2527. if (oldcur == val || !val) {
  2528. char *s = getpwd();
  2529. physdir = s;
  2530. if (!val)
  2531. dir = s;
  2532. } else
  2533. dir = ckstrdup(val);
  2534. if (oldcur != dir && oldcur != nullstr) {
  2535. free(oldcur);
  2536. }
  2537. curdir = dir;
  2538. INT_ON;
  2539. setvar("PWD", dir, VEXPORT);
  2540. }
  2541. static void hashcd(void);
  2542. /*
  2543. * Actually do the chdir. We also call hashcd to let other routines
  2544. * know that the current directory has changed.
  2545. */
  2546. static int
  2547. docd(const char *dest, int flags)
  2548. {
  2549. const char *dir = NULL;
  2550. int err;
  2551. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2552. INT_OFF;
  2553. if (!(flags & CD_PHYSICAL)) {
  2554. dir = updatepwd(dest);
  2555. if (dir)
  2556. dest = dir;
  2557. }
  2558. err = chdir(dest);
  2559. if (err)
  2560. goto out;
  2561. setpwd(dir, 1);
  2562. hashcd();
  2563. out:
  2564. INT_ON;
  2565. return err;
  2566. }
  2567. static int FAST_FUNC
  2568. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2569. {
  2570. const char *dest;
  2571. const char *path;
  2572. const char *p;
  2573. char c;
  2574. struct stat statb;
  2575. int flags;
  2576. int len;
  2577. flags = cdopt();
  2578. dest = *argptr;
  2579. if (!dest)
  2580. dest = bltinlookup("HOME");
  2581. else if (LONE_DASH(dest)) {
  2582. dest = bltinlookup("OLDPWD");
  2583. flags |= CD_PRINT;
  2584. }
  2585. if (!dest)
  2586. dest = nullstr;
  2587. if (*dest == '/')
  2588. goto step6;
  2589. if (*dest == '.') {
  2590. c = dest[1];
  2591. dotdot:
  2592. switch (c) {
  2593. case '\0':
  2594. case '/':
  2595. goto step6;
  2596. case '.':
  2597. c = dest[2];
  2598. if (c != '.')
  2599. goto dotdot;
  2600. }
  2601. }
  2602. if (!*dest)
  2603. dest = ".";
  2604. path = bltinlookup("CDPATH");
  2605. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2606. c = *p;
  2607. p = stalloc(len);
  2608. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2609. if (c && c != ':')
  2610. flags |= CD_PRINT;
  2611. docd:
  2612. if (!docd(p, flags))
  2613. goto out;
  2614. goto err;
  2615. }
  2616. }
  2617. step6:
  2618. p = dest;
  2619. goto docd;
  2620. err:
  2621. ash_msg_and_raise_perror("can't cd to %s", dest);
  2622. /* NOTREACHED */
  2623. out:
  2624. if (flags & CD_PRINT)
  2625. out1fmt("%s\n", curdir);
  2626. return 0;
  2627. }
  2628. static int FAST_FUNC
  2629. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2630. {
  2631. int flags;
  2632. const char *dir = curdir;
  2633. flags = cdopt();
  2634. if (flags) {
  2635. if (physdir == nullstr)
  2636. setpwd(dir, 0);
  2637. dir = physdir;
  2638. }
  2639. out1fmt("%s\n", dir);
  2640. return 0;
  2641. }
  2642. /* ============ ... */
  2643. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2644. /* Syntax classes */
  2645. #define CWORD 0 /* character is nothing special */
  2646. #define CNL 1 /* newline character */
  2647. #define CBACK 2 /* a backslash character */
  2648. #define CSQUOTE 3 /* single quote */
  2649. #define CDQUOTE 4 /* double quote */
  2650. #define CENDQUOTE 5 /* a terminating quote */
  2651. #define CBQUOTE 6 /* backwards single quote */
  2652. #define CVAR 7 /* a dollar sign */
  2653. #define CENDVAR 8 /* a '}' character */
  2654. #define CLP 9 /* a left paren in arithmetic */
  2655. #define CRP 10 /* a right paren in arithmetic */
  2656. #define CENDFILE 11 /* end of file */
  2657. #define CCTL 12 /* like CWORD, except it must be escaped */
  2658. #define CSPCL 13 /* these terminate a word */
  2659. #define CIGN 14 /* character should be ignored */
  2660. #define PEOF 256
  2661. #if ENABLE_ASH_ALIAS
  2662. # define PEOA 257
  2663. #endif
  2664. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2665. #if ENABLE_FEATURE_SH_MATH
  2666. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2667. #else
  2668. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2669. #endif
  2670. static const uint16_t S_I_T[] ALIGN2 = {
  2671. #if ENABLE_ASH_ALIAS
  2672. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2673. #endif
  2674. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2675. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2676. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2677. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2678. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2679. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2680. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2681. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2682. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2683. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2684. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2685. #if !USE_SIT_FUNCTION
  2686. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2687. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2688. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2689. #endif
  2690. #undef SIT_ITEM
  2691. };
  2692. /* Constants below must match table above */
  2693. enum {
  2694. #if ENABLE_ASH_ALIAS
  2695. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2696. #endif
  2697. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2698. CNL_CNL_CNL_CNL , /* 2 */
  2699. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2700. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2701. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2702. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2703. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2704. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2705. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2706. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2707. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2708. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2709. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2710. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2711. };
  2712. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2713. * caller must ensure proper cast on it if c is *char_ptr!
  2714. */
  2715. #if USE_SIT_FUNCTION
  2716. static int
  2717. SIT(int c, int syntax)
  2718. {
  2719. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2720. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2721. /*
  2722. * This causes '/' to be prepended with CTLESC in dquoted string,
  2723. * making "./file"* treated incorrectly because we feed
  2724. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2725. * The "homegrown" glob implementation is okay with that,
  2726. * but glibc one isn't. With '/' always treated as CWORD,
  2727. * both work fine.
  2728. */
  2729. # if ENABLE_ASH_ALIAS
  2730. static const uint8_t syntax_index_table[] ALIGN1 = {
  2731. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2732. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2733. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2734. 11, 3 /* "}~" */
  2735. };
  2736. # else
  2737. static const uint8_t syntax_index_table[] ALIGN1 = {
  2738. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2739. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2740. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2741. 10, 2 /* "}~" */
  2742. };
  2743. # endif
  2744. const char *s;
  2745. int indx;
  2746. if (c == PEOF)
  2747. return CENDFILE;
  2748. # if ENABLE_ASH_ALIAS
  2749. if (c == PEOA)
  2750. indx = 0;
  2751. else
  2752. # endif
  2753. {
  2754. /* Cast is purely for paranoia here,
  2755. * just in case someone passed signed char to us */
  2756. if ((unsigned char)c >= CTL_FIRST
  2757. && (unsigned char)c <= CTL_LAST
  2758. ) {
  2759. return CCTL;
  2760. }
  2761. s = strchrnul(spec_symbls, c);
  2762. if (*s == '\0')
  2763. return CWORD;
  2764. indx = syntax_index_table[s - spec_symbls];
  2765. }
  2766. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2767. }
  2768. #else /* !USE_SIT_FUNCTION */
  2769. static const uint8_t syntax_index_table[] ALIGN1 = {
  2770. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2771. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2781. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2782. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2804. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2805. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2806. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2808. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2810. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2811. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2812. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2813. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2814. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2817. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2818. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2819. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2831. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2832. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2833. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2834. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2835. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2836. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2864. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2865. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2866. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2869. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2897. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2898. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2899. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2902. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2903. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2904. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2905. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2906. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2907. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2908. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2909. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3026. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3027. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3028. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3029. # if ENABLE_ASH_ALIAS
  3030. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3031. # endif
  3032. };
  3033. #if 1
  3034. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3035. #else /* debug version, caught one signed char bug */
  3036. # define SIT(c, syntax) \
  3037. ({ \
  3038. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3039. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3040. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3041. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3042. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3043. })
  3044. #endif
  3045. #endif /* !USE_SIT_FUNCTION */
  3046. /* ============ Alias handling */
  3047. #if ENABLE_ASH_ALIAS
  3048. #define ALIASINUSE 1
  3049. #define ALIASDEAD 2
  3050. struct alias {
  3051. struct alias *next;
  3052. char *name;
  3053. char *val;
  3054. int flag;
  3055. };
  3056. static struct alias **atab; // [ATABSIZE];
  3057. #define INIT_G_alias() do { \
  3058. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3059. } while (0)
  3060. static struct alias **
  3061. __lookupalias(const char *name)
  3062. {
  3063. unsigned int hashval;
  3064. struct alias **app;
  3065. const char *p;
  3066. unsigned int ch;
  3067. p = name;
  3068. ch = (unsigned char)*p;
  3069. hashval = ch << 4;
  3070. while (ch) {
  3071. hashval += ch;
  3072. ch = (unsigned char)*++p;
  3073. }
  3074. app = &atab[hashval % ATABSIZE];
  3075. for (; *app; app = &(*app)->next) {
  3076. if (strcmp(name, (*app)->name) == 0) {
  3077. break;
  3078. }
  3079. }
  3080. return app;
  3081. }
  3082. static struct alias *
  3083. lookupalias(const char *name, int check)
  3084. {
  3085. struct alias *ap = *__lookupalias(name);
  3086. if (check && ap && (ap->flag & ALIASINUSE))
  3087. return NULL;
  3088. return ap;
  3089. }
  3090. static struct alias *
  3091. freealias(struct alias *ap)
  3092. {
  3093. struct alias *next;
  3094. if (ap->flag & ALIASINUSE) {
  3095. ap->flag |= ALIASDEAD;
  3096. return ap;
  3097. }
  3098. next = ap->next;
  3099. free(ap->name);
  3100. free(ap->val);
  3101. free(ap);
  3102. return next;
  3103. }
  3104. static void
  3105. setalias(const char *name, const char *val)
  3106. {
  3107. struct alias *ap, **app;
  3108. app = __lookupalias(name);
  3109. ap = *app;
  3110. INT_OFF;
  3111. if (ap) {
  3112. if (!(ap->flag & ALIASINUSE)) {
  3113. free(ap->val);
  3114. }
  3115. ap->val = ckstrdup(val);
  3116. ap->flag &= ~ALIASDEAD;
  3117. } else {
  3118. /* not found */
  3119. ap = ckzalloc(sizeof(struct alias));
  3120. ap->name = ckstrdup(name);
  3121. ap->val = ckstrdup(val);
  3122. /*ap->flag = 0; - ckzalloc did it */
  3123. /*ap->next = NULL;*/
  3124. *app = ap;
  3125. }
  3126. INT_ON;
  3127. }
  3128. static int
  3129. unalias(const char *name)
  3130. {
  3131. struct alias **app;
  3132. app = __lookupalias(name);
  3133. if (*app) {
  3134. INT_OFF;
  3135. *app = freealias(*app);
  3136. INT_ON;
  3137. return 0;
  3138. }
  3139. return 1;
  3140. }
  3141. static void
  3142. rmaliases(void)
  3143. {
  3144. struct alias *ap, **app;
  3145. int i;
  3146. INT_OFF;
  3147. for (i = 0; i < ATABSIZE; i++) {
  3148. app = &atab[i];
  3149. for (ap = *app; ap; ap = *app) {
  3150. *app = freealias(*app);
  3151. if (ap == *app) {
  3152. app = &ap->next;
  3153. }
  3154. }
  3155. }
  3156. INT_ON;
  3157. }
  3158. static void
  3159. printalias(const struct alias *ap)
  3160. {
  3161. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3162. }
  3163. /*
  3164. * TODO - sort output
  3165. */
  3166. static int FAST_FUNC
  3167. aliascmd(int argc UNUSED_PARAM, char **argv)
  3168. {
  3169. char *n, *v;
  3170. int ret = 0;
  3171. struct alias *ap;
  3172. if (!argv[1]) {
  3173. int i;
  3174. for (i = 0; i < ATABSIZE; i++) {
  3175. for (ap = atab[i]; ap; ap = ap->next) {
  3176. printalias(ap);
  3177. }
  3178. }
  3179. return 0;
  3180. }
  3181. while ((n = *++argv) != NULL) {
  3182. v = strchr(n+1, '=');
  3183. if (v == NULL) { /* n+1: funny ksh stuff */
  3184. ap = *__lookupalias(n);
  3185. if (ap == NULL) {
  3186. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3187. ret = 1;
  3188. } else
  3189. printalias(ap);
  3190. } else {
  3191. *v++ = '\0';
  3192. setalias(n, v);
  3193. }
  3194. }
  3195. return ret;
  3196. }
  3197. static int FAST_FUNC
  3198. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3199. {
  3200. int i;
  3201. while (nextopt("a") != '\0') {
  3202. rmaliases();
  3203. return 0;
  3204. }
  3205. for (i = 0; *argptr; argptr++) {
  3206. if (unalias(*argptr)) {
  3207. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3208. i = 1;
  3209. }
  3210. }
  3211. return i;
  3212. }
  3213. #endif /* ASH_ALIAS */
  3214. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3215. #define FORK_FG 0
  3216. #define FORK_BG 1
  3217. #define FORK_NOJOB 2
  3218. /* mode flags for showjob(s) */
  3219. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3220. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3221. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3222. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3223. /*
  3224. * A job structure contains information about a job. A job is either a
  3225. * single process or a set of processes contained in a pipeline. In the
  3226. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3227. * array of pids.
  3228. */
  3229. struct procstat {
  3230. pid_t ps_pid; /* process id */
  3231. int ps_status; /* last process status from wait() */
  3232. char *ps_cmd; /* text of command being run */
  3233. };
  3234. struct job {
  3235. struct procstat ps0; /* status of process */
  3236. struct procstat *ps; /* status of processes when more than one */
  3237. #if JOBS
  3238. int stopstatus; /* status of a stopped job */
  3239. #endif
  3240. unsigned nprocs; /* number of processes */
  3241. #define JOBRUNNING 0 /* at least one proc running */
  3242. #define JOBSTOPPED 1 /* all procs are stopped */
  3243. #define JOBDONE 2 /* all procs are completed */
  3244. unsigned
  3245. state: 8,
  3246. #if JOBS
  3247. sigint: 1, /* job was killed by SIGINT */
  3248. jobctl: 1, /* job running under job control */
  3249. #endif
  3250. waited: 1, /* true if this entry has been waited for */
  3251. used: 1, /* true if this entry is in used */
  3252. changed: 1; /* true if status has changed */
  3253. struct job *prev_job; /* previous job */
  3254. };
  3255. static struct job *makejob(/*union node *,*/ int);
  3256. static int forkshell(struct job *, union node *, int);
  3257. static int waitforjob(struct job *);
  3258. #if !JOBS
  3259. enum { doing_jobctl = 0 };
  3260. #define setjobctl(on) do {} while (0)
  3261. #else
  3262. static smallint doing_jobctl; //references:8
  3263. static void setjobctl(int);
  3264. #endif
  3265. /*
  3266. * Ignore a signal.
  3267. */
  3268. static void
  3269. ignoresig(int signo)
  3270. {
  3271. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3272. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3273. /* No, need to do it */
  3274. signal(signo, SIG_IGN);
  3275. }
  3276. sigmode[signo - 1] = S_HARD_IGN;
  3277. }
  3278. /*
  3279. * Only one usage site - in setsignal()
  3280. */
  3281. static void
  3282. signal_handler(int signo)
  3283. {
  3284. if (signo == SIGCHLD) {
  3285. got_sigchld = 1;
  3286. if (!trap[SIGCHLD])
  3287. return;
  3288. }
  3289. gotsig[signo - 1] = 1;
  3290. pending_sig = signo;
  3291. if (signo == SIGINT && !trap[SIGINT]) {
  3292. if (!suppress_int) {
  3293. pending_sig = 0;
  3294. raise_interrupt(); /* does not return */
  3295. }
  3296. pending_int = 1;
  3297. }
  3298. }
  3299. /*
  3300. * Set the signal handler for the specified signal. The routine figures
  3301. * out what it should be set to.
  3302. */
  3303. static void
  3304. setsignal(int signo)
  3305. {
  3306. char *t;
  3307. char cur_act, new_act;
  3308. struct sigaction act;
  3309. t = trap[signo];
  3310. new_act = S_DFL;
  3311. if (t != NULL) { /* trap for this sig is set */
  3312. new_act = S_CATCH;
  3313. if (t[0] == '\0') /* trap is "": ignore this sig */
  3314. new_act = S_IGN;
  3315. }
  3316. if (rootshell && new_act == S_DFL) {
  3317. switch (signo) {
  3318. case SIGINT:
  3319. if (iflag || minusc || sflag == 0)
  3320. new_act = S_CATCH;
  3321. break;
  3322. case SIGQUIT:
  3323. #if DEBUG
  3324. if (debug)
  3325. break;
  3326. #endif
  3327. /* man bash:
  3328. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3329. * commands run by bash have signal handlers
  3330. * set to the values inherited by the shell
  3331. * from its parent". */
  3332. new_act = S_IGN;
  3333. break;
  3334. case SIGTERM:
  3335. if (iflag)
  3336. new_act = S_IGN;
  3337. break;
  3338. #if JOBS
  3339. case SIGTSTP:
  3340. case SIGTTOU:
  3341. if (mflag)
  3342. new_act = S_IGN;
  3343. break;
  3344. #endif
  3345. }
  3346. }
  3347. /* if !rootshell, we reset SIGQUIT to DFL,
  3348. * whereas we have to restore it to what shell got on entry.
  3349. * This is handled by the fact that if signal was IGNored on entry,
  3350. * then cur_act is S_HARD_IGN and we never change its sigaction
  3351. * (see code below).
  3352. */
  3353. if (signo == SIGCHLD)
  3354. new_act = S_CATCH;
  3355. t = &sigmode[signo - 1];
  3356. cur_act = *t;
  3357. if (cur_act == 0) {
  3358. /* current setting is not yet known */
  3359. if (sigaction(signo, NULL, &act)) {
  3360. /* pretend it worked; maybe we should give a warning,
  3361. * but other shells don't. We don't alter sigmode,
  3362. * so we retry every time.
  3363. * btw, in Linux it never fails. --vda */
  3364. return;
  3365. }
  3366. if (act.sa_handler == SIG_IGN) {
  3367. cur_act = S_HARD_IGN;
  3368. if (mflag
  3369. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3370. ) {
  3371. cur_act = S_IGN; /* don't hard ignore these */
  3372. }
  3373. }
  3374. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3375. /* installing SIG_DFL over SIG_DFL is a no-op */
  3376. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3377. *t = S_DFL;
  3378. return;
  3379. }
  3380. }
  3381. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3382. return;
  3383. *t = new_act;
  3384. act.sa_handler = SIG_DFL;
  3385. switch (new_act) {
  3386. case S_CATCH:
  3387. act.sa_handler = signal_handler;
  3388. break;
  3389. case S_IGN:
  3390. act.sa_handler = SIG_IGN;
  3391. break;
  3392. }
  3393. /* flags and mask matter only if !DFL and !IGN, but we do it
  3394. * for all cases for more deterministic behavior:
  3395. */
  3396. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3397. sigfillset(&act.sa_mask);
  3398. sigaction_set(signo, &act);
  3399. }
  3400. /* mode flags for set_curjob */
  3401. #define CUR_DELETE 2
  3402. #define CUR_RUNNING 1
  3403. #define CUR_STOPPED 0
  3404. #if JOBS
  3405. /* pgrp of shell on invocation */
  3406. static int initialpgrp; //references:2
  3407. static int ttyfd = -1; //5
  3408. #endif
  3409. /* array of jobs */
  3410. static struct job *jobtab; //5
  3411. /* size of array */
  3412. static unsigned njobs; //4
  3413. /* current job */
  3414. static struct job *curjob; //lots
  3415. #if 0
  3416. /* Bash has a feature: it restores termios after a successful wait for
  3417. * a foreground job which had at least one stopped or sigkilled member.
  3418. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3419. * properly restoring tty state. Should we do this too?
  3420. * A reproducer: ^Z an interactive python:
  3421. *
  3422. * # python
  3423. * Python 2.7.12 (...)
  3424. * >>> ^Z
  3425. * { python leaves tty in -icanon -echo state. We do survive that... }
  3426. * [1]+ Stopped python
  3427. * { ...however, next program (python #2) does not survive it well: }
  3428. * # python
  3429. * Python 2.7.12 (...)
  3430. * >>> Traceback (most recent call last):
  3431. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3432. * File "<stdin>", line 1, in <module>
  3433. * NameError: name 'qwerty' is not defined
  3434. *
  3435. * The implementation below is modeled on bash code and seems to work.
  3436. * However, I'm not sure we should do this. For one: what if I'd fg
  3437. * the stopped python instead? It'll be confused by "restored" tty state.
  3438. */
  3439. static struct termios shell_tty_info;
  3440. static void
  3441. get_tty_state(void)
  3442. {
  3443. if (rootshell && ttyfd >= 0)
  3444. tcgetattr(ttyfd, &shell_tty_info);
  3445. }
  3446. static void
  3447. set_tty_state(void)
  3448. {
  3449. /* if (rootshell) - caller ensures this */
  3450. if (ttyfd >= 0)
  3451. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3452. }
  3453. static int
  3454. job_signal_status(struct job *jp)
  3455. {
  3456. int status;
  3457. unsigned i;
  3458. struct procstat *ps = jp->ps;
  3459. for (i = 0; i < jp->nprocs; i++) {
  3460. status = ps[i].ps_status;
  3461. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3462. return status;
  3463. }
  3464. return 0;
  3465. }
  3466. static void
  3467. restore_tty_if_stopped_or_signaled(struct job *jp)
  3468. {
  3469. //TODO: check what happens if we come from waitforjob() in expbackq()
  3470. if (rootshell) {
  3471. int s = job_signal_status(jp);
  3472. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3473. set_tty_state();
  3474. }
  3475. }
  3476. #else
  3477. # define get_tty_state() ((void)0)
  3478. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3479. #endif
  3480. static void
  3481. set_curjob(struct job *jp, unsigned mode)
  3482. {
  3483. struct job *jp1;
  3484. struct job **jpp, **curp;
  3485. /* first remove from list */
  3486. jpp = curp = &curjob;
  3487. while (1) {
  3488. jp1 = *jpp;
  3489. if (jp1 == jp)
  3490. break;
  3491. jpp = &jp1->prev_job;
  3492. }
  3493. *jpp = jp1->prev_job;
  3494. /* Then re-insert in correct position */
  3495. jpp = curp;
  3496. switch (mode) {
  3497. default:
  3498. #if DEBUG
  3499. abort();
  3500. #endif
  3501. case CUR_DELETE:
  3502. /* job being deleted */
  3503. break;
  3504. case CUR_RUNNING:
  3505. /* newly created job or backgrounded job,
  3506. * put after all stopped jobs.
  3507. */
  3508. while (1) {
  3509. jp1 = *jpp;
  3510. #if JOBS
  3511. if (!jp1 || jp1->state != JOBSTOPPED)
  3512. #endif
  3513. break;
  3514. jpp = &jp1->prev_job;
  3515. }
  3516. /* FALLTHROUGH */
  3517. #if JOBS
  3518. case CUR_STOPPED:
  3519. #endif
  3520. /* newly stopped job - becomes curjob */
  3521. jp->prev_job = *jpp;
  3522. *jpp = jp;
  3523. break;
  3524. }
  3525. }
  3526. #if JOBS || DEBUG
  3527. static int
  3528. jobno(const struct job *jp)
  3529. {
  3530. return jp - jobtab + 1;
  3531. }
  3532. #endif
  3533. /*
  3534. * Convert a job name to a job structure.
  3535. */
  3536. #if !JOBS
  3537. #define getjob(name, getctl) getjob(name)
  3538. #endif
  3539. static struct job *
  3540. getjob(const char *name, int getctl)
  3541. {
  3542. struct job *jp;
  3543. struct job *found;
  3544. const char *err_msg = "%s: no such job";
  3545. unsigned num;
  3546. int c;
  3547. const char *p;
  3548. char *(*match)(const char *, const char *);
  3549. jp = curjob;
  3550. p = name;
  3551. if (!p)
  3552. goto currentjob;
  3553. if (*p != '%')
  3554. goto err;
  3555. c = *++p;
  3556. if (!c)
  3557. goto currentjob;
  3558. if (!p[1]) {
  3559. if (c == '+' || c == '%') {
  3560. currentjob:
  3561. err_msg = "No current job";
  3562. goto check;
  3563. }
  3564. if (c == '-') {
  3565. if (jp)
  3566. jp = jp->prev_job;
  3567. err_msg = "No previous job";
  3568. check:
  3569. if (!jp)
  3570. goto err;
  3571. goto gotit;
  3572. }
  3573. }
  3574. if (is_number(p)) {
  3575. num = atoi(p);
  3576. if (num > 0 && num <= njobs) {
  3577. jp = jobtab + num - 1;
  3578. if (jp->used)
  3579. goto gotit;
  3580. goto err;
  3581. }
  3582. }
  3583. match = prefix;
  3584. if (*p == '?') {
  3585. match = strstr;
  3586. p++;
  3587. }
  3588. found = NULL;
  3589. while (jp) {
  3590. if (match(jp->ps[0].ps_cmd, p)) {
  3591. if (found)
  3592. goto err;
  3593. found = jp;
  3594. err_msg = "%s: ambiguous";
  3595. }
  3596. jp = jp->prev_job;
  3597. }
  3598. if (!found)
  3599. goto err;
  3600. jp = found;
  3601. gotit:
  3602. #if JOBS
  3603. err_msg = "job %s not created under job control";
  3604. if (getctl && jp->jobctl == 0)
  3605. goto err;
  3606. #endif
  3607. return jp;
  3608. err:
  3609. ash_msg_and_raise_error(err_msg, name);
  3610. }
  3611. /*
  3612. * Mark a job structure as unused.
  3613. */
  3614. static void
  3615. freejob(struct job *jp)
  3616. {
  3617. struct procstat *ps;
  3618. int i;
  3619. INT_OFF;
  3620. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3621. if (ps->ps_cmd != nullstr)
  3622. free(ps->ps_cmd);
  3623. }
  3624. if (jp->ps != &jp->ps0)
  3625. free(jp->ps);
  3626. jp->used = 0;
  3627. set_curjob(jp, CUR_DELETE);
  3628. INT_ON;
  3629. }
  3630. #if JOBS
  3631. static void
  3632. xtcsetpgrp(int fd, pid_t pgrp)
  3633. {
  3634. if (tcsetpgrp(fd, pgrp))
  3635. ash_msg_and_raise_perror("can't set tty process group");
  3636. }
  3637. /*
  3638. * Turn job control on and off.
  3639. *
  3640. * Note: This code assumes that the third arg to ioctl is a character
  3641. * pointer, which is true on Berkeley systems but not System V. Since
  3642. * System V doesn't have job control yet, this isn't a problem now.
  3643. *
  3644. * Called with interrupts off.
  3645. */
  3646. static void
  3647. setjobctl(int on)
  3648. {
  3649. int fd;
  3650. int pgrp;
  3651. if (on == doing_jobctl || rootshell == 0)
  3652. return;
  3653. if (on) {
  3654. int ofd;
  3655. ofd = fd = open(_PATH_TTY, O_RDWR);
  3656. if (fd < 0) {
  3657. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3658. * That sometimes helps to acquire controlling tty.
  3659. * Obviously, a workaround for bugs when someone
  3660. * failed to provide a controlling tty to bash! :) */
  3661. fd = 2;
  3662. while (!isatty(fd))
  3663. if (--fd < 0)
  3664. goto out;
  3665. }
  3666. /* fd is a tty at this point */
  3667. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3668. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3669. close(ofd);
  3670. if (fd < 0)
  3671. goto out; /* F_DUPFD failed */
  3672. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3673. close_on_exec_on(fd);
  3674. while (1) { /* while we are in the background */
  3675. pgrp = tcgetpgrp(fd);
  3676. if (pgrp < 0) {
  3677. out:
  3678. ash_msg("can't access tty; job control turned off");
  3679. mflag = on = 0;
  3680. goto close;
  3681. }
  3682. if (pgrp == getpgrp())
  3683. break;
  3684. killpg(0, SIGTTIN);
  3685. }
  3686. initialpgrp = pgrp;
  3687. setsignal(SIGTSTP);
  3688. setsignal(SIGTTOU);
  3689. setsignal(SIGTTIN);
  3690. pgrp = rootpid;
  3691. setpgid(0, pgrp);
  3692. xtcsetpgrp(fd, pgrp);
  3693. } else {
  3694. /* turning job control off */
  3695. fd = ttyfd;
  3696. pgrp = initialpgrp;
  3697. /* was xtcsetpgrp, but this can make exiting ash
  3698. * loop forever if pty is already deleted */
  3699. tcsetpgrp(fd, pgrp);
  3700. setpgid(0, pgrp);
  3701. setsignal(SIGTSTP);
  3702. setsignal(SIGTTOU);
  3703. setsignal(SIGTTIN);
  3704. close:
  3705. if (fd >= 0)
  3706. close(fd);
  3707. fd = -1;
  3708. }
  3709. ttyfd = fd;
  3710. doing_jobctl = on;
  3711. }
  3712. static int FAST_FUNC
  3713. killcmd(int argc, char **argv)
  3714. {
  3715. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3716. int i = 1;
  3717. do {
  3718. if (argv[i][0] == '%') {
  3719. /*
  3720. * "kill %N" - job kill
  3721. * Converting to pgrp / pid kill
  3722. */
  3723. struct job *jp;
  3724. char *dst;
  3725. int j, n;
  3726. jp = getjob(argv[i], 0);
  3727. /*
  3728. * In jobs started under job control, we signal
  3729. * entire process group by kill -PGRP_ID.
  3730. * This happens, f.e., in interactive shell.
  3731. *
  3732. * Otherwise, we signal each child via
  3733. * kill PID1 PID2 PID3.
  3734. * Testcases:
  3735. * sh -c 'sleep 1|sleep 1 & kill %1'
  3736. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3737. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3738. */
  3739. n = jp->nprocs; /* can't be 0 (I hope) */
  3740. if (jp->jobctl)
  3741. n = 1;
  3742. dst = alloca(n * sizeof(int)*4);
  3743. argv[i] = dst;
  3744. for (j = 0; j < n; j++) {
  3745. struct procstat *ps = &jp->ps[j];
  3746. /* Skip non-running and not-stopped members
  3747. * (i.e. dead members) of the job
  3748. */
  3749. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3750. continue;
  3751. /*
  3752. * kill_main has matching code to expect
  3753. * leading space. Needed to not confuse
  3754. * negative pids with "kill -SIGNAL_NO" syntax
  3755. */
  3756. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3757. }
  3758. *dst = '\0';
  3759. }
  3760. } while (argv[++i]);
  3761. }
  3762. return kill_main(argc, argv);
  3763. }
  3764. static void
  3765. showpipe(struct job *jp /*, FILE *out*/)
  3766. {
  3767. struct procstat *ps;
  3768. struct procstat *psend;
  3769. psend = jp->ps + jp->nprocs;
  3770. for (ps = jp->ps + 1; ps < psend; ps++)
  3771. printf(" | %s", ps->ps_cmd);
  3772. newline_and_flush(stdout);
  3773. flush_stdout_stderr();
  3774. }
  3775. static int
  3776. restartjob(struct job *jp, int mode)
  3777. {
  3778. struct procstat *ps;
  3779. int i;
  3780. int status;
  3781. pid_t pgid;
  3782. INT_OFF;
  3783. if (jp->state == JOBDONE)
  3784. goto out;
  3785. jp->state = JOBRUNNING;
  3786. pgid = jp->ps[0].ps_pid;
  3787. if (mode == FORK_FG) {
  3788. get_tty_state();
  3789. xtcsetpgrp(ttyfd, pgid);
  3790. }
  3791. killpg(pgid, SIGCONT);
  3792. ps = jp->ps;
  3793. i = jp->nprocs;
  3794. do {
  3795. if (WIFSTOPPED(ps->ps_status)) {
  3796. ps->ps_status = -1;
  3797. }
  3798. ps++;
  3799. } while (--i);
  3800. out:
  3801. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3802. INT_ON;
  3803. return status;
  3804. }
  3805. static int FAST_FUNC
  3806. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3807. {
  3808. struct job *jp;
  3809. int mode;
  3810. int retval;
  3811. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3812. nextopt(nullstr);
  3813. argv = argptr;
  3814. do {
  3815. jp = getjob(*argv, 1);
  3816. if (mode == FORK_BG) {
  3817. set_curjob(jp, CUR_RUNNING);
  3818. printf("[%d] ", jobno(jp));
  3819. }
  3820. out1str(jp->ps[0].ps_cmd);
  3821. showpipe(jp /*, stdout*/);
  3822. retval = restartjob(jp, mode);
  3823. } while (*argv && *++argv);
  3824. return retval;
  3825. }
  3826. #endif
  3827. static int
  3828. sprint_status48(char *os, int status, int sigonly)
  3829. {
  3830. char *s = os;
  3831. int st;
  3832. if (!WIFEXITED(status)) {
  3833. #if JOBS
  3834. if (WIFSTOPPED(status))
  3835. st = WSTOPSIG(status);
  3836. else
  3837. #endif
  3838. st = WTERMSIG(status);
  3839. if (sigonly) {
  3840. if (st == SIGINT || st == SIGPIPE)
  3841. goto out;
  3842. #if JOBS
  3843. if (WIFSTOPPED(status))
  3844. goto out;
  3845. #endif
  3846. }
  3847. st &= 0x7f;
  3848. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3849. //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
  3850. s += fmtstr(s, 32, strsignal(st));
  3851. if (WCOREDUMP(status)) {
  3852. s = stpcpy(s, " (core dumped)");
  3853. }
  3854. } else if (!sigonly) {
  3855. st = WEXITSTATUS(status);
  3856. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3857. }
  3858. out:
  3859. return s - os;
  3860. }
  3861. #define DOWAIT_NONBLOCK 0
  3862. #define DOWAIT_BLOCK 1
  3863. #define DOWAIT_BLOCK_OR_SIG 2
  3864. #if BASH_WAIT_N
  3865. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3866. #endif
  3867. static int
  3868. waitproc(int block, int *status)
  3869. {
  3870. sigset_t oldmask;
  3871. int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
  3872. int err;
  3873. #if JOBS
  3874. if (doing_jobctl)
  3875. flags |= WUNTRACED;
  3876. #endif
  3877. do {
  3878. got_sigchld = 0;
  3879. do
  3880. err = waitpid(-1, status, flags);
  3881. while (err < 0 && errno == EINTR);
  3882. if (err || (err = -!block))
  3883. break;
  3884. sigfillset(&oldmask);
  3885. sigprocmask2(SIG_SETMASK, &oldmask); /* mask is updated */
  3886. while (!got_sigchld && !pending_sig)
  3887. sigsuspend(&oldmask);
  3888. sigprocmask(SIG_SETMASK, &oldmask, NULL);
  3889. //simpler, but unsafe: a signal can set pending_sig after check, but before pause():
  3890. //while (!got_sigchld && !pending_sig)
  3891. // pause();
  3892. } while (got_sigchld);
  3893. return err;
  3894. }
  3895. static int
  3896. waitone(int block, struct job *job)
  3897. {
  3898. int pid;
  3899. int status;
  3900. struct job *jp;
  3901. struct job *thisjob = NULL;
  3902. #if BASH_WAIT_N
  3903. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3904. block = (block & ~DOWAIT_JOBSTATUS);
  3905. #endif
  3906. TRACE(("dowait(0x%x) called\n", block));
  3907. /* It's wrong to call waitpid() outside of INT_OFF region:
  3908. * signal can arrive just after syscall return and handler can
  3909. * longjmp away, losing stop/exit notification processing.
  3910. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3911. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3912. *
  3913. * However, for "wait" builtin it is wrong to simply call waitpid()
  3914. * in INT_OFF region: "wait" needs to wait for any running job
  3915. * to change state, but should exit on any trap too.
  3916. * In INT_OFF region, a signal just before syscall entry can set
  3917. * pending_sig variables, but we can't check them, and we would
  3918. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3919. *
  3920. * Because of this, we run inside INT_OFF, but use a special routine
  3921. * which combines waitpid() and sigsuspend().
  3922. * This is the reason why we need to have a handler for SIGCHLD:
  3923. * SIG_DFL handler does not wake sigsuspend().
  3924. */
  3925. INT_OFF;
  3926. pid = waitproc(block, &status);
  3927. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3928. if (pid <= 0)
  3929. goto out;
  3930. for (jp = curjob; jp; jp = jp->prev_job) {
  3931. int jobstate;
  3932. struct procstat *ps;
  3933. struct procstat *psend;
  3934. if (jp->state == JOBDONE)
  3935. continue;
  3936. jobstate = JOBDONE;
  3937. ps = jp->ps;
  3938. psend = ps + jp->nprocs;
  3939. do {
  3940. if (ps->ps_pid == pid) {
  3941. TRACE(("Job %d: changing status of proc %d "
  3942. "from 0x%x to 0x%x\n",
  3943. jobno(jp), pid, ps->ps_status, status));
  3944. ps->ps_status = status;
  3945. thisjob = jp;
  3946. }
  3947. if (ps->ps_status == -1)
  3948. jobstate = JOBRUNNING;
  3949. #if JOBS
  3950. if (jobstate == JOBRUNNING)
  3951. continue;
  3952. if (WIFSTOPPED(ps->ps_status)) {
  3953. jp->stopstatus = ps->ps_status;
  3954. jobstate = JOBSTOPPED;
  3955. }
  3956. #endif
  3957. } while (++ps < psend);
  3958. if (!thisjob)
  3959. continue;
  3960. /* Found the job where one of its processes changed its state.
  3961. * Is there at least one live and running process in this job? */
  3962. if (jobstate != JOBRUNNING) {
  3963. /* No. All live processes in the job are stopped
  3964. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3965. */
  3966. thisjob->changed = 1;
  3967. if (thisjob->state != jobstate) {
  3968. TRACE(("Job %d: changing state from %d to %d\n",
  3969. jobno(thisjob), thisjob->state, jobstate));
  3970. thisjob->state = jobstate;
  3971. #if JOBS
  3972. if (jobstate == JOBSTOPPED)
  3973. set_curjob(thisjob, CUR_STOPPED);
  3974. #endif
  3975. }
  3976. }
  3977. goto out;
  3978. }
  3979. /* The process wasn't found in job list */
  3980. out:
  3981. INT_ON;
  3982. #if BASH_WAIT_N
  3983. if (want_jobexitstatus) {
  3984. pid = -1;
  3985. if (thisjob && thisjob->state == JOBDONE)
  3986. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  3987. }
  3988. #endif
  3989. if (thisjob && thisjob == job) {
  3990. char s[48 + 1];
  3991. int len;
  3992. len = sprint_status48(s, status, 1);
  3993. if (len) {
  3994. s[len] = '\n';
  3995. s[len + 1] = '\0';
  3996. out2str(s);
  3997. }
  3998. }
  3999. return pid;
  4000. }
  4001. static int
  4002. dowait(int block, struct job *jp)
  4003. {
  4004. smallint gotchld = *(volatile smallint *)&got_sigchld;
  4005. int rpid;
  4006. int pid;
  4007. if (jp && jp->state != JOBRUNNING)
  4008. block = DOWAIT_NONBLOCK;
  4009. if (block == DOWAIT_NONBLOCK && !gotchld)
  4010. return 1;
  4011. rpid = 1;
  4012. do {
  4013. pid = waitone(block, jp);
  4014. rpid &= !!pid;
  4015. if (!pid || (jp && jp->state != JOBRUNNING))
  4016. block = DOWAIT_NONBLOCK;
  4017. } while (pid >= 0);
  4018. return rpid;
  4019. }
  4020. #if JOBS
  4021. static void
  4022. showjob(struct job *jp, int mode)
  4023. {
  4024. struct procstat *ps;
  4025. struct procstat *psend;
  4026. int col;
  4027. int indent_col;
  4028. char s[16 + 16 + 48];
  4029. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4030. ps = jp->ps;
  4031. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4032. /* just output process (group) id of pipeline */
  4033. fprintf(out, "%d\n", ps->ps_pid);
  4034. return;
  4035. }
  4036. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4037. indent_col = col;
  4038. if (jp == curjob)
  4039. s[col - 3] = '+';
  4040. else if (curjob && jp == curjob->prev_job)
  4041. s[col - 3] = '-';
  4042. if (mode & SHOW_PIDS)
  4043. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4044. psend = ps + jp->nprocs;
  4045. if (jp->state == JOBRUNNING) {
  4046. strcpy(s + col, "Running");
  4047. col += sizeof("Running") - 1;
  4048. } else {
  4049. int status = psend[-1].ps_status;
  4050. if (jp->state == JOBSTOPPED)
  4051. status = jp->stopstatus;
  4052. col += sprint_status48(s + col, status, 0);
  4053. }
  4054. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4055. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4056. * or prints several "PID | <cmdN>" lines,
  4057. * depending on SHOW_PIDS bit.
  4058. * We do not print status of individual processes
  4059. * between PID and <cmdN>. bash does it, but not very well:
  4060. * first line shows overall job status, not process status,
  4061. * making it impossible to know 1st process status.
  4062. */
  4063. goto start;
  4064. do {
  4065. /* for each process */
  4066. s[0] = '\0';
  4067. col = 33;
  4068. if (mode & SHOW_PIDS)
  4069. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4070. start:
  4071. fprintf(out, "%s%*c%s%s",
  4072. s,
  4073. 33 - col >= 0 ? 33 - col : 0, ' ',
  4074. ps == jp->ps ? "" : "| ",
  4075. ps->ps_cmd
  4076. );
  4077. } while (++ps != psend);
  4078. newline_and_flush(out);
  4079. jp->changed = 0;
  4080. if (jp->state == JOBDONE) {
  4081. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4082. freejob(jp);
  4083. }
  4084. }
  4085. /*
  4086. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4087. * statuses have changed since the last call to showjobs.
  4088. */
  4089. static void
  4090. showjobs(int mode)
  4091. {
  4092. struct job *jp;
  4093. TRACE(("showjobs(0x%x) called\n", mode));
  4094. /* Handle all finished jobs */
  4095. dowait(DOWAIT_NONBLOCK, NULL);
  4096. for (jp = curjob; jp; jp = jp->prev_job) {
  4097. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4098. showjob(jp, mode);
  4099. }
  4100. }
  4101. }
  4102. static int FAST_FUNC
  4103. jobscmd(int argc UNUSED_PARAM, char **argv)
  4104. {
  4105. int mode, m;
  4106. mode = 0;
  4107. while ((m = nextopt("lp")) != '\0') {
  4108. if (m == 'l')
  4109. mode |= SHOW_PIDS;
  4110. else
  4111. mode |= SHOW_ONLY_PGID;
  4112. }
  4113. argv = argptr;
  4114. if (*argv) {
  4115. do
  4116. showjob(getjob(*argv, 0), mode);
  4117. while (*++argv);
  4118. } else {
  4119. showjobs(mode);
  4120. }
  4121. return 0;
  4122. }
  4123. #endif /* JOBS */
  4124. /* Called only on finished or stopped jobs (no members are running) */
  4125. static int
  4126. getstatus(struct job *job)
  4127. {
  4128. int status;
  4129. int retval;
  4130. struct procstat *ps;
  4131. /* Fetch last member's status */
  4132. ps = job->ps + job->nprocs - 1;
  4133. status = ps->ps_status;
  4134. if (pipefail) {
  4135. /* "set -o pipefail" mode: use last _nonzero_ status */
  4136. while (status == 0 && --ps >= job->ps)
  4137. status = ps->ps_status;
  4138. }
  4139. retval = WEXITSTATUS(status);
  4140. if (!WIFEXITED(status)) {
  4141. #if JOBS
  4142. retval = WSTOPSIG(status);
  4143. if (!WIFSTOPPED(status))
  4144. #endif
  4145. {
  4146. /* XXX: limits number of signals */
  4147. retval = WTERMSIG(status);
  4148. #if JOBS
  4149. if (retval == SIGINT)
  4150. job->sigint = 1;
  4151. #endif
  4152. }
  4153. retval |= 128;
  4154. }
  4155. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4156. jobno(job), job->nprocs, status, retval));
  4157. return retval;
  4158. }
  4159. static int FAST_FUNC
  4160. waitcmd(int argc UNUSED_PARAM, char **argv)
  4161. {
  4162. struct job *job;
  4163. int retval;
  4164. struct job *jp;
  4165. #if BASH_WAIT_N
  4166. int status;
  4167. char one = nextopt("n");
  4168. #else
  4169. nextopt(nullstr);
  4170. #endif
  4171. retval = 0;
  4172. argv = argptr;
  4173. if (!argv[0]) {
  4174. /* wait for all jobs / one job if -n */
  4175. for (;;) {
  4176. jp = curjob;
  4177. #if BASH_WAIT_N
  4178. if (one && !jp)
  4179. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4180. retval = 127;
  4181. #endif
  4182. while (1) {
  4183. if (!jp) /* no running procs */
  4184. goto ret;
  4185. if (jp->state == JOBRUNNING)
  4186. break;
  4187. jp->waited = 1;
  4188. jp = jp->prev_job;
  4189. }
  4190. /* man bash:
  4191. * "When bash is waiting for an asynchronous command via
  4192. * the wait builtin, the reception of a signal for which a trap
  4193. * has been set will cause the wait builtin to return immediately
  4194. * with an exit status greater than 128, immediately after which
  4195. * the trap is executed."
  4196. */
  4197. #if BASH_WAIT_N
  4198. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4199. #else
  4200. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4201. #endif
  4202. /* if child sends us a signal *and immediately exits*,
  4203. * dowait() returns pid > 0. Check this case,
  4204. * not "if (dowait() < 0)"!
  4205. */
  4206. if (pending_sig)
  4207. goto sigout;
  4208. #if BASH_WAIT_N
  4209. if (one) {
  4210. /* wait -n waits for one _job_, not one _process_.
  4211. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4212. * should wait for 2 seconds. Not 1 or 3.
  4213. */
  4214. if (status != -1 && !WIFSTOPPED(status)) {
  4215. retval = WEXITSTATUS(status);
  4216. if (WIFSIGNALED(status))
  4217. retval = 128 | WTERMSIG(status);
  4218. goto ret;
  4219. }
  4220. }
  4221. #endif
  4222. }
  4223. }
  4224. retval = 127;
  4225. do {
  4226. if (**argv != '%') {
  4227. pid_t pid = number(*argv);
  4228. job = curjob;
  4229. while (1) {
  4230. if (!job)
  4231. goto repeat;
  4232. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4233. break;
  4234. job = job->prev_job;
  4235. }
  4236. } else {
  4237. job = getjob(*argv, 0);
  4238. }
  4239. /* loop until process terminated or stopped */
  4240. dowait(DOWAIT_BLOCK_OR_SIG, job);
  4241. if (pending_sig)
  4242. goto sigout;
  4243. job->waited = 1;
  4244. retval = getstatus(job);
  4245. repeat: ;
  4246. } while (*++argv);
  4247. ret:
  4248. return retval;
  4249. sigout:
  4250. retval = 128 | pending_sig;
  4251. return retval;
  4252. }
  4253. static struct job *
  4254. growjobtab(void)
  4255. {
  4256. size_t len;
  4257. ptrdiff_t offset;
  4258. struct job *jp, *jq;
  4259. len = njobs * sizeof(*jp);
  4260. jq = jobtab;
  4261. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4262. offset = (char *)jp - (char *)jq;
  4263. if (offset) {
  4264. /* Relocate pointers */
  4265. size_t l = len;
  4266. jq = (struct job *)((char *)jq + l);
  4267. while (l) {
  4268. l -= sizeof(*jp);
  4269. jq--;
  4270. #define joff(p) ((struct job *)((char *)(p) + l))
  4271. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4272. if (joff(jp)->ps == &jq->ps0)
  4273. jmove(joff(jp)->ps);
  4274. if (joff(jp)->prev_job)
  4275. jmove(joff(jp)->prev_job);
  4276. }
  4277. if (curjob)
  4278. jmove(curjob);
  4279. #undef joff
  4280. #undef jmove
  4281. }
  4282. njobs += 4;
  4283. jobtab = jp;
  4284. jp = (struct job *)((char *)jp + len);
  4285. jq = jp + 3;
  4286. do {
  4287. jq->used = 0;
  4288. } while (--jq >= jp);
  4289. return jp;
  4290. }
  4291. /*
  4292. * Return a new job structure.
  4293. * Called with interrupts off.
  4294. */
  4295. static struct job *
  4296. makejob(/*union node *node,*/ int nprocs)
  4297. {
  4298. int i;
  4299. struct job *jp;
  4300. for (i = njobs, jp = jobtab; ; jp++) {
  4301. if (--i < 0) {
  4302. jp = growjobtab();
  4303. break;
  4304. }
  4305. if (jp->used == 0)
  4306. break;
  4307. if (jp->state != JOBDONE || !jp->waited)
  4308. continue;
  4309. #if JOBS
  4310. if (doing_jobctl)
  4311. continue;
  4312. #endif
  4313. freejob(jp);
  4314. break;
  4315. }
  4316. memset(jp, 0, sizeof(*jp));
  4317. #if JOBS
  4318. /* jp->jobctl is a bitfield.
  4319. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4320. if (doing_jobctl)
  4321. jp->jobctl = 1;
  4322. #endif
  4323. jp->prev_job = curjob;
  4324. curjob = jp;
  4325. jp->used = 1;
  4326. jp->ps = &jp->ps0;
  4327. if (nprocs > 1) {
  4328. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4329. }
  4330. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4331. jobno(jp)));
  4332. return jp;
  4333. }
  4334. #if JOBS
  4335. /*
  4336. * Return a string identifying a command (to be printed by the
  4337. * jobs command).
  4338. */
  4339. static char *cmdnextc;
  4340. static void
  4341. cmdputs(const char *s)
  4342. {
  4343. static const char vstype[VSTYPE + 1][3] ALIGN1 = {
  4344. "", "}", "-", "+", "?", "=",
  4345. "%", "%%", "#", "##"
  4346. IF_BASH_SUBSTR(, ":")
  4347. IF_BASH_PATTERN_SUBST(, "/", "//")
  4348. };
  4349. const char *p, *str;
  4350. char cc[2];
  4351. char *nextc;
  4352. unsigned char c;
  4353. unsigned char subtype = 0;
  4354. int quoted = 0;
  4355. cc[1] = '\0';
  4356. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4357. p = s;
  4358. while ((c = *p++) != '\0') {
  4359. str = NULL;
  4360. switch (c) {
  4361. case CTLESC:
  4362. c = *p++;
  4363. break;
  4364. case CTLVAR:
  4365. subtype = *p++;
  4366. if ((subtype & VSTYPE) == VSLENGTH)
  4367. str = "${#";
  4368. else
  4369. str = "${";
  4370. goto dostr;
  4371. case CTLENDVAR:
  4372. str = "\"}";
  4373. str += !(quoted & 1);
  4374. quoted >>= 1;
  4375. subtype = 0;
  4376. goto dostr;
  4377. case CTLBACKQ:
  4378. str = "$(...)";
  4379. goto dostr;
  4380. #if ENABLE_FEATURE_SH_MATH
  4381. case CTLARI:
  4382. str = "$((";
  4383. goto dostr;
  4384. case CTLENDARI:
  4385. str = "))";
  4386. goto dostr;
  4387. #endif
  4388. case CTLQUOTEMARK:
  4389. quoted ^= 1;
  4390. c = '"';
  4391. break;
  4392. case '=':
  4393. if (subtype == 0)
  4394. break;
  4395. if ((subtype & VSTYPE) != VSNORMAL)
  4396. quoted <<= 1;
  4397. str = vstype[subtype & VSTYPE];
  4398. if (subtype & VSNUL)
  4399. c = ':';
  4400. else
  4401. goto checkstr;
  4402. break;
  4403. case '\'':
  4404. case '\\':
  4405. case '"':
  4406. case '$':
  4407. /* These can only happen inside quotes */
  4408. cc[0] = c;
  4409. str = cc;
  4410. //FIXME:
  4411. // $ true $$ &
  4412. // $ <cr>
  4413. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4414. c = '\\';
  4415. break;
  4416. default:
  4417. break;
  4418. }
  4419. USTPUTC(c, nextc);
  4420. checkstr:
  4421. if (!str)
  4422. continue;
  4423. dostr:
  4424. while ((c = *str++) != '\0') {
  4425. USTPUTC(c, nextc);
  4426. }
  4427. } /* while *p++ not NUL */
  4428. if (quoted & 1) {
  4429. USTPUTC('"', nextc);
  4430. }
  4431. *nextc = 0;
  4432. cmdnextc = nextc;
  4433. }
  4434. /* cmdtxt() and cmdlist() call each other */
  4435. static void cmdtxt(union node *n);
  4436. static void
  4437. cmdlist(union node *np, int sep)
  4438. {
  4439. for (; np; np = np->narg.next) {
  4440. if (!sep)
  4441. cmdputs(" ");
  4442. cmdtxt(np);
  4443. if (sep && np->narg.next)
  4444. cmdputs(" ");
  4445. }
  4446. }
  4447. static void
  4448. cmdtxt(union node *n)
  4449. {
  4450. union node *np;
  4451. struct nodelist *lp;
  4452. const char *p;
  4453. if (!n)
  4454. return;
  4455. switch (n->type) {
  4456. default:
  4457. #if DEBUG
  4458. abort();
  4459. #endif
  4460. case NPIPE:
  4461. lp = n->npipe.cmdlist;
  4462. for (;;) {
  4463. cmdtxt(lp->n);
  4464. lp = lp->next;
  4465. if (!lp)
  4466. break;
  4467. cmdputs(" | ");
  4468. }
  4469. break;
  4470. case NSEMI:
  4471. p = "; ";
  4472. goto binop;
  4473. case NAND:
  4474. p = " && ";
  4475. goto binop;
  4476. case NOR:
  4477. p = " || ";
  4478. binop:
  4479. cmdtxt(n->nbinary.ch1);
  4480. cmdputs(p);
  4481. n = n->nbinary.ch2;
  4482. goto donode;
  4483. case NREDIR:
  4484. case NBACKGND:
  4485. n = n->nredir.n;
  4486. goto donode;
  4487. case NNOT:
  4488. cmdputs("!");
  4489. n = n->nnot.com;
  4490. donode:
  4491. cmdtxt(n);
  4492. break;
  4493. case NIF:
  4494. cmdputs("if ");
  4495. cmdtxt(n->nif.test);
  4496. cmdputs("; then ");
  4497. if (n->nif.elsepart) {
  4498. cmdtxt(n->nif.ifpart);
  4499. cmdputs("; else ");
  4500. n = n->nif.elsepart;
  4501. } else {
  4502. n = n->nif.ifpart;
  4503. }
  4504. p = "; fi";
  4505. goto dotail;
  4506. case NSUBSHELL:
  4507. cmdputs("(");
  4508. n = n->nredir.n;
  4509. p = ")";
  4510. goto dotail;
  4511. case NWHILE:
  4512. p = "while ";
  4513. goto until;
  4514. case NUNTIL:
  4515. p = "until ";
  4516. until:
  4517. cmdputs(p);
  4518. cmdtxt(n->nbinary.ch1);
  4519. n = n->nbinary.ch2;
  4520. p = "; done";
  4521. dodo:
  4522. cmdputs("; do ");
  4523. dotail:
  4524. cmdtxt(n);
  4525. goto dotail2;
  4526. case NFOR:
  4527. cmdputs("for ");
  4528. cmdputs(n->nfor.var);
  4529. cmdputs(" in ");
  4530. cmdlist(n->nfor.args, 1);
  4531. n = n->nfor.body;
  4532. p = "; done";
  4533. goto dodo;
  4534. case NDEFUN:
  4535. cmdputs(n->ndefun.text);
  4536. p = "() { ... }";
  4537. goto dotail2;
  4538. case NCMD:
  4539. cmdlist(n->ncmd.args, 1);
  4540. cmdlist(n->ncmd.redirect, 0);
  4541. break;
  4542. case NARG:
  4543. p = n->narg.text;
  4544. dotail2:
  4545. cmdputs(p);
  4546. break;
  4547. case NHERE:
  4548. case NXHERE:
  4549. p = "<<...";
  4550. goto dotail2;
  4551. case NCASE:
  4552. cmdputs("case ");
  4553. cmdputs(n->ncase.expr->narg.text);
  4554. cmdputs(" in ");
  4555. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4556. cmdtxt(np->nclist.pattern);
  4557. cmdputs(") ");
  4558. cmdtxt(np->nclist.body);
  4559. cmdputs(";; ");
  4560. }
  4561. p = "esac";
  4562. goto dotail2;
  4563. case NTO:
  4564. p = ">";
  4565. goto redir;
  4566. case NCLOBBER:
  4567. p = ">|";
  4568. goto redir;
  4569. case NAPPEND:
  4570. p = ">>";
  4571. goto redir;
  4572. #if BASH_REDIR_OUTPUT
  4573. case NTO2:
  4574. #endif
  4575. case NTOFD:
  4576. p = ">&";
  4577. goto redir;
  4578. case NFROM:
  4579. p = "<";
  4580. goto redir;
  4581. case NFROMFD:
  4582. p = "<&";
  4583. goto redir;
  4584. case NFROMTO:
  4585. p = "<>";
  4586. redir:
  4587. cmdputs(utoa(n->nfile.fd));
  4588. cmdputs(p);
  4589. if (n->type == NTOFD || n->type == NFROMFD) {
  4590. if (n->ndup.dupfd >= 0)
  4591. cmdputs(utoa(n->ndup.dupfd));
  4592. else
  4593. cmdputs("-");
  4594. break;
  4595. }
  4596. n = n->nfile.fname;
  4597. goto donode;
  4598. }
  4599. }
  4600. static char *
  4601. commandtext(union node *n)
  4602. {
  4603. char *name;
  4604. STARTSTACKSTR(cmdnextc);
  4605. cmdtxt(n);
  4606. name = stackblock();
  4607. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4608. return ckstrdup(name);
  4609. }
  4610. #endif /* JOBS */
  4611. /*
  4612. * Fork off a subshell. If we are doing job control, give the subshell its
  4613. * own process group. Jp is a job structure that the job is to be added to.
  4614. * N is the command that will be evaluated by the child. Both jp and n may
  4615. * be NULL. The mode parameter can be one of the following:
  4616. * FORK_FG - Fork off a foreground process.
  4617. * FORK_BG - Fork off a background process.
  4618. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4619. * process group even if job control is on.
  4620. *
  4621. * When job control is turned off, background processes have their standard
  4622. * input redirected to /dev/null (except for the second and later processes
  4623. * in a pipeline).
  4624. *
  4625. * Called with interrupts off.
  4626. */
  4627. /*
  4628. * Clear traps on a fork.
  4629. */
  4630. static void
  4631. clear_traps(void)
  4632. {
  4633. char **tp;
  4634. INT_OFF;
  4635. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4636. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4637. if (trap_ptr == trap)
  4638. free(*tp);
  4639. /* else: it "belongs" to trap_ptr vector, don't free */
  4640. *tp = NULL;
  4641. if ((tp - trap) != 0)
  4642. setsignal(tp - trap);
  4643. }
  4644. }
  4645. may_have_traps = 0;
  4646. INT_ON;
  4647. }
  4648. /* Lives far away from here, needed for forkchild */
  4649. static void closescript(void);
  4650. /* Called after fork(), in child */
  4651. /* jp and n are NULL when called by openhere() for heredoc support */
  4652. static NOINLINE void
  4653. forkchild(struct job *jp, union node *n, int mode)
  4654. {
  4655. int oldlvl;
  4656. TRACE(("Child shell %d\n", getpid()));
  4657. oldlvl = shlvl;
  4658. shlvl++;
  4659. /* man bash: "Non-builtin commands run by bash have signal handlers
  4660. * set to the values inherited by the shell from its parent".
  4661. * Do we do it correctly? */
  4662. closescript();
  4663. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4664. && n && n->type == NCMD /* is it single cmd? */
  4665. /* && n->ncmd.args->type == NARG - always true? */
  4666. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4667. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4668. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4669. ) {
  4670. TRACE(("Trap hack\n"));
  4671. /* Awful hack for `trap` or $(trap).
  4672. *
  4673. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4674. * contains an example where "trap" is executed in a subshell:
  4675. *
  4676. * save_traps=$(trap)
  4677. * ...
  4678. * eval "$save_traps"
  4679. *
  4680. * Standard does not say that "trap" in subshell shall print
  4681. * parent shell's traps. It only says that its output
  4682. * must have suitable form, but then, in the above example
  4683. * (which is not supposed to be normative), it implies that.
  4684. *
  4685. * bash (and probably other shell) does implement it
  4686. * (traps are reset to defaults, but "trap" still shows them),
  4687. * but as a result, "trap" logic is hopelessly messed up:
  4688. *
  4689. * # trap
  4690. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4691. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4692. * # true | trap <--- trap is in subshell - no output (ditto)
  4693. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4694. * trap -- 'echo Ho' SIGWINCH
  4695. * # echo `(trap)` <--- in subshell in subshell - output
  4696. * trap -- 'echo Ho' SIGWINCH
  4697. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4698. * trap -- 'echo Ho' SIGWINCH
  4699. *
  4700. * The rules when to forget and when to not forget traps
  4701. * get really complex and nonsensical.
  4702. *
  4703. * Our solution: ONLY bare $(trap) or `trap` is special.
  4704. */
  4705. /* Save trap handler strings for trap builtin to print */
  4706. trap_ptr = xmemdup(trap, sizeof(trap));
  4707. /* Fall through into clearing traps */
  4708. }
  4709. clear_traps();
  4710. #if JOBS
  4711. /* do job control only in root shell */
  4712. doing_jobctl = 0;
  4713. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4714. pid_t pgrp;
  4715. if (jp->nprocs == 0)
  4716. pgrp = getpid();
  4717. else
  4718. pgrp = jp->ps[0].ps_pid;
  4719. /* this can fail because we are doing it in the parent also */
  4720. setpgid(0, pgrp);
  4721. if (mode == FORK_FG)
  4722. xtcsetpgrp(ttyfd, pgrp);
  4723. setsignal(SIGTSTP);
  4724. setsignal(SIGTTOU);
  4725. } else
  4726. #endif
  4727. if (mode == FORK_BG) {
  4728. /* man bash: "When job control is not in effect,
  4729. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4730. ignoresig(SIGINT);
  4731. ignoresig(SIGQUIT);
  4732. if (jp->nprocs == 0) {
  4733. close(0);
  4734. if (open(bb_dev_null, O_RDONLY) != 0)
  4735. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4736. }
  4737. }
  4738. if (oldlvl == 0) {
  4739. if (iflag) { /* why if iflag only? */
  4740. setsignal(SIGINT);
  4741. setsignal(SIGTERM);
  4742. }
  4743. /* man bash:
  4744. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4745. * commands run by bash have signal handlers
  4746. * set to the values inherited by the shell
  4747. * from its parent".
  4748. * Take care of the second rule: */
  4749. setsignal(SIGQUIT);
  4750. }
  4751. #if JOBS
  4752. if (n && n->type == NCMD
  4753. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4754. ) {
  4755. TRACE(("Job hack\n"));
  4756. /* "jobs": we do not want to clear job list for it,
  4757. * instead we remove only _its_ own_ job from job list.
  4758. * This makes "jobs .... | cat" more useful.
  4759. */
  4760. freejob(curjob);
  4761. return;
  4762. }
  4763. #endif
  4764. for (jp = curjob; jp; jp = jp->prev_job)
  4765. freejob(jp);
  4766. }
  4767. /* Called after fork(), in parent */
  4768. #if !JOBS
  4769. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4770. #endif
  4771. static void
  4772. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4773. {
  4774. TRACE(("In parent shell: child = %d\n", pid));
  4775. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4776. return;
  4777. #if JOBS
  4778. if (mode != FORK_NOJOB && jp->jobctl) {
  4779. int pgrp;
  4780. if (jp->nprocs == 0)
  4781. pgrp = pid;
  4782. else
  4783. pgrp = jp->ps[0].ps_pid;
  4784. /* This can fail because we are doing it in the child also */
  4785. setpgid(pid, pgrp);
  4786. }
  4787. #endif
  4788. if (mode == FORK_BG) {
  4789. backgndpid = pid; /* set $! */
  4790. set_curjob(jp, CUR_RUNNING);
  4791. }
  4792. if (jp) {
  4793. struct procstat *ps = &jp->ps[jp->nprocs++];
  4794. ps->ps_pid = pid;
  4795. ps->ps_status = -1;
  4796. ps->ps_cmd = nullstr;
  4797. #if JOBS
  4798. if (doing_jobctl && n)
  4799. ps->ps_cmd = commandtext(n);
  4800. #endif
  4801. }
  4802. }
  4803. /* jp and n are NULL when called by openhere() for heredoc support */
  4804. static int
  4805. forkshell(struct job *jp, union node *n, int mode)
  4806. {
  4807. int pid;
  4808. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4809. pid = fork();
  4810. if (pid < 0) {
  4811. TRACE(("Fork failed, errno=%d", errno));
  4812. if (jp)
  4813. freejob(jp);
  4814. ash_msg_and_raise_perror("can't fork");
  4815. }
  4816. if (pid == 0) {
  4817. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4818. forkchild(jp, n, mode);
  4819. } else {
  4820. forkparent(jp, n, mode, pid);
  4821. }
  4822. return pid;
  4823. }
  4824. /*
  4825. * Wait for job to finish.
  4826. *
  4827. * Under job control we have the problem that while a child process
  4828. * is running interrupts generated by the user are sent to the child
  4829. * but not to the shell. This means that an infinite loop started by
  4830. * an interactive user may be hard to kill. With job control turned off,
  4831. * an interactive user may place an interactive program inside a loop.
  4832. * If the interactive program catches interrupts, the user doesn't want
  4833. * these interrupts to also abort the loop. The approach we take here
  4834. * is to have the shell ignore interrupt signals while waiting for a
  4835. * foreground process to terminate, and then send itself an interrupt
  4836. * signal if the child process was terminated by an interrupt signal.
  4837. * Unfortunately, some programs want to do a bit of cleanup and then
  4838. * exit on interrupt; unless these processes terminate themselves by
  4839. * sending a signal to themselves (instead of calling exit) they will
  4840. * confuse this approach.
  4841. *
  4842. * Called with interrupts off.
  4843. */
  4844. static int
  4845. waitforjob(struct job *jp)
  4846. {
  4847. int st;
  4848. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4849. /* In non-interactive shells, we _can_ get
  4850. * a keyboard signal here and be EINTRed, but we just loop
  4851. * inside dowait(), waiting for command to complete.
  4852. *
  4853. * man bash:
  4854. * "If bash is waiting for a command to complete and receives
  4855. * a signal for which a trap has been set, the trap
  4856. * will not be executed until the command completes."
  4857. *
  4858. * Reality is that even if trap is not set, bash
  4859. * will not act on the signal until command completes.
  4860. * Try this. sleep5intoff.c:
  4861. * #include <signal.h>
  4862. * #include <unistd.h>
  4863. * int main() {
  4864. * sigset_t set;
  4865. * sigemptyset(&set);
  4866. * sigaddset(&set, SIGINT);
  4867. * sigaddset(&set, SIGQUIT);
  4868. * sigprocmask(SIG_BLOCK, &set, NULL);
  4869. * sleep(5);
  4870. * return 0;
  4871. * }
  4872. * $ bash -c './sleep5intoff; echo hi'
  4873. * ^C^C^C^C <--- pressing ^C once a second
  4874. * $ _
  4875. * $ bash -c './sleep5intoff; echo hi'
  4876. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4877. * $ _
  4878. */
  4879. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4880. if (!jp)
  4881. return exitstatus;
  4882. st = getstatus(jp);
  4883. #if JOBS
  4884. if (jp->jobctl) {
  4885. xtcsetpgrp(ttyfd, rootpid);
  4886. restore_tty_if_stopped_or_signaled(jp);
  4887. /*
  4888. * This is truly gross.
  4889. * If we're doing job control, then we did a TIOCSPGRP which
  4890. * caused us (the shell) to no longer be in the controlling
  4891. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4892. * intuit from the subprocess exit status whether a SIGINT
  4893. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4894. */
  4895. if (jp->sigint) /* TODO: do the same with all signals */
  4896. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4897. }
  4898. if (jp->state == JOBDONE)
  4899. #endif
  4900. freejob(jp);
  4901. return st;
  4902. }
  4903. /*
  4904. * return 1 if there are stopped jobs, otherwise 0
  4905. */
  4906. static int
  4907. stoppedjobs(void)
  4908. {
  4909. struct job *jp;
  4910. int retval;
  4911. retval = 0;
  4912. if (job_warning)
  4913. goto out;
  4914. jp = curjob;
  4915. if (jp && jp->state == JOBSTOPPED) {
  4916. out2str("You have stopped jobs.\n");
  4917. job_warning = 2;
  4918. retval++;
  4919. }
  4920. out:
  4921. return retval;
  4922. }
  4923. /*
  4924. * Code for dealing with input/output redirection.
  4925. */
  4926. #undef EMPTY
  4927. #undef CLOSED
  4928. #define EMPTY -2 /* marks an unused slot in redirtab */
  4929. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4930. /*
  4931. * Handle here documents. Normally we fork off a process to write the
  4932. * data to a pipe. If the document is short, we can stuff the data in
  4933. * the pipe without forking.
  4934. */
  4935. /* openhere needs this forward reference */
  4936. static void expandhere(union node *arg);
  4937. static int
  4938. openhere(union node *redir)
  4939. {
  4940. char *p;
  4941. int pip[2];
  4942. size_t len = 0;
  4943. if (pipe(pip) < 0)
  4944. ash_msg_and_raise_perror("can't create pipe");
  4945. p = redir->nhere.doc->narg.text;
  4946. if (redir->type == NXHERE) {
  4947. expandhere(redir->nhere.doc);
  4948. p = stackblock();
  4949. }
  4950. len = strlen(p);
  4951. if (len <= PIPE_BUF) {
  4952. xwrite(pip[1], p, len);
  4953. goto out;
  4954. }
  4955. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4956. /* child */
  4957. close(pip[0]);
  4958. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4959. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4960. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4961. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4962. signal(SIGPIPE, SIG_DFL);
  4963. xwrite(pip[1], p, len);
  4964. _exit(EXIT_SUCCESS);
  4965. }
  4966. out:
  4967. close(pip[1]);
  4968. return pip[0];
  4969. }
  4970. static int
  4971. openredirect(union node *redir)
  4972. {
  4973. struct stat sb;
  4974. char *fname;
  4975. int f;
  4976. switch (redir->nfile.type) {
  4977. /* Can't happen, our single caller does this itself */
  4978. // case NTOFD:
  4979. // case NFROMFD:
  4980. // return -1;
  4981. case NHERE:
  4982. case NXHERE:
  4983. return openhere(redir);
  4984. }
  4985. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4986. * allocated space. Do it only when we know it is safe.
  4987. */
  4988. fname = redir->nfile.expfname;
  4989. switch (redir->nfile.type) {
  4990. default:
  4991. #if DEBUG
  4992. abort();
  4993. #endif
  4994. case NFROM:
  4995. f = open(fname, O_RDONLY);
  4996. if (f < 0)
  4997. goto eopen;
  4998. break;
  4999. case NFROMTO:
  5000. f = open(fname, O_RDWR|O_CREAT, 0666);
  5001. if (f < 0)
  5002. goto ecreate;
  5003. break;
  5004. case NTO:
  5005. #if BASH_REDIR_OUTPUT
  5006. case NTO2:
  5007. #endif
  5008. /* Take care of noclobber mode. */
  5009. if (Cflag) {
  5010. if (stat(fname, &sb) < 0) {
  5011. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5012. if (f < 0)
  5013. goto ecreate;
  5014. } else if (!S_ISREG(sb.st_mode)) {
  5015. f = open(fname, O_WRONLY, 0666);
  5016. if (f < 0)
  5017. goto ecreate;
  5018. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5019. close(f);
  5020. errno = EEXIST;
  5021. goto ecreate;
  5022. }
  5023. } else {
  5024. errno = EEXIST;
  5025. goto ecreate;
  5026. }
  5027. break;
  5028. }
  5029. /* FALLTHROUGH */
  5030. case NCLOBBER:
  5031. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5032. if (f < 0)
  5033. goto ecreate;
  5034. break;
  5035. case NAPPEND:
  5036. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5037. if (f < 0)
  5038. goto ecreate;
  5039. break;
  5040. }
  5041. return f;
  5042. ecreate:
  5043. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5044. eopen:
  5045. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5046. }
  5047. /*
  5048. * Copy a file descriptor to be >= 10. Throws exception on error.
  5049. */
  5050. static int
  5051. savefd(int from)
  5052. {
  5053. int newfd;
  5054. int err;
  5055. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5056. err = newfd < 0 ? errno : 0;
  5057. if (err != EBADF) {
  5058. if (err)
  5059. ash_msg_and_raise_perror("%d", from);
  5060. close(from);
  5061. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5062. close_on_exec_on(newfd);
  5063. }
  5064. return newfd;
  5065. }
  5066. static int
  5067. dup2_or_raise(int from, int to)
  5068. {
  5069. int newfd;
  5070. newfd = (from != to) ? dup2(from, to) : to;
  5071. if (newfd < 0) {
  5072. /* Happens when source fd is not open: try "echo >&99" */
  5073. ash_msg_and_raise_perror("%d", from);
  5074. }
  5075. return newfd;
  5076. }
  5077. static int
  5078. dup_CLOEXEC(int fd, int avoid_fd)
  5079. {
  5080. int newfd;
  5081. repeat:
  5082. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5083. if (newfd >= 0) {
  5084. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5085. close_on_exec_on(newfd);
  5086. } else { /* newfd < 0 */
  5087. if (errno == EBUSY)
  5088. goto repeat;
  5089. if (errno == EINTR)
  5090. goto repeat;
  5091. }
  5092. return newfd;
  5093. }
  5094. static int
  5095. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5096. {
  5097. int newfd;
  5098. repeat:
  5099. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5100. if (newfd < 0) {
  5101. if (errno == EBUSY)
  5102. goto repeat;
  5103. if (errno == EINTR)
  5104. goto repeat;
  5105. /* fd was not open? */
  5106. if (errno == EBADF)
  5107. return fd;
  5108. ash_msg_and_raise_perror("%d", newfd);
  5109. }
  5110. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5111. close_on_exec_on(newfd);
  5112. close(fd);
  5113. return newfd;
  5114. }
  5115. /* Struct def and variable are moved down to the first usage site */
  5116. struct squirrel {
  5117. int orig_fd;
  5118. int moved_to;
  5119. };
  5120. struct redirtab {
  5121. struct redirtab *next;
  5122. int pair_count;
  5123. struct squirrel two_fd[];
  5124. };
  5125. #define redirlist (G_var.redirlist)
  5126. static void
  5127. add_squirrel_closed(struct redirtab *sq, int fd)
  5128. {
  5129. int i;
  5130. if (!sq)
  5131. return;
  5132. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5133. /* If we collide with an already moved fd... */
  5134. if (fd == sq->two_fd[i].orig_fd) {
  5135. /* Examples:
  5136. * "echo 3>FILE 3>&- 3>FILE"
  5137. * "echo 3>&- 3>FILE"
  5138. * No need for last redirect to insert
  5139. * another "need to close 3" indicator.
  5140. */
  5141. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5142. return;
  5143. }
  5144. }
  5145. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5146. sq->two_fd[i].orig_fd = fd;
  5147. sq->two_fd[i].moved_to = CLOSED;
  5148. }
  5149. static int
  5150. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5151. {
  5152. int i, new_fd;
  5153. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5154. avoid_fd = 9;
  5155. #if JOBS
  5156. if (fd == ttyfd) {
  5157. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5158. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5159. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5160. return 1; /* "we closed fd" */
  5161. }
  5162. #endif
  5163. /* Are we called from redirect(0)? E.g. redirect
  5164. * in a forked child. No need to save fds,
  5165. * we aren't going to use them anymore, ok to trash.
  5166. */
  5167. if (!sq)
  5168. return 0;
  5169. /* If this one of script's fds? */
  5170. if (fd != 0) {
  5171. struct parsefile *pf = g_parsefile;
  5172. while (pf) {
  5173. /* We skip fd == 0 case because of the following:
  5174. * $ ash # running ash interactively
  5175. * $ . ./script.sh
  5176. * and in script.sh: "exec 9>&0".
  5177. * Even though top-level pf_fd _is_ 0,
  5178. * it's still ok to use it: "read" builtin uses it,
  5179. * why should we cripple "exec" builtin?
  5180. */
  5181. if (fd == pf->pf_fd) {
  5182. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5183. return 1; /* "we closed fd" */
  5184. }
  5185. pf = pf->prev;
  5186. }
  5187. }
  5188. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5189. /* First: do we collide with some already moved fds? */
  5190. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5191. /* If we collide with an already moved fd... */
  5192. if (fd == sq->two_fd[i].moved_to) {
  5193. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5194. sq->two_fd[i].moved_to = new_fd;
  5195. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5196. if (new_fd < 0) /* what? */
  5197. xfunc_die();
  5198. return 0; /* "we did not close fd" */
  5199. }
  5200. if (fd == sq->two_fd[i].orig_fd) {
  5201. /* Example: echo Hello >/dev/null 1>&2 */
  5202. TRACE(("redirect_fd %d: already moved\n", fd));
  5203. return 0; /* "we did not close fd" */
  5204. }
  5205. }
  5206. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5207. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5208. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5209. if (new_fd < 0) {
  5210. if (errno != EBADF)
  5211. xfunc_die();
  5212. /* new_fd = CLOSED; - already is -1 */
  5213. }
  5214. sq->two_fd[i].moved_to = new_fd;
  5215. sq->two_fd[i].orig_fd = fd;
  5216. /* if we move stderr, let "set -x" code know */
  5217. if (fd == preverrout_fd)
  5218. preverrout_fd = new_fd;
  5219. return 0; /* "we did not close fd" */
  5220. }
  5221. static int
  5222. internally_opened_fd(int fd, struct redirtab *sq)
  5223. {
  5224. int i;
  5225. #if JOBS
  5226. if (fd == ttyfd)
  5227. return 1;
  5228. #endif
  5229. /* If this one of script's fds? */
  5230. if (fd != 0) {
  5231. struct parsefile *pf = g_parsefile;
  5232. while (pf) {
  5233. if (fd == pf->pf_fd)
  5234. return 1;
  5235. pf = pf->prev;
  5236. }
  5237. }
  5238. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5239. if (fd == sq->two_fd[i].moved_to)
  5240. return 1;
  5241. }
  5242. return 0;
  5243. }
  5244. /*
  5245. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5246. * old file descriptors are stashed away so that the redirection can be
  5247. * undone by calling popredir.
  5248. */
  5249. /* flags passed to redirect */
  5250. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5251. static void
  5252. redirect(union node *redir, int flags)
  5253. {
  5254. struct redirtab *sv;
  5255. if (!redir)
  5256. return;
  5257. sv = NULL;
  5258. INT_OFF;
  5259. if (flags & REDIR_PUSH)
  5260. sv = redirlist;
  5261. do {
  5262. int fd;
  5263. int newfd;
  5264. int close_fd;
  5265. int closed;
  5266. fd = redir->nfile.fd;
  5267. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5268. //bb_error_msg("doing %d > %d", fd, newfd);
  5269. newfd = redir->ndup.dupfd;
  5270. close_fd = -1;
  5271. } else {
  5272. newfd = openredirect(redir); /* always >= 0 */
  5273. if (fd == newfd) {
  5274. /* open() gave us precisely the fd we wanted.
  5275. * This means that this fd was not busy
  5276. * (not opened to anywhere).
  5277. * Remember to close it on restore:
  5278. */
  5279. add_squirrel_closed(sv, fd);
  5280. continue;
  5281. }
  5282. close_fd = newfd;
  5283. }
  5284. if (fd == newfd)
  5285. continue;
  5286. /* if "N>FILE": move newfd to fd */
  5287. /* if "N>&M": dup newfd to fd */
  5288. /* if "N>&-": close fd (newfd is -1) */
  5289. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5290. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5291. if (newfd == -1) {
  5292. /* "N>&-" means "close me" */
  5293. if (!closed) {
  5294. /* ^^^ optimization: saving may already
  5295. * have closed it. If not... */
  5296. close(fd);
  5297. }
  5298. } else {
  5299. /* if newfd is a script fd or saved fd, simulate EBADF */
  5300. if (internally_opened_fd(newfd, sv)) {
  5301. errno = EBADF;
  5302. ash_msg_and_raise_perror("%d", newfd);
  5303. }
  5304. dup2_or_raise(newfd, fd);
  5305. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5306. close(close_fd);
  5307. #if BASH_REDIR_OUTPUT
  5308. if (redir->nfile.type == NTO2 && fd == 1) {
  5309. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5310. fd = 2;
  5311. newfd = 1;
  5312. close_fd = -1;
  5313. goto redirect_more;
  5314. }
  5315. #endif
  5316. }
  5317. } while ((redir = redir->nfile.next) != NULL);
  5318. INT_ON;
  5319. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5320. #define REDIR_SAVEFD2 0
  5321. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5322. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5323. // not only for calls with flags containing REDIR_SAVEFD2.
  5324. // We do this unconditionally (see save_fd_on_redirect()).
  5325. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5326. // preverrout_fd = copied_fd2;
  5327. }
  5328. static int
  5329. redirectsafe(union node *redir, int flags)
  5330. {
  5331. int err;
  5332. volatile int saveint;
  5333. struct jmploc *volatile savehandler = exception_handler;
  5334. struct jmploc jmploc;
  5335. SAVE_INT(saveint);
  5336. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5337. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5338. if (!err) {
  5339. exception_handler = &jmploc;
  5340. redirect(redir, flags);
  5341. }
  5342. exception_handler = savehandler;
  5343. if (err && exception_type != EXERROR)
  5344. longjmp(exception_handler->loc, 1);
  5345. RESTORE_INT(saveint);
  5346. return err;
  5347. }
  5348. static struct redirtab*
  5349. pushredir(union node *redir)
  5350. {
  5351. struct redirtab *sv;
  5352. int i;
  5353. if (!redir)
  5354. return redirlist;
  5355. i = 0;
  5356. do {
  5357. i++;
  5358. #if BASH_REDIR_OUTPUT
  5359. if (redir->nfile.type == NTO2)
  5360. i++;
  5361. #endif
  5362. redir = redir->nfile.next;
  5363. } while (redir);
  5364. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5365. sv->pair_count = i;
  5366. while (--i >= 0)
  5367. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5368. sv->next = redirlist;
  5369. redirlist = sv;
  5370. return sv->next;
  5371. }
  5372. /*
  5373. * Undo the effects of the last redirection.
  5374. */
  5375. static void
  5376. popredir(int drop)
  5377. {
  5378. struct redirtab *rp;
  5379. int i;
  5380. if (redirlist == NULL)
  5381. return;
  5382. INT_OFF;
  5383. rp = redirlist;
  5384. for (i = 0; i < rp->pair_count; i++) {
  5385. int fd = rp->two_fd[i].orig_fd;
  5386. int copy = rp->two_fd[i].moved_to;
  5387. if (copy == CLOSED) {
  5388. if (!drop)
  5389. close(fd);
  5390. continue;
  5391. }
  5392. if (copy != EMPTY) {
  5393. if (!drop) {
  5394. /*close(fd);*/
  5395. dup2_or_raise(copy, fd);
  5396. }
  5397. close(copy);
  5398. }
  5399. }
  5400. redirlist = rp->next;
  5401. free(rp);
  5402. INT_ON;
  5403. }
  5404. static void
  5405. unwindredir(struct redirtab *stop)
  5406. {
  5407. while (redirlist != stop)
  5408. popredir(/*drop:*/ 0);
  5409. }
  5410. /* ============ Routines to expand arguments to commands
  5411. *
  5412. * We have to deal with backquotes, shell variables, and file metacharacters.
  5413. */
  5414. #if ENABLE_FEATURE_SH_MATH
  5415. static arith_t
  5416. ash_arith(const char *s)
  5417. {
  5418. arith_state_t math_state;
  5419. arith_t result;
  5420. math_state.lookupvar = lookupvar;
  5421. math_state.setvar = setvar0;
  5422. //math_state.endofname = endofname;
  5423. INT_OFF;
  5424. result = arith(&math_state, s);
  5425. if (math_state.errmsg)
  5426. ash_msg_and_raise_error(math_state.errmsg);
  5427. INT_ON;
  5428. return result;
  5429. }
  5430. #endif
  5431. #if BASH_SUBSTR
  5432. # if ENABLE_FEATURE_SH_MATH
  5433. static int substr_atoi(const char *s)
  5434. {
  5435. arith_t t = ash_arith(s);
  5436. if (sizeof(t) > sizeof(int)) {
  5437. /* clamp very large or very large negative nums for ${v:N:M}:
  5438. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5439. */
  5440. if (t > INT_MAX)
  5441. t = INT_MAX;
  5442. if (t < INT_MIN)
  5443. t = INT_MIN;
  5444. }
  5445. return t;
  5446. }
  5447. # else
  5448. # define substr_atoi(s) number(s)
  5449. # endif
  5450. #endif
  5451. /*
  5452. * expandarg flags
  5453. */
  5454. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5455. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5456. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5457. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5458. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5459. * POSIX says for this case:
  5460. * Pathname expansion shall not be performed on the word by a
  5461. * non-interactive shell; an interactive shell may perform it, but shall
  5462. * do so only when the expansion would result in one word.
  5463. * Currently, our code complies to the above rule by never globbing
  5464. * redirection filenames.
  5465. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5466. * (this means that on a typical Linux distro, bash almost always
  5467. * performs globbing, and thus diverges from what we do).
  5468. */
  5469. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5470. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5471. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5472. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5473. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5474. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5475. /*
  5476. * rmescape() flags
  5477. */
  5478. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5479. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5480. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5481. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5482. /* Add CTLESC when necessary. */
  5483. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5484. /*
  5485. * Structure specifying which parts of the string should be searched
  5486. * for IFS characters.
  5487. */
  5488. struct ifsregion {
  5489. struct ifsregion *next; /* next region in list */
  5490. int begoff; /* offset of start of region */
  5491. int endoff; /* offset of end of region */
  5492. int nulonly; /* search for nul bytes only */
  5493. };
  5494. struct arglist {
  5495. struct strlist *list;
  5496. struct strlist **lastp;
  5497. };
  5498. /* output of current string */
  5499. static char *expdest;
  5500. /* list of back quote expressions */
  5501. static struct nodelist *argbackq;
  5502. /* first struct in list of ifs regions */
  5503. static struct ifsregion ifsfirst;
  5504. /* last struct in list */
  5505. static struct ifsregion *ifslastp;
  5506. /* holds expanded arg list */
  5507. static struct arglist exparg;
  5508. /*
  5509. * Break the argument string into pieces based upon IFS and add the
  5510. * strings to the argument list. The regions of the string to be
  5511. * searched for IFS characters have been stored by recordregion.
  5512. */
  5513. static void
  5514. ifsbreakup(char *string, struct arglist *arglist)
  5515. {
  5516. struct ifsregion *ifsp;
  5517. struct strlist *sp;
  5518. char *start;
  5519. char *p;
  5520. char *q;
  5521. const char *ifs, *realifs;
  5522. int ifsspc;
  5523. int nulonly;
  5524. start = string;
  5525. if (ifslastp != NULL) {
  5526. ifsspc = 0;
  5527. nulonly = 0;
  5528. realifs = ifsset() ? ifsval() : defifs;
  5529. ifsp = &ifsfirst;
  5530. do {
  5531. int afternul;
  5532. p = string + ifsp->begoff;
  5533. afternul = nulonly;
  5534. nulonly = ifsp->nulonly;
  5535. ifs = nulonly ? nullstr : realifs;
  5536. ifsspc = 0;
  5537. while (p < string + ifsp->endoff) {
  5538. q = p;
  5539. if ((unsigned char)*p == CTLESC)
  5540. p++;
  5541. if (!strchr(ifs, *p)) {
  5542. p++;
  5543. continue;
  5544. }
  5545. if (!(afternul || nulonly))
  5546. ifsspc = (strchr(defifs, *p) != NULL);
  5547. /* Ignore IFS whitespace at start */
  5548. if (q == start && ifsspc) {
  5549. p++;
  5550. start = p;
  5551. continue;
  5552. }
  5553. *q = '\0';
  5554. sp = stzalloc(sizeof(*sp));
  5555. sp->text = start;
  5556. *arglist->lastp = sp;
  5557. arglist->lastp = &sp->next;
  5558. p++;
  5559. if (!nulonly) {
  5560. for (;;) {
  5561. if (p >= string + ifsp->endoff) {
  5562. break;
  5563. }
  5564. q = p;
  5565. if ((unsigned char)*p == CTLESC)
  5566. p++;
  5567. if (strchr(ifs, *p) == NULL) {
  5568. p = q;
  5569. break;
  5570. }
  5571. if (strchr(defifs, *p) == NULL) {
  5572. if (ifsspc) {
  5573. p++;
  5574. ifsspc = 0;
  5575. } else {
  5576. p = q;
  5577. break;
  5578. }
  5579. } else
  5580. p++;
  5581. }
  5582. }
  5583. start = p;
  5584. } /* while */
  5585. ifsp = ifsp->next;
  5586. } while (ifsp != NULL);
  5587. if (nulonly)
  5588. goto add;
  5589. }
  5590. if (!*start)
  5591. return;
  5592. add:
  5593. sp = stzalloc(sizeof(*sp));
  5594. sp->text = start;
  5595. *arglist->lastp = sp;
  5596. arglist->lastp = &sp->next;
  5597. }
  5598. static void
  5599. ifsfree(void)
  5600. {
  5601. struct ifsregion *p = ifsfirst.next;
  5602. if (!p)
  5603. goto out;
  5604. INT_OFF;
  5605. do {
  5606. struct ifsregion *ifsp;
  5607. ifsp = p->next;
  5608. free(p);
  5609. p = ifsp;
  5610. } while (p);
  5611. ifsfirst.next = NULL;
  5612. INT_ON;
  5613. out:
  5614. ifslastp = NULL;
  5615. }
  5616. static size_t
  5617. esclen(const char *start, const char *p)
  5618. {
  5619. size_t esc = 0;
  5620. while (p > start && (unsigned char)*--p == CTLESC) {
  5621. esc++;
  5622. }
  5623. return esc;
  5624. }
  5625. /*
  5626. * Remove any CTLESC characters from a string.
  5627. */
  5628. #if !BASH_PATTERN_SUBST
  5629. #define rmescapes(str, flag, slash_position) \
  5630. rmescapes(str, flag)
  5631. #endif
  5632. static char *
  5633. rmescapes(char *str, int flag, int *slash_position)
  5634. {
  5635. static const char qchars[] ALIGN1 = {
  5636. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5637. char *p, *q, *r;
  5638. unsigned protect_against_glob;
  5639. unsigned globbing;
  5640. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5641. if (!p)
  5642. return str;
  5643. q = p;
  5644. r = str;
  5645. if (flag & RMESCAPE_ALLOC) {
  5646. size_t len = p - str;
  5647. size_t fulllen = len + strlen(p) + 1;
  5648. if (flag & RMESCAPE_GROW) {
  5649. int strloc = str - (char *)stackblock();
  5650. r = makestrspace(fulllen, expdest);
  5651. /* p and str may be invalidated by makestrspace */
  5652. str = (char *)stackblock() + strloc;
  5653. p = str + len;
  5654. } else if (flag & RMESCAPE_HEAP) {
  5655. r = ckmalloc(fulllen);
  5656. } else {
  5657. r = stalloc(fulllen);
  5658. }
  5659. q = r;
  5660. if (len > 0) {
  5661. q = (char *)mempcpy(q, str, len);
  5662. }
  5663. }
  5664. globbing = flag & RMESCAPE_GLOB;
  5665. protect_against_glob = globbing;
  5666. while (*p) {
  5667. if ((unsigned char)*p == CTLQUOTEMARK) {
  5668. // Note: protect_against_glob only affect whether
  5669. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5670. p++;
  5671. protect_against_glob = globbing;
  5672. continue;
  5673. }
  5674. if (*p == '\\') {
  5675. /* naked back slash */
  5676. protect_against_glob = 0;
  5677. goto copy;
  5678. }
  5679. if ((unsigned char)*p == CTLESC) {
  5680. p++;
  5681. #if DEBUG
  5682. if (*p == '\0')
  5683. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5684. #endif
  5685. if (protect_against_glob) {
  5686. /*
  5687. * We used to trust glob() and fnmatch() to eat
  5688. * superfluous escapes (\z where z has no
  5689. * special meaning anyway). But this causes
  5690. * bugs such as string of one greek letter rho
  5691. * (unicode-encoded as two bytes "cf,81")
  5692. * getting encoded as "cf,CTLESC,81"
  5693. * and here, converted to "cf,\,81" -
  5694. * which does not go well with some flavors
  5695. * of fnmatch() in unicode locales
  5696. * (for example, glibc <= 2.22).
  5697. *
  5698. * Lets add "\" only on the chars which need it.
  5699. * Testcases for less obvious chars are shown.
  5700. */
  5701. if (*p == '*'
  5702. || *p == '?'
  5703. || *p == '['
  5704. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5705. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5706. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5707. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5708. /* Some libc support [^negate], that's why "^" also needs love */
  5709. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5710. ) {
  5711. *q++ = '\\';
  5712. }
  5713. }
  5714. }
  5715. #if BASH_PATTERN_SUBST
  5716. else if (slash_position && p == str + *slash_position) {
  5717. /* stop handling globbing */
  5718. globbing = 0;
  5719. *slash_position = q - r;
  5720. slash_position = NULL;
  5721. }
  5722. #endif
  5723. protect_against_glob = globbing;
  5724. copy:
  5725. *q++ = *p++;
  5726. }
  5727. *q = '\0';
  5728. if (flag & RMESCAPE_GROW) {
  5729. expdest = r;
  5730. STADJUST(q - r + 1, expdest);
  5731. }
  5732. return r;
  5733. }
  5734. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5735. /*
  5736. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5737. *
  5738. * Returns an stalloced string.
  5739. */
  5740. static char *
  5741. preglob(const char *pattern, int flag)
  5742. {
  5743. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5744. }
  5745. /*
  5746. * Put a string on the stack.
  5747. */
  5748. static size_t
  5749. memtodest(const char *p, size_t len, int flags)
  5750. {
  5751. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5752. char *q;
  5753. char *s;
  5754. if (!len)
  5755. return 0;
  5756. q = makestrspace(len * 2, expdest);
  5757. s = q;
  5758. do {
  5759. unsigned char c = *p++;
  5760. if (c) {
  5761. if (flags & QUOTES_ESC) {
  5762. int n = SIT(c, syntax);
  5763. if (n == CCTL
  5764. || ((flags & EXP_QUOTED) && n == CBACK)
  5765. ) {
  5766. USTPUTC(CTLESC, q);
  5767. }
  5768. }
  5769. } else if (!(flags & EXP_KEEPNUL))
  5770. continue;
  5771. USTPUTC(c, q);
  5772. } while (--len);
  5773. expdest = q;
  5774. return q - s;
  5775. }
  5776. static size_t
  5777. strtodest(const char *p, int flags)
  5778. {
  5779. size_t len = strlen(p);
  5780. memtodest(p, len, flags);
  5781. return len;
  5782. }
  5783. /*
  5784. * Our own itoa().
  5785. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5786. */
  5787. static int
  5788. cvtnum(arith_t num, int flags)
  5789. {
  5790. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5791. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5792. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5793. char buf[len];
  5794. len = fmtstr(buf, len, ARITH_FMT, num);
  5795. return memtodest(buf, len, flags);
  5796. }
  5797. /*
  5798. * Record the fact that we have to scan this region of the
  5799. * string for IFS characters.
  5800. */
  5801. static void
  5802. recordregion(int start, int end, int nulonly)
  5803. {
  5804. struct ifsregion *ifsp;
  5805. if (ifslastp == NULL) {
  5806. ifsp = &ifsfirst;
  5807. } else {
  5808. INT_OFF;
  5809. ifsp = ckzalloc(sizeof(*ifsp));
  5810. /*ifsp->next = NULL; - ckzalloc did it */
  5811. ifslastp->next = ifsp;
  5812. INT_ON;
  5813. }
  5814. ifslastp = ifsp;
  5815. ifslastp->begoff = start;
  5816. ifslastp->endoff = end;
  5817. ifslastp->nulonly = nulonly;
  5818. }
  5819. static void
  5820. removerecordregions(int endoff)
  5821. {
  5822. if (ifslastp == NULL)
  5823. return;
  5824. if (ifsfirst.endoff > endoff) {
  5825. while (ifsfirst.next) {
  5826. struct ifsregion *ifsp;
  5827. INT_OFF;
  5828. ifsp = ifsfirst.next->next;
  5829. free(ifsfirst.next);
  5830. ifsfirst.next = ifsp;
  5831. INT_ON;
  5832. }
  5833. if (ifsfirst.begoff > endoff) {
  5834. ifslastp = NULL;
  5835. } else {
  5836. ifslastp = &ifsfirst;
  5837. ifsfirst.endoff = endoff;
  5838. }
  5839. return;
  5840. }
  5841. ifslastp = &ifsfirst;
  5842. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5843. ifslastp = ifslastp->next;
  5844. while (ifslastp->next) {
  5845. struct ifsregion *ifsp;
  5846. INT_OFF;
  5847. ifsp = ifslastp->next->next;
  5848. free(ifslastp->next);
  5849. ifslastp->next = ifsp;
  5850. INT_ON;
  5851. }
  5852. if (ifslastp->endoff > endoff)
  5853. ifslastp->endoff = endoff;
  5854. }
  5855. static char *
  5856. exptilde(char *startp, int flag)
  5857. {
  5858. unsigned char c;
  5859. char *name;
  5860. struct passwd *pw;
  5861. const char *home;
  5862. char *p;
  5863. p = startp;
  5864. name = p + 1;
  5865. while ((c = *++p) != '\0') {
  5866. switch (c) {
  5867. case CTLESC:
  5868. return startp;
  5869. case CTLQUOTEMARK:
  5870. return startp;
  5871. case ':':
  5872. if (flag & EXP_VARTILDE)
  5873. goto done;
  5874. break;
  5875. case '/':
  5876. case CTLENDVAR:
  5877. goto done;
  5878. }
  5879. }
  5880. done:
  5881. if (flag & EXP_DISCARD)
  5882. goto out;
  5883. *p = '\0';
  5884. if (*name == '\0') {
  5885. home = lookupvar("HOME");
  5886. } else {
  5887. pw = getpwnam(name);
  5888. if (pw == NULL)
  5889. goto lose;
  5890. home = pw->pw_dir;
  5891. }
  5892. *p = c;
  5893. if (!home)
  5894. goto lose;
  5895. strtodest(home, flag | EXP_QUOTED);
  5896. out:
  5897. return p;
  5898. lose:
  5899. return startp;
  5900. }
  5901. /*
  5902. * Execute a command inside back quotes. If it's a builtin command, we
  5903. * want to save its output in a block obtained from malloc. Otherwise
  5904. * we fork off a subprocess and get the output of the command via a pipe.
  5905. * Should be called with interrupts off.
  5906. */
  5907. struct backcmd { /* result of evalbackcmd */
  5908. int fd; /* file descriptor to read from */
  5909. int nleft; /* number of chars in buffer */
  5910. char *buf; /* buffer */
  5911. struct job *jp; /* job structure for command */
  5912. };
  5913. /* These forward decls are needed to use "eval" code for backticks handling: */
  5914. /* flags in argument to evaltree */
  5915. #define EV_EXIT 01 /* exit after evaluating tree */
  5916. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5917. static int evaltree(union node *, int);
  5918. /* An evaltree() which is known to never return.
  5919. * Used to use an alias:
  5920. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5921. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5922. */
  5923. static ALWAYS_INLINE NORETURN void
  5924. evaltreenr(union node *n, int flags)
  5925. {
  5926. evaltree(n, flags);
  5927. bb_unreachable(abort());
  5928. /* NOTREACHED */
  5929. }
  5930. static void FAST_FUNC
  5931. evalbackcmd(union node *n, struct backcmd *result)
  5932. {
  5933. int pip[2];
  5934. struct job *jp;
  5935. result->fd = -1;
  5936. result->buf = NULL;
  5937. result->nleft = 0;
  5938. result->jp = NULL;
  5939. if (n == NULL) {
  5940. goto out;
  5941. }
  5942. if (pipe(pip) < 0)
  5943. ash_msg_and_raise_perror("can't create pipe");
  5944. jp = makejob(/*n,*/ 1);
  5945. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5946. /* child */
  5947. FORCE_INT_ON;
  5948. close(pip[0]);
  5949. if (pip[1] != 1) {
  5950. /*close(1);*/
  5951. dup2_or_raise(pip[1], 1);
  5952. close(pip[1]);
  5953. }
  5954. /* TODO: eflag clearing makes the following not abort:
  5955. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5956. * which is what bash does (unless it is in POSIX mode).
  5957. * dash deleted "eflag = 0" line in the commit
  5958. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5959. * [EVAL] Don't clear eflag in evalbackcmd
  5960. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5961. */
  5962. eflag = 0;
  5963. ifsfree();
  5964. evaltreenr(n, EV_EXIT);
  5965. /* NOTREACHED */
  5966. }
  5967. /* parent */
  5968. close(pip[1]);
  5969. result->fd = pip[0];
  5970. result->jp = jp;
  5971. out:
  5972. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5973. result->fd, result->buf, result->nleft, result->jp));
  5974. }
  5975. /*
  5976. * Expand stuff in backwards quotes.
  5977. */
  5978. static void
  5979. expbackq(union node *cmd, int flag)
  5980. {
  5981. struct backcmd in;
  5982. int i;
  5983. char buf[128];
  5984. char *p;
  5985. char *dest;
  5986. int startloc;
  5987. struct stackmark smark;
  5988. if (flag & EXP_DISCARD)
  5989. goto out;
  5990. INT_OFF;
  5991. startloc = expdest - (char *)stackblock();
  5992. pushstackmark(&smark, startloc);
  5993. evalbackcmd(cmd, &in);
  5994. popstackmark(&smark);
  5995. p = in.buf;
  5996. i = in.nleft;
  5997. if (i == 0)
  5998. goto read;
  5999. for (;;) {
  6000. memtodest(p, i, flag);
  6001. read:
  6002. if (in.fd < 0)
  6003. break;
  6004. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6005. TRACE(("expbackq: read returns %d\n", i));
  6006. if (i <= 0)
  6007. break;
  6008. p = buf;
  6009. }
  6010. free(in.buf);
  6011. if (in.fd >= 0) {
  6012. close(in.fd);
  6013. back_exitstatus = waitforjob(in.jp);
  6014. }
  6015. INT_ON;
  6016. /* Eat all trailing newlines */
  6017. dest = expdest;
  6018. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6019. STUNPUTC(dest);
  6020. expdest = dest;
  6021. if (!(flag & EXP_QUOTED))
  6022. recordregion(startloc, dest - (char *)stackblock(), 0);
  6023. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6024. (int)((dest - (char *)stackblock()) - startloc),
  6025. (int)((dest - (char *)stackblock()) - startloc),
  6026. stackblock() + startloc));
  6027. out:
  6028. argbackq = argbackq->next;
  6029. }
  6030. /* expari needs it */
  6031. static char *argstr(char *p, int flag);
  6032. #if ENABLE_FEATURE_SH_MATH
  6033. /*
  6034. * Expand arithmetic expression. Backup to start of expression,
  6035. * evaluate, place result in (backed up) result, adjust string position.
  6036. */
  6037. static char *
  6038. expari(char *start, int flag)
  6039. {
  6040. struct stackmark sm;
  6041. int begoff;
  6042. int endoff;
  6043. int len;
  6044. arith_t result;
  6045. char *p;
  6046. p = stackblock();
  6047. begoff = expdest - p;
  6048. p = argstr(start, flag & EXP_DISCARD);
  6049. if (flag & EXP_DISCARD)
  6050. goto out;
  6051. start = stackblock();
  6052. endoff = expdest - start;
  6053. start += begoff;
  6054. STADJUST(start - expdest, expdest);
  6055. removerecordregions(begoff);
  6056. if (flag & QUOTES_ESC)
  6057. rmescapes(start, 0, NULL);
  6058. pushstackmark(&sm, endoff);
  6059. result = ash_arith(start);
  6060. popstackmark(&sm);
  6061. len = cvtnum(result, flag);
  6062. if (!(flag & EXP_QUOTED))
  6063. recordregion(begoff, begoff + len, 0);
  6064. out:
  6065. return p;
  6066. }
  6067. #endif
  6068. /* argstr needs it */
  6069. static char *evalvar(char *p, int flags);
  6070. /*
  6071. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6072. * characters to allow for further processing. Otherwise treat
  6073. * $@ like $* since no splitting will be performed.
  6074. */
  6075. static char *
  6076. argstr(char *p, int flag)
  6077. {
  6078. static const char spclchars[] ALIGN1 = {
  6079. '=',
  6080. ':',
  6081. CTLQUOTEMARK,
  6082. CTLENDVAR,
  6083. CTLESC,
  6084. CTLVAR,
  6085. CTLBACKQ,
  6086. #if ENABLE_FEATURE_SH_MATH
  6087. CTLARI,
  6088. CTLENDARI,
  6089. #endif
  6090. '\0'
  6091. };
  6092. const char *reject = spclchars;
  6093. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6094. int inquotes;
  6095. size_t length;
  6096. int startloc;
  6097. reject += !!(flag & EXP_VARTILDE2);
  6098. reject += flag & EXP_VARTILDE ? 0 : 2;
  6099. inquotes = 0;
  6100. length = 0;
  6101. if (flag & EXP_TILDE) {
  6102. flag &= ~EXP_TILDE;
  6103. tilde:
  6104. if (*p == '~')
  6105. p = exptilde(p, flag);
  6106. }
  6107. start:
  6108. startloc = expdest - (char *)stackblock();
  6109. for (;;) {
  6110. int end;
  6111. unsigned char c;
  6112. length += strcspn(p + length, reject);
  6113. end = 0;
  6114. c = p[length];
  6115. if (!(c & 0x80)
  6116. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6117. || c == CTLENDVAR
  6118. ) {
  6119. /*
  6120. * c == '=' || c == ':' || c == '\0' ||
  6121. * c == CTLENDARI || c == CTLENDVAR
  6122. */
  6123. length++;
  6124. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6125. end = !!((c - 1) & 0x80);
  6126. }
  6127. if (length > 0 && !(flag & EXP_DISCARD)) {
  6128. int newloc;
  6129. char *q;
  6130. q = stnputs(p, length, expdest);
  6131. q[-1] &= end - 1;
  6132. expdest = q - (flag & EXP_WORD ? end : 0);
  6133. newloc = q - (char *)stackblock() - end;
  6134. if (breakall && !inquotes && newloc > startloc) {
  6135. recordregion(startloc, newloc, 0);
  6136. }
  6137. startloc = newloc;
  6138. }
  6139. p += length + 1;
  6140. length = 0;
  6141. if (end)
  6142. break;
  6143. switch (c) {
  6144. case '=':
  6145. flag |= EXP_VARTILDE2;
  6146. reject++;
  6147. /* fall through */
  6148. case ':':
  6149. /*
  6150. * sort of a hack - expand tildes in variable
  6151. * assignments (after the first '=' and after ':'s).
  6152. */
  6153. if (*--p == '~') {
  6154. goto tilde;
  6155. }
  6156. continue;
  6157. case CTLQUOTEMARK:
  6158. /* "$@" syntax adherence hack */
  6159. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6160. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6161. goto start;
  6162. }
  6163. inquotes ^= EXP_QUOTED;
  6164. addquote:
  6165. if (flag & QUOTES_ESC) {
  6166. p--;
  6167. length++;
  6168. startloc++;
  6169. }
  6170. break;
  6171. case CTLESC:
  6172. startloc++;
  6173. length++;
  6174. goto addquote;
  6175. case CTLVAR:
  6176. TRACE(("argstr: evalvar('%s')\n", p));
  6177. p = evalvar(p, flag | inquotes);
  6178. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6179. goto start;
  6180. case CTLBACKQ:
  6181. expbackq(argbackq->n, flag | inquotes);
  6182. goto start;
  6183. #if ENABLE_FEATURE_SH_MATH
  6184. case CTLARI:
  6185. p = expari(p, flag | inquotes);
  6186. goto start;
  6187. #endif
  6188. }
  6189. }
  6190. return p - 1;
  6191. }
  6192. static char *
  6193. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6194. char *pattern, int quotes, int zero)
  6195. {
  6196. char *loc, *loc2;
  6197. char c;
  6198. loc = startp;
  6199. loc2 = rmesc;
  6200. do {
  6201. int match;
  6202. const char *s = loc2;
  6203. c = *loc2;
  6204. if (zero) {
  6205. *loc2 = '\0';
  6206. s = rmesc;
  6207. }
  6208. match = pmatch(pattern, s);
  6209. *loc2 = c;
  6210. if (match)
  6211. return loc;
  6212. if (quotes && (unsigned char)*loc == CTLESC)
  6213. loc++;
  6214. loc++;
  6215. loc2++;
  6216. } while (c);
  6217. return NULL;
  6218. }
  6219. static char *
  6220. scanright(char *startp, char *rmesc, char *rmescend,
  6221. char *pattern, int quotes, int match_at_start)
  6222. {
  6223. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6224. int try2optimize = match_at_start;
  6225. #endif
  6226. int esc = 0;
  6227. char *loc;
  6228. char *loc2;
  6229. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6230. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6231. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6232. * Logic:
  6233. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6234. * and on each iteration they go back two/one char until they reach the beginning.
  6235. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6236. */
  6237. /* TODO: document in what other circumstances we are called. */
  6238. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6239. int match;
  6240. char c = *loc2;
  6241. const char *s = loc2;
  6242. if (match_at_start) {
  6243. *loc2 = '\0';
  6244. s = rmesc;
  6245. }
  6246. match = pmatch(pattern, s);
  6247. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6248. *loc2 = c;
  6249. if (match)
  6250. return loc;
  6251. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6252. if (try2optimize) {
  6253. /* Maybe we can optimize this:
  6254. * if pattern ends with unescaped *, we can avoid checking
  6255. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6256. * it won't match truncated "raw_value_of_" strings too.
  6257. */
  6258. unsigned plen = strlen(pattern);
  6259. /* Does it end with "*"? */
  6260. if (plen != 0 && pattern[--plen] == '*') {
  6261. /* "xxxx*" is not escaped */
  6262. /* "xxx\*" is escaped */
  6263. /* "xx\\*" is not escaped */
  6264. /* "x\\\*" is escaped */
  6265. int slashes = 0;
  6266. while (plen != 0 && pattern[--plen] == '\\')
  6267. slashes++;
  6268. if (!(slashes & 1))
  6269. break; /* ends with unescaped "*" */
  6270. }
  6271. try2optimize = 0;
  6272. }
  6273. #endif
  6274. loc--;
  6275. if (quotes) {
  6276. if (--esc < 0) {
  6277. esc = esclen(startp, loc);
  6278. }
  6279. if (esc % 2) {
  6280. esc--;
  6281. loc--;
  6282. }
  6283. }
  6284. }
  6285. return NULL;
  6286. }
  6287. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6288. static void
  6289. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6290. {
  6291. const char *msg;
  6292. const char *tail;
  6293. tail = nullstr;
  6294. msg = "parameter not set";
  6295. if (umsg) {
  6296. if ((unsigned char)*end == CTLENDVAR) {
  6297. if (varflags & VSNUL)
  6298. tail = " or null";
  6299. } else {
  6300. msg = umsg;
  6301. }
  6302. }
  6303. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6304. }
  6305. static char *
  6306. subevalvar(char *start, char *str, int strloc,
  6307. int startloc, int varflags, int flag)
  6308. {
  6309. int subtype = varflags & VSTYPE;
  6310. int quotes = flag & QUOTES_ESC;
  6311. char *startp;
  6312. char *loc;
  6313. char *rmesc, *rmescend;
  6314. long amount;
  6315. int resetloc;
  6316. int argstr_flags;
  6317. IF_BASH_PATTERN_SUBST(int workloc;)
  6318. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6319. IF_BASH_PATTERN_SUBST(char *repl;)
  6320. int zero;
  6321. char *(*scan)(char*, char*, char*, char*, int, int);
  6322. char *p;
  6323. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6324. // start, str, strloc, startloc, varflags, quotes);
  6325. #if BASH_PATTERN_SUBST
  6326. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6327. * argstr() call expands possible variable references in pattern:
  6328. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6329. */
  6330. repl = NULL;
  6331. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6332. /* Find '/' and replace with NUL */
  6333. repl = start;
  6334. /* The pattern can't be empty.
  6335. * IOW: if the first char after "${v//" is a slash,
  6336. * it does not terminate the pattern - it's the first char of the pattern:
  6337. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6338. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6339. */
  6340. if (*repl == '/')
  6341. repl++;
  6342. for (;;) {
  6343. if (*repl == '\0') {
  6344. repl = NULL;
  6345. break;
  6346. }
  6347. if (*repl == '/') {
  6348. *repl = '\0';
  6349. break;
  6350. }
  6351. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6352. if ((unsigned char)*repl == CTLESC && repl[1])
  6353. repl++;
  6354. repl++;
  6355. }
  6356. }
  6357. #endif
  6358. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6359. if (!str
  6360. #if BASH_SUBSTR
  6361. && subtype != VSSUBSTR
  6362. #endif
  6363. ) {
  6364. /* EXP_CASE keeps CTLESC's */
  6365. argstr_flags |= EXP_CASE;
  6366. }
  6367. p = argstr(start, argstr_flags);
  6368. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6369. #if BASH_PATTERN_SUBST
  6370. slash_pos = -1;
  6371. if (repl) {
  6372. slash_pos = expdest - ((char *)stackblock() + strloc);
  6373. if (!(flag & EXP_DISCARD))
  6374. STPUTC('/', expdest);
  6375. //bb_error_msg("repl+1:'%s'", repl + 1);
  6376. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6377. *repl = '/';
  6378. }
  6379. #endif
  6380. if (flag & EXP_DISCARD)
  6381. return p;
  6382. startp = (char *)stackblock() + startloc;
  6383. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6384. switch (subtype) {
  6385. case VSASSIGN:
  6386. setvar0(str, startp);
  6387. loc = startp;
  6388. goto out;
  6389. case VSQUESTION:
  6390. varunset(start, str, startp, varflags);
  6391. /* NOTREACHED */
  6392. #if BASH_SUBSTR
  6393. case VSSUBSTR: {
  6394. int pos, len, orig_len;
  6395. char *colon;
  6396. char *vstr;
  6397. loc = vstr = stackblock() + strloc;
  6398. /* Read POS in ${var:POS:LEN} */
  6399. colon = strchr(loc, ':');
  6400. if (colon) *colon = '\0';
  6401. pos = substr_atoi(loc);
  6402. if (colon) *colon = ':';
  6403. /* Read LEN in ${var:POS:LEN} */
  6404. len = vstr - startp - 1;
  6405. /* *loc != '\0', guaranteed by parser */
  6406. if (quotes) {
  6407. char *ptr;
  6408. /* Adjust the length by the number of escapes */
  6409. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6410. if ((unsigned char)*ptr == CTLESC) {
  6411. len--;
  6412. ptr++;
  6413. }
  6414. }
  6415. }
  6416. orig_len = len;
  6417. if (*loc++ == ':') {
  6418. /* ${var::LEN} */
  6419. len = substr_atoi(loc);
  6420. } else {
  6421. /* Skip POS in ${var:POS:LEN} */
  6422. len = orig_len;
  6423. while (*loc && *loc != ':')
  6424. loc++;
  6425. if (*loc++ == ':')
  6426. len = substr_atoi(loc);
  6427. }
  6428. if (pos < 0) {
  6429. /* ${VAR:$((-n)):l} starts n chars from the end */
  6430. pos = orig_len + pos;
  6431. }
  6432. if ((unsigned)pos >= orig_len) {
  6433. /* apart from obvious ${VAR:999999:l},
  6434. * covers ${VAR:$((-9999999)):l} - result is ""
  6435. * (bash compat)
  6436. */
  6437. pos = 0;
  6438. len = 0;
  6439. }
  6440. if (len < 0) {
  6441. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6442. len = (orig_len - pos) + len;
  6443. }
  6444. if ((unsigned)len > (orig_len - pos))
  6445. len = orig_len - pos;
  6446. for (vstr = startp; pos; vstr++, pos--) {
  6447. if (quotes && (unsigned char)*vstr == CTLESC)
  6448. vstr++;
  6449. }
  6450. for (loc = startp; len; len--) {
  6451. if (quotes && (unsigned char)*vstr == CTLESC)
  6452. *loc++ = *vstr++;
  6453. *loc++ = *vstr++;
  6454. }
  6455. *loc = '\0';
  6456. goto out;
  6457. }
  6458. #endif /* BASH_SUBSTR */
  6459. }
  6460. resetloc = expdest - (char *)stackblock();
  6461. #if BASH_PATTERN_SUBST
  6462. repl = NULL;
  6463. /* We'll comeback here if we grow the stack while handling
  6464. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6465. * stack will need rebasing, and we'll need to remove our work
  6466. * areas each time
  6467. */
  6468. restart:
  6469. #endif
  6470. amount = expdest - ((char *)stackblock() + resetloc);
  6471. STADJUST(-amount, expdest);
  6472. startp = (char *)stackblock() + startloc;
  6473. rmesc = startp;
  6474. rmescend = (char *)stackblock() + strloc;
  6475. //bb_error_msg("str7:'%s'", rmescend);
  6476. if (quotes) {
  6477. //TODO: how to handle slash_pos here if string changes (shortens?)
  6478. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6479. if (rmesc != startp) {
  6480. rmescend = expdest;
  6481. startp = (char *)stackblock() + startloc;
  6482. }
  6483. }
  6484. rmescend--;
  6485. str = (char *)stackblock() + strloc;
  6486. /*
  6487. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6488. * The result is a_\_z_c (not a\_\_z_c)!
  6489. *
  6490. * The search pattern and replace string treat backslashes differently!
  6491. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6492. * and string. It's only used on the first call.
  6493. */
  6494. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6495. rmescapes(str, RMESCAPE_GLOB,
  6496. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6497. );
  6498. #if BASH_PATTERN_SUBST
  6499. workloc = expdest - (char *)stackblock();
  6500. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6501. int len;
  6502. char *idx, *end;
  6503. if (!repl) {
  6504. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6505. repl = nullstr;
  6506. if (slash_pos >= 0) {
  6507. repl = str + slash_pos;
  6508. *repl++ = '\0';
  6509. }
  6510. }
  6511. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6512. /* If there's no pattern to match, return the expansion unmolested */
  6513. if (str[0] == '\0')
  6514. goto out1;
  6515. len = 0;
  6516. idx = startp;
  6517. end = str - 1;
  6518. while (idx < end) {
  6519. try_to_match:
  6520. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6521. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6522. if (!loc) {
  6523. /* No match, advance */
  6524. char *restart_detect = stackblock();
  6525. skip_matching:
  6526. STPUTC(*idx, expdest);
  6527. if (quotes && (unsigned char)*idx == CTLESC) {
  6528. idx++;
  6529. len++;
  6530. STPUTC(*idx, expdest);
  6531. }
  6532. if (stackblock() != restart_detect)
  6533. goto restart;
  6534. idx++;
  6535. len++;
  6536. rmesc++;
  6537. /* continue; - prone to quadratic behavior, smarter code: */
  6538. if (idx >= end)
  6539. break;
  6540. if (str[0] == '*') {
  6541. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6542. * it would never match "ong_string" etc, no point in trying.
  6543. */
  6544. goto skip_matching;
  6545. }
  6546. goto try_to_match;
  6547. }
  6548. if (subtype == VSREPLACEALL) {
  6549. while (idx < loc) {
  6550. if (quotes && (unsigned char)*idx == CTLESC)
  6551. idx++;
  6552. idx++;
  6553. rmesc++;
  6554. }
  6555. } else {
  6556. idx = loc;
  6557. }
  6558. //bb_error_msg("repl:'%s'", repl);
  6559. for (loc = (char*)repl; *loc; loc++) {
  6560. char *restart_detect = stackblock();
  6561. if (quotes && *loc == '\\') {
  6562. STPUTC(CTLESC, expdest);
  6563. len++;
  6564. }
  6565. STPUTC(*loc, expdest);
  6566. if (stackblock() != restart_detect)
  6567. goto restart;
  6568. len++;
  6569. }
  6570. if (subtype == VSREPLACE) {
  6571. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6572. while (*idx) {
  6573. char *restart_detect = stackblock();
  6574. STPUTC(*idx, expdest);
  6575. if (stackblock() != restart_detect)
  6576. goto restart;
  6577. len++;
  6578. idx++;
  6579. }
  6580. break;
  6581. }
  6582. }
  6583. /* We've put the replaced text into a buffer at workloc, now
  6584. * move it to the right place and adjust the stack.
  6585. */
  6586. STPUTC('\0', expdest);
  6587. startp = (char *)stackblock() + startloc;
  6588. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6589. //bb_error_msg("startp:'%s'", startp);
  6590. loc = startp + len;
  6591. goto out;
  6592. }
  6593. #endif /* BASH_PATTERN_SUBST */
  6594. subtype -= VSTRIMRIGHT;
  6595. #if DEBUG
  6596. if (subtype < 0 || subtype > 7)
  6597. abort();
  6598. #endif
  6599. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6600. zero = subtype >> 1;
  6601. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6602. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6603. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6604. if (loc) {
  6605. if (zero) {
  6606. memmove(startp, loc, str - loc);
  6607. loc = startp + (str - loc) - 1;
  6608. }
  6609. *loc = '\0';
  6610. } else
  6611. loc = str - 1;
  6612. out:
  6613. amount = loc - expdest;
  6614. STADJUST(amount, expdest);
  6615. #if BASH_PATTERN_SUBST
  6616. out1:
  6617. #endif
  6618. /* Remove any recorded regions beyond start of variable */
  6619. removerecordregions(startloc);
  6620. return p;
  6621. }
  6622. /*
  6623. * Add the value of a specialized variable to the stack string.
  6624. * name parameter (examples):
  6625. * ash -c 'echo $1' name:'1='
  6626. * ash -c 'echo $qwe' name:'qwe='
  6627. * ash -c 'echo $$' name:'$='
  6628. * ash -c 'echo ${$}' name:'$='
  6629. * ash -c 'echo ${$##q}' name:'$=q'
  6630. * ash -c 'echo ${#$}' name:'$='
  6631. * note: examples with bad shell syntax:
  6632. * ash -c 'echo ${#$1}' name:'$=1'
  6633. * ash -c 'echo ${#1#}' name:'1=#'
  6634. */
  6635. static NOINLINE ssize_t
  6636. varvalue(char *name, int varflags, int flags, int quoted)
  6637. {
  6638. const char *p;
  6639. int num;
  6640. int i;
  6641. ssize_t len = 0;
  6642. int sep;
  6643. int subtype = varflags & VSTYPE;
  6644. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6645. if (!subtype) {
  6646. if (discard)
  6647. return -1;
  6648. raise_error_syntax("bad substitution");
  6649. }
  6650. flags |= EXP_KEEPNUL;
  6651. flags &= discard ? ~QUOTES_ESC : ~0;
  6652. sep = (flags & EXP_FULL) << CHAR_BIT;
  6653. switch (*name) {
  6654. case '$':
  6655. num = rootpid;
  6656. goto numvar;
  6657. case '?':
  6658. num = exitstatus;
  6659. goto numvar;
  6660. case '#':
  6661. num = shellparam.nparam;
  6662. goto numvar;
  6663. case '!':
  6664. num = backgndpid;
  6665. if (num == 0)
  6666. return -1;
  6667. numvar:
  6668. len = cvtnum(num, flags);
  6669. goto check_1char_name;
  6670. case '-':
  6671. expdest = makestrspace(NOPTS, expdest);
  6672. for (i = NOPTS - 1; i >= 0; i--) {
  6673. if (optlist[i] && optletters(i)) {
  6674. USTPUTC(optletters(i), expdest);
  6675. len++;
  6676. }
  6677. }
  6678. check_1char_name:
  6679. #if 0
  6680. /* handles cases similar to ${#$1} */
  6681. if (name[2] != '\0')
  6682. raise_error_syntax("bad substitution");
  6683. #endif
  6684. break;
  6685. case '@':
  6686. if (quoted && sep)
  6687. goto param;
  6688. /* fall through */
  6689. case '*': {
  6690. char **ap;
  6691. char sepc;
  6692. char c;
  6693. /* We will set c to 0 or ~0 depending on whether
  6694. * we're doing field splitting. We won't do field
  6695. * splitting if either we're quoted or sep is zero.
  6696. *
  6697. * Instead of testing (quoted || !sep) the following
  6698. * trick optimises away any branches by using the
  6699. * fact that EXP_QUOTED (which is the only bit that
  6700. * can be set in quoted) is the same as EXP_FULL <<
  6701. * CHAR_BIT (which is the only bit that can be set
  6702. * in sep).
  6703. */
  6704. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6705. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6706. #endif
  6707. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6708. sep &= ~quoted;
  6709. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6710. param:
  6711. sepc = sep;
  6712. ap = shellparam.p;
  6713. if (!ap)
  6714. return -1;
  6715. while ((p = *ap++) != NULL) {
  6716. len += strtodest(p, flags);
  6717. if (*ap && sep) {
  6718. len++;
  6719. memtodest(&sepc, 1, flags);
  6720. }
  6721. }
  6722. break;
  6723. } /* case '*' */
  6724. case '0':
  6725. case '1':
  6726. case '2':
  6727. case '3':
  6728. case '4':
  6729. case '5':
  6730. case '6':
  6731. case '7':
  6732. case '8':
  6733. case '9':
  6734. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6735. if (num < 0 || num > shellparam.nparam)
  6736. return -1;
  6737. p = num ? shellparam.p[num - 1] : arg0;
  6738. goto value;
  6739. default:
  6740. /* NB: name has form "VAR=..." */
  6741. p = lookupvar(name);
  6742. value:
  6743. if (!p)
  6744. return -1;
  6745. len = strtodest(p, flags);
  6746. #if ENABLE_UNICODE_SUPPORT
  6747. if (subtype == VSLENGTH && len > 0) {
  6748. reinit_unicode_for_ash();
  6749. if (unicode_status == UNICODE_ON) {
  6750. STADJUST(-len, expdest);
  6751. discard = 0;
  6752. len = unicode_strlen(p);
  6753. }
  6754. }
  6755. #endif
  6756. break;
  6757. }
  6758. if (discard)
  6759. STADJUST(-len, expdest);
  6760. return len;
  6761. }
  6762. /*
  6763. * Expand a variable, and return a pointer to the next character in the
  6764. * input string.
  6765. */
  6766. static char *
  6767. evalvar(char *p, int flag)
  6768. {
  6769. char varflags;
  6770. char subtype;
  6771. char *var;
  6772. int patloc;
  6773. int startloc;
  6774. ssize_t varlen;
  6775. int discard;
  6776. int quoted;
  6777. varflags = (unsigned char) *p++;
  6778. subtype = varflags & VSTYPE;
  6779. quoted = flag & EXP_QUOTED;
  6780. var = p;
  6781. startloc = expdest - (char *)stackblock();
  6782. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6783. again:
  6784. varlen = varvalue(var, varflags, flag, quoted);
  6785. if (varflags & VSNUL)
  6786. varlen--;
  6787. discard = varlen < 0 ? EXP_DISCARD : 0;
  6788. switch (subtype) {
  6789. case VSPLUS:
  6790. discard ^= EXP_DISCARD;
  6791. /* fall through */
  6792. case 0:
  6793. case VSMINUS:
  6794. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6795. goto record;
  6796. case VSASSIGN:
  6797. case VSQUESTION:
  6798. p = subevalvar(p, var, 0, startloc, varflags,
  6799. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6800. if ((flag | ~discard) & EXP_DISCARD)
  6801. goto record;
  6802. varflags &= ~VSNUL;
  6803. subtype = VSNORMAL;
  6804. goto again;
  6805. }
  6806. if ((discard & ~flag) && uflag)
  6807. varunset(p, var, 0, 0);
  6808. if (subtype == VSLENGTH) {
  6809. p++;
  6810. if (flag & EXP_DISCARD)
  6811. return p;
  6812. cvtnum(varlen > 0 ? varlen : 0, flag);
  6813. goto really_record;
  6814. }
  6815. if (subtype == VSNORMAL)
  6816. goto record;
  6817. #if DEBUG
  6818. switch (subtype) {
  6819. case VSTRIMLEFT:
  6820. case VSTRIMLEFTMAX:
  6821. case VSTRIMRIGHT:
  6822. case VSTRIMRIGHTMAX:
  6823. #if BASH_SUBSTR
  6824. case VSSUBSTR:
  6825. #endif
  6826. #if BASH_PATTERN_SUBST
  6827. case VSREPLACE:
  6828. case VSREPLACEALL:
  6829. #endif
  6830. break;
  6831. default:
  6832. abort();
  6833. }
  6834. #endif
  6835. flag |= discard;
  6836. if (!(flag & EXP_DISCARD)) {
  6837. /*
  6838. * Terminate the string and start recording the pattern
  6839. * right after it
  6840. */
  6841. STPUTC('\0', expdest);
  6842. }
  6843. patloc = expdest - (char *)stackblock();
  6844. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6845. record:
  6846. if ((flag | discard) & EXP_DISCARD)
  6847. return p;
  6848. really_record:
  6849. if (quoted) {
  6850. quoted = *var == '@' && shellparam.nparam;
  6851. if (!quoted)
  6852. return p;
  6853. }
  6854. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6855. return p;
  6856. }
  6857. /*
  6858. * Add a file name to the list.
  6859. */
  6860. static void
  6861. addfname(const char *name)
  6862. {
  6863. struct strlist *sp;
  6864. sp = stzalloc(sizeof(*sp));
  6865. sp->text = sstrdup(name);
  6866. *exparg.lastp = sp;
  6867. exparg.lastp = &sp->next;
  6868. }
  6869. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6870. static int
  6871. hasmeta(const char *p)
  6872. {
  6873. static const char chars[] ALIGN1 = {
  6874. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6875. };
  6876. for (;;) {
  6877. p = strpbrk(p, chars);
  6878. if (!p)
  6879. break;
  6880. switch ((unsigned char)*p) {
  6881. case CTLQUOTEMARK:
  6882. for (;;) {
  6883. p++;
  6884. if ((unsigned char)*p == CTLQUOTEMARK)
  6885. break;
  6886. if ((unsigned char)*p == CTLESC)
  6887. p++;
  6888. if (*p == '\0') /* huh? */
  6889. return 0;
  6890. }
  6891. break;
  6892. case '\\':
  6893. case CTLESC:
  6894. p++;
  6895. if (*p == '\0')
  6896. return 0;
  6897. break;
  6898. case '[':
  6899. if (!strchr(p + 1, ']')) {
  6900. /* It's not a properly closed [] pattern,
  6901. * but other metas may follow. Continue checking.
  6902. * my[file* _is_ globbed by bash
  6903. * and matches filenames like "my[file1".
  6904. */
  6905. break;
  6906. }
  6907. /* fallthrough */
  6908. default:
  6909. /* case '*': */
  6910. /* case '?': */
  6911. return 1;
  6912. }
  6913. p++;
  6914. }
  6915. return 0;
  6916. }
  6917. /* If we want to use glob() from libc... */
  6918. #if !ENABLE_ASH_INTERNAL_GLOB
  6919. /* Add the result of glob() to the list */
  6920. static void
  6921. addglob(const glob_t *pglob)
  6922. {
  6923. char **p = pglob->gl_pathv;
  6924. do {
  6925. addfname(*p);
  6926. } while (*++p);
  6927. }
  6928. static void
  6929. expandmeta(struct strlist *str /*, int flag*/)
  6930. {
  6931. /* TODO - EXP_REDIR */
  6932. while (str) {
  6933. char *p;
  6934. glob_t pglob;
  6935. int i;
  6936. if (fflag)
  6937. goto nometa;
  6938. if (!hasmeta(str->text))
  6939. goto nometa;
  6940. INT_OFF;
  6941. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6942. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6943. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6944. //
  6945. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6946. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6947. // Which means you need to unescape the string, right? Not so fast:
  6948. // if there _is_ a file named "file\?" (with backslash), it is returned
  6949. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6950. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6951. //
  6952. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6953. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6954. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6955. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6956. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6957. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6958. i = glob(p, 0, NULL, &pglob);
  6959. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6960. if (p != str->text)
  6961. free(p);
  6962. switch (i) {
  6963. case 0:
  6964. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6965. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6966. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6967. goto nometa2;
  6968. #endif
  6969. addglob(&pglob);
  6970. globfree(&pglob);
  6971. INT_ON;
  6972. break;
  6973. case GLOB_NOMATCH:
  6974. //nometa2:
  6975. globfree(&pglob);
  6976. INT_ON;
  6977. nometa:
  6978. *exparg.lastp = str;
  6979. rmescapes(str->text, 0, NULL);
  6980. exparg.lastp = &str->next;
  6981. break;
  6982. default: /* GLOB_NOSPACE */
  6983. globfree(&pglob);
  6984. INT_ON;
  6985. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6986. }
  6987. str = str->next;
  6988. }
  6989. }
  6990. #else
  6991. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6992. /*
  6993. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6994. */
  6995. typedef struct exp_t {
  6996. char *dir;
  6997. unsigned dir_max;
  6998. } exp_t;
  6999. static void
  7000. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7001. {
  7002. #define expdir exp->dir
  7003. #define expdir_max exp->dir_max
  7004. char *enddir = expdir + expdir_len;
  7005. char *p;
  7006. const char *cp;
  7007. char *start;
  7008. char *endname;
  7009. int metaflag;
  7010. struct stat statb;
  7011. DIR *dirp;
  7012. struct dirent *dp;
  7013. int atend;
  7014. int matchdot;
  7015. int esc;
  7016. metaflag = 0;
  7017. start = name;
  7018. for (p = name; esc = 0, *p; p += esc + 1) {
  7019. if (*p == '*' || *p == '?')
  7020. metaflag = 1;
  7021. else if (*p == '[') {
  7022. char *q = p + 1;
  7023. if (*q == '!')
  7024. q++;
  7025. for (;;) {
  7026. if (*q == '\\')
  7027. q++;
  7028. if (*q == '/' || *q == '\0')
  7029. break;
  7030. if (*++q == ']') {
  7031. metaflag = 1;
  7032. break;
  7033. }
  7034. }
  7035. } else {
  7036. if (*p == '\\' && p[1])
  7037. esc++;
  7038. if (p[esc] == '/') {
  7039. if (metaflag)
  7040. break;
  7041. start = p + esc + 1;
  7042. }
  7043. }
  7044. }
  7045. if (metaflag == 0) { /* we've reached the end of the file name */
  7046. if (!expdir_len)
  7047. return;
  7048. p = name;
  7049. do {
  7050. if (*p == '\\' && p[1])
  7051. p++;
  7052. *enddir++ = *p;
  7053. } while (*p++);
  7054. if (lstat(expdir, &statb) == 0)
  7055. addfname(expdir);
  7056. return;
  7057. }
  7058. endname = p;
  7059. if (name < start) {
  7060. p = name;
  7061. do {
  7062. if (*p == '\\' && p[1])
  7063. p++;
  7064. *enddir++ = *p++;
  7065. } while (p < start);
  7066. }
  7067. *enddir = '\0';
  7068. cp = expdir;
  7069. expdir_len = enddir - cp;
  7070. if (!expdir_len)
  7071. cp = ".";
  7072. dirp = opendir(cp);
  7073. if (dirp == NULL)
  7074. return;
  7075. if (*endname == 0) {
  7076. atend = 1;
  7077. } else {
  7078. atend = 0;
  7079. *endname = '\0';
  7080. endname += esc + 1;
  7081. }
  7082. name_len -= endname - name;
  7083. matchdot = 0;
  7084. p = start;
  7085. if (*p == '\\')
  7086. p++;
  7087. if (*p == '.')
  7088. matchdot++;
  7089. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7090. if (dp->d_name[0] == '.' && !matchdot)
  7091. continue;
  7092. if (pmatch(start, dp->d_name)) {
  7093. if (atend) {
  7094. strcpy(enddir, dp->d_name);
  7095. addfname(expdir);
  7096. } else {
  7097. unsigned offset;
  7098. unsigned len;
  7099. p = stpcpy(enddir, dp->d_name);
  7100. *p = '/';
  7101. offset = p - expdir + 1;
  7102. len = offset + name_len + NAME_MAX;
  7103. if (len > expdir_max) {
  7104. len += PATH_MAX;
  7105. expdir = ckrealloc(expdir, len);
  7106. expdir_max = len;
  7107. }
  7108. expmeta(exp, endname, name_len, offset);
  7109. enddir = expdir + expdir_len;
  7110. }
  7111. }
  7112. }
  7113. closedir(dirp);
  7114. if (!atend)
  7115. endname[-esc - 1] = esc ? '\\' : '/';
  7116. #undef expdir
  7117. #undef expdir_max
  7118. }
  7119. static struct strlist *
  7120. msort(struct strlist *list, int len)
  7121. {
  7122. struct strlist *p, *q = NULL;
  7123. struct strlist **lpp;
  7124. int half;
  7125. int n;
  7126. if (len <= 1)
  7127. return list;
  7128. half = len >> 1;
  7129. p = list;
  7130. for (n = half; --n >= 0;) {
  7131. q = p;
  7132. p = p->next;
  7133. }
  7134. q->next = NULL; /* terminate first half of list */
  7135. q = msort(list, half); /* sort first half of list */
  7136. p = msort(p, len - half); /* sort second half */
  7137. lpp = &list;
  7138. for (;;) {
  7139. #if ENABLE_LOCALE_SUPPORT
  7140. if (strcoll(p->text, q->text) < 0)
  7141. #else
  7142. if (strcmp(p->text, q->text) < 0)
  7143. #endif
  7144. {
  7145. *lpp = p;
  7146. lpp = &p->next;
  7147. p = *lpp;
  7148. if (p == NULL) {
  7149. *lpp = q;
  7150. break;
  7151. }
  7152. } else {
  7153. *lpp = q;
  7154. lpp = &q->next;
  7155. q = *lpp;
  7156. if (q == NULL) {
  7157. *lpp = p;
  7158. break;
  7159. }
  7160. }
  7161. }
  7162. return list;
  7163. }
  7164. /*
  7165. * Sort the results of file name expansion. It calculates the number of
  7166. * strings to sort and then calls msort (short for merge sort) to do the
  7167. * work.
  7168. */
  7169. static struct strlist *
  7170. expsort(struct strlist *str)
  7171. {
  7172. int len;
  7173. struct strlist *sp;
  7174. len = 0;
  7175. for (sp = str; sp; sp = sp->next)
  7176. len++;
  7177. return msort(str, len);
  7178. }
  7179. static void
  7180. expandmeta(struct strlist *str /*, int flag*/)
  7181. {
  7182. /* TODO - EXP_REDIR */
  7183. while (str) {
  7184. exp_t exp;
  7185. struct strlist **savelastp;
  7186. struct strlist *sp;
  7187. char *p;
  7188. unsigned len;
  7189. if (fflag)
  7190. goto nometa;
  7191. if (!hasmeta(str->text))
  7192. goto nometa;
  7193. savelastp = exparg.lastp;
  7194. INT_OFF;
  7195. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7196. len = strlen(p);
  7197. exp.dir_max = len + PATH_MAX;
  7198. exp.dir = ckmalloc(exp.dir_max);
  7199. expmeta(&exp, p, len, 0);
  7200. free(exp.dir);
  7201. if (p != str->text)
  7202. free(p);
  7203. INT_ON;
  7204. if (exparg.lastp == savelastp) {
  7205. /*
  7206. * no matches
  7207. */
  7208. nometa:
  7209. *exparg.lastp = str;
  7210. rmescapes(str->text, 0, NULL);
  7211. exparg.lastp = &str->next;
  7212. } else {
  7213. *exparg.lastp = NULL;
  7214. *savelastp = sp = expsort(*savelastp);
  7215. while (sp->next != NULL)
  7216. sp = sp->next;
  7217. exparg.lastp = &sp->next;
  7218. }
  7219. str = str->next;
  7220. }
  7221. }
  7222. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7223. /*
  7224. * Perform variable substitution and command substitution on an argument,
  7225. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7226. * perform splitting and file name expansion. When arglist is NULL, perform
  7227. * here document expansion.
  7228. */
  7229. static void
  7230. expandarg(union node *arg, struct arglist *arglist, int flag)
  7231. {
  7232. struct strlist *sp;
  7233. char *p;
  7234. argbackq = arg->narg.backquote;
  7235. STARTSTACKSTR(expdest);
  7236. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7237. argstr(arg->narg.text, flag);
  7238. if (arglist == NULL) {
  7239. /* here document expanded */
  7240. goto out;
  7241. }
  7242. p = grabstackstr(expdest);
  7243. TRACE(("expandarg: p:'%s'\n", p));
  7244. exparg.lastp = &exparg.list;
  7245. /*
  7246. * TODO - EXP_REDIR
  7247. */
  7248. if (flag & EXP_FULL) {
  7249. ifsbreakup(p, &exparg);
  7250. *exparg.lastp = NULL;
  7251. exparg.lastp = &exparg.list;
  7252. expandmeta(exparg.list /*, flag*/);
  7253. } else {
  7254. sp = stzalloc(sizeof(*sp));
  7255. sp->text = p;
  7256. *exparg.lastp = sp;
  7257. exparg.lastp = &sp->next;
  7258. }
  7259. *exparg.lastp = NULL;
  7260. if (exparg.list) {
  7261. *arglist->lastp = exparg.list;
  7262. arglist->lastp = exparg.lastp;
  7263. }
  7264. out:
  7265. ifsfree();
  7266. }
  7267. /*
  7268. * Expand shell variables and backquotes inside a here document.
  7269. */
  7270. static void
  7271. expandhere(union node *arg)
  7272. {
  7273. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7274. }
  7275. /*
  7276. * Returns true if the pattern matches the string.
  7277. */
  7278. static int
  7279. patmatch(char *pattern, const char *string)
  7280. {
  7281. char *p = preglob(pattern, 0);
  7282. int r = pmatch(p, string);
  7283. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7284. return r;
  7285. }
  7286. /*
  7287. * See if a pattern matches in a case statement.
  7288. */
  7289. static int
  7290. casematch(union node *pattern, char *val)
  7291. {
  7292. struct stackmark smark;
  7293. int result;
  7294. setstackmark(&smark);
  7295. argbackq = pattern->narg.backquote;
  7296. STARTSTACKSTR(expdest);
  7297. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7298. ifsfree();
  7299. result = patmatch(stackblock(), val);
  7300. popstackmark(&smark);
  7301. return result;
  7302. }
  7303. /* ============ find_command */
  7304. struct builtincmd {
  7305. const char *name;
  7306. int (*builtin)(int, char **) FAST_FUNC;
  7307. /* unsigned flags; */
  7308. };
  7309. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7310. /* "regular" builtins always take precedence over commands,
  7311. * regardless of PATH=....%builtin... position */
  7312. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7313. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7314. struct cmdentry {
  7315. smallint cmdtype; /* CMDxxx */
  7316. union param {
  7317. int index;
  7318. /* index >= 0 for commands without path (slashes) */
  7319. /* (TODO: what exactly does the value mean? PATH position?) */
  7320. /* index == -1 for commands with slashes */
  7321. /* index == (-2 - applet_no) for NOFORK applets */
  7322. const struct builtincmd *cmd;
  7323. struct funcnode *func;
  7324. } u;
  7325. };
  7326. /* values of cmdtype */
  7327. #define CMDUNKNOWN -1 /* no entry in table for command */
  7328. #define CMDNORMAL 0 /* command is an executable program */
  7329. #define CMDFUNCTION 1 /* command is a shell function */
  7330. #define CMDBUILTIN 2 /* command is a shell builtin */
  7331. /* action to find_command() */
  7332. #define DO_ERR 0x01 /* prints errors */
  7333. #define DO_ABS 0x02 /* checks absolute paths */
  7334. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7335. #define DO_ALTPATH 0x08 /* using alternate path */
  7336. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7337. static void find_command(char *, struct cmdentry *, int, const char *);
  7338. /* ============ Hashing commands */
  7339. /*
  7340. * When commands are first encountered, they are entered in a hash table.
  7341. * This ensures that a full path search will not have to be done for them
  7342. * on each invocation.
  7343. *
  7344. * We should investigate converting to a linear search, even though that
  7345. * would make the command name "hash" a misnomer.
  7346. */
  7347. struct tblentry {
  7348. struct tblentry *next; /* next entry in hash chain */
  7349. union param param; /* definition of builtin function */
  7350. smallint cmdtype; /* CMDxxx */
  7351. char rehash; /* if set, cd done since entry created */
  7352. char cmdname[1]; /* name of command */
  7353. };
  7354. static struct tblentry **cmdtable;
  7355. #define INIT_G_cmdtable() do { \
  7356. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7357. } while (0)
  7358. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7359. static void
  7360. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7361. {
  7362. #if ENABLE_FEATURE_SH_STANDALONE
  7363. if (applet_no >= 0) {
  7364. if (APPLET_IS_NOEXEC(applet_no)) {
  7365. clearenv();
  7366. while (*envp)
  7367. putenv(*envp++);
  7368. popredir(/*drop:*/ 1);
  7369. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7370. }
  7371. /* re-exec ourselves with the new arguments */
  7372. execve(bb_busybox_exec_path, argv, envp);
  7373. /* If they called chroot or otherwise made the binary no longer
  7374. * executable, fall through */
  7375. }
  7376. #endif
  7377. repeat:
  7378. #ifdef SYSV
  7379. do {
  7380. execve(cmd, argv, envp);
  7381. } while (errno == EINTR);
  7382. #else
  7383. execve(cmd, argv, envp);
  7384. #endif
  7385. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7386. /* Run "cmd" as a shell script:
  7387. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7388. * "If the execve() function fails with ENOEXEC, the shell
  7389. * shall execute a command equivalent to having a shell invoked
  7390. * with the command name as its first operand,
  7391. * with any remaining arguments passed to the new shell"
  7392. *
  7393. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7394. * just call ourselves.
  7395. *
  7396. * Note that bash reads ~80 chars of the file, and if it sees
  7397. * a zero byte before it sees newline, it doesn't try to
  7398. * interpret it, but fails with "cannot execute binary file"
  7399. * message and exit code 126. For one, this prevents attempts
  7400. * to interpret foreign ELF binaries as shell scripts.
  7401. */
  7402. argv[0] = (char*) cmd;
  7403. cmd = bb_busybox_exec_path;
  7404. /* NB: this is only possible because all callers of shellexec()
  7405. * ensure that the argv[-1] slot exists!
  7406. */
  7407. argv--;
  7408. argv[0] = (char*) "ash";
  7409. goto repeat;
  7410. }
  7411. }
  7412. /*
  7413. * Exec a program. Never returns. If you change this routine, you may
  7414. * have to change the find_command routine as well.
  7415. * argv[-1] must exist and be writable! See tryexec() for why.
  7416. */
  7417. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7418. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7419. {
  7420. char *cmdname;
  7421. int e;
  7422. char **envp;
  7423. int exerrno;
  7424. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7425. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7426. if (strchr(prog, '/') != NULL
  7427. #if ENABLE_FEATURE_SH_STANDALONE
  7428. || (applet_no = find_applet_by_name(prog)) >= 0
  7429. #endif
  7430. ) {
  7431. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7432. if (applet_no >= 0) {
  7433. /* We tried execing ourself, but it didn't work.
  7434. * Maybe /proc/self/exe doesn't exist?
  7435. * Try $PATH search.
  7436. */
  7437. goto try_PATH;
  7438. }
  7439. e = errno;
  7440. } else {
  7441. try_PATH:
  7442. e = ENOENT;
  7443. while (padvance(&path, argv[0]) >= 0) {
  7444. cmdname = stackblock();
  7445. if (--idx < 0 && pathopt == NULL) {
  7446. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7447. if (errno != ENOENT && errno != ENOTDIR)
  7448. e = errno;
  7449. }
  7450. }
  7451. }
  7452. /* Map to POSIX errors */
  7453. switch (e) {
  7454. default:
  7455. exerrno = 126;
  7456. break;
  7457. case ELOOP:
  7458. case ENAMETOOLONG:
  7459. case ENOENT:
  7460. case ENOTDIR:
  7461. exerrno = 127;
  7462. break;
  7463. }
  7464. exitstatus = exerrno;
  7465. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7466. prog, e, suppress_int));
  7467. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7468. /* NOTREACHED */
  7469. }
  7470. static void
  7471. printentry(struct tblentry *cmdp)
  7472. {
  7473. int idx;
  7474. const char *path;
  7475. char *name;
  7476. idx = cmdp->param.index;
  7477. path = pathval();
  7478. do {
  7479. padvance(&path, cmdp->cmdname);
  7480. } while (--idx >= 0);
  7481. name = stackblock();
  7482. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7483. }
  7484. /*
  7485. * Clear out command entries.
  7486. */
  7487. static void
  7488. clearcmdentry(void)
  7489. {
  7490. struct tblentry **tblp;
  7491. struct tblentry **pp;
  7492. struct tblentry *cmdp;
  7493. INT_OFF;
  7494. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7495. pp = tblp;
  7496. while ((cmdp = *pp) != NULL) {
  7497. if (cmdp->cmdtype == CMDNORMAL
  7498. || (cmdp->cmdtype == CMDBUILTIN
  7499. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7500. && builtinloc > 0
  7501. )
  7502. ) {
  7503. *pp = cmdp->next;
  7504. free(cmdp);
  7505. } else {
  7506. pp = &cmdp->next;
  7507. }
  7508. }
  7509. }
  7510. INT_ON;
  7511. }
  7512. /*
  7513. * Locate a command in the command hash table. If "add" is nonzero,
  7514. * add the command to the table if it is not already present. The
  7515. * variable "lastcmdentry" is set to point to the address of the link
  7516. * pointing to the entry, so that delete_cmd_entry can delete the
  7517. * entry.
  7518. *
  7519. * Interrupts must be off if called with add != 0.
  7520. */
  7521. static struct tblentry **lastcmdentry;
  7522. static struct tblentry *
  7523. cmdlookup(const char *name, int add)
  7524. {
  7525. unsigned int hashval;
  7526. const char *p;
  7527. struct tblentry *cmdp;
  7528. struct tblentry **pp;
  7529. p = name;
  7530. hashval = (unsigned char)*p << 4;
  7531. while (*p)
  7532. hashval += (unsigned char)*p++;
  7533. hashval &= 0x7FFF;
  7534. pp = &cmdtable[hashval % CMDTABLESIZE];
  7535. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7536. if (strcmp(cmdp->cmdname, name) == 0)
  7537. break;
  7538. pp = &cmdp->next;
  7539. }
  7540. if (add && cmdp == NULL) {
  7541. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7542. + strlen(name)
  7543. /* + 1 - already done because
  7544. * tblentry::cmdname is char[1] */);
  7545. /*cmdp->next = NULL; - ckzalloc did it */
  7546. cmdp->cmdtype = CMDUNKNOWN;
  7547. strcpy(cmdp->cmdname, name);
  7548. }
  7549. lastcmdentry = pp;
  7550. return cmdp;
  7551. }
  7552. /*
  7553. * Delete the command entry returned on the last lookup.
  7554. */
  7555. static void
  7556. delete_cmd_entry(void)
  7557. {
  7558. struct tblentry *cmdp;
  7559. INT_OFF;
  7560. cmdp = *lastcmdentry;
  7561. *lastcmdentry = cmdp->next;
  7562. if (cmdp->cmdtype == CMDFUNCTION)
  7563. freefunc(cmdp->param.func);
  7564. free(cmdp);
  7565. INT_ON;
  7566. }
  7567. /*
  7568. * Add a new command entry, replacing any existing command entry for
  7569. * the same name - except special builtins.
  7570. */
  7571. static void
  7572. addcmdentry(char *name, struct cmdentry *entry)
  7573. {
  7574. struct tblentry *cmdp;
  7575. cmdp = cmdlookup(name, 1);
  7576. if (cmdp->cmdtype == CMDFUNCTION) {
  7577. freefunc(cmdp->param.func);
  7578. }
  7579. cmdp->cmdtype = entry->cmdtype;
  7580. cmdp->param = entry->u;
  7581. cmdp->rehash = 0;
  7582. }
  7583. static int FAST_FUNC
  7584. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7585. {
  7586. struct tblentry **pp;
  7587. struct tblentry *cmdp;
  7588. int c;
  7589. struct cmdentry entry;
  7590. char *name;
  7591. if (nextopt("r") != '\0') {
  7592. clearcmdentry();
  7593. return 0;
  7594. }
  7595. if (*argptr == NULL) {
  7596. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7597. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7598. if (cmdp->cmdtype == CMDNORMAL)
  7599. printentry(cmdp);
  7600. }
  7601. }
  7602. return 0;
  7603. }
  7604. c = 0;
  7605. while ((name = *argptr) != NULL) {
  7606. cmdp = cmdlookup(name, 0);
  7607. if (cmdp != NULL
  7608. && (cmdp->cmdtype == CMDNORMAL
  7609. || (cmdp->cmdtype == CMDBUILTIN
  7610. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7611. && builtinloc > 0
  7612. )
  7613. )
  7614. ) {
  7615. delete_cmd_entry();
  7616. }
  7617. find_command(name, &entry, DO_ERR, pathval());
  7618. if (entry.cmdtype == CMDUNKNOWN)
  7619. c = 1;
  7620. argptr++;
  7621. }
  7622. return c;
  7623. }
  7624. /*
  7625. * Called when a cd is done. Marks all commands so the next time they
  7626. * are executed they will be rehashed.
  7627. */
  7628. static void
  7629. hashcd(void)
  7630. {
  7631. struct tblentry **pp;
  7632. struct tblentry *cmdp;
  7633. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7634. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7635. if (cmdp->cmdtype == CMDNORMAL
  7636. || (cmdp->cmdtype == CMDBUILTIN
  7637. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7638. && builtinloc > 0)
  7639. ) {
  7640. cmdp->rehash = 1;
  7641. }
  7642. }
  7643. }
  7644. }
  7645. /*
  7646. * Fix command hash table when PATH changed.
  7647. * Called before PATH is changed. The argument is the new value of PATH;
  7648. * pathval() still returns the old value at this point.
  7649. * Called with interrupts off.
  7650. */
  7651. static void FAST_FUNC
  7652. changepath(const char *newval)
  7653. {
  7654. const char *new;
  7655. int idx;
  7656. int bltin;
  7657. new = newval;
  7658. idx = 0;
  7659. bltin = -1;
  7660. for (;;) {
  7661. if (*new == '%' && prefix(new + 1, "builtin")) {
  7662. bltin = idx;
  7663. break;
  7664. }
  7665. new = strchr(new, ':');
  7666. if (!new)
  7667. break;
  7668. idx++;
  7669. new++;
  7670. }
  7671. builtinloc = bltin;
  7672. clearcmdentry();
  7673. }
  7674. enum {
  7675. TEOF,
  7676. TNL,
  7677. TREDIR,
  7678. TWORD,
  7679. TSEMI,
  7680. TBACKGND,
  7681. TAND,
  7682. TOR,
  7683. TPIPE,
  7684. TLP,
  7685. TRP,
  7686. TENDCASE,
  7687. TENDBQUOTE,
  7688. TNOT,
  7689. TCASE,
  7690. TDO,
  7691. TDONE,
  7692. TELIF,
  7693. TELSE,
  7694. TESAC,
  7695. TFI,
  7696. TFOR,
  7697. #if BASH_FUNCTION
  7698. TFUNCTION,
  7699. #endif
  7700. TIF,
  7701. TIN,
  7702. TTHEN,
  7703. TUNTIL,
  7704. TWHILE,
  7705. TBEGIN,
  7706. TEND
  7707. };
  7708. typedef smallint token_id_t;
  7709. /* Nth bit indicates if token marks the end of a list */
  7710. enum {
  7711. tokendlist = 0
  7712. /* 0 */ | (1u << TEOF)
  7713. /* 1 */ | (0u << TNL)
  7714. /* 2 */ | (0u << TREDIR)
  7715. /* 3 */ | (0u << TWORD)
  7716. /* 4 */ | (0u << TSEMI)
  7717. /* 5 */ | (0u << TBACKGND)
  7718. /* 6 */ | (0u << TAND)
  7719. /* 7 */ | (0u << TOR)
  7720. /* 8 */ | (0u << TPIPE)
  7721. /* 9 */ | (0u << TLP)
  7722. /* 10 */ | (1u << TRP)
  7723. /* 11 */ | (1u << TENDCASE)
  7724. /* 12 */ | (1u << TENDBQUOTE)
  7725. /* 13 */ | (0u << TNOT)
  7726. /* 14 */ | (0u << TCASE)
  7727. /* 15 */ | (1u << TDO)
  7728. /* 16 */ | (1u << TDONE)
  7729. /* 17 */ | (1u << TELIF)
  7730. /* 18 */ | (1u << TELSE)
  7731. /* 19 */ | (1u << TESAC)
  7732. /* 20 */ | (1u << TFI)
  7733. /* 21 */ | (0u << TFOR)
  7734. #if BASH_FUNCTION
  7735. /* 22 */ | (0u << TFUNCTION)
  7736. #endif
  7737. /* 23 */ | (0u << TIF)
  7738. /* 24 */ | (0u << TIN)
  7739. /* 25 */ | (1u << TTHEN)
  7740. /* 26 */ | (0u << TUNTIL)
  7741. /* 27 */ | (0u << TWHILE)
  7742. /* 28 */ | (0u << TBEGIN)
  7743. /* 29 */ | (1u << TEND)
  7744. , /* thus far 29 bits used */
  7745. };
  7746. static const char *const tokname_array[] ALIGN_PTR = {
  7747. "end of file",
  7748. "newline",
  7749. "redirection",
  7750. "word",
  7751. ";",
  7752. "&",
  7753. "&&",
  7754. "||",
  7755. "|",
  7756. "(",
  7757. ")",
  7758. ";;",
  7759. "`",
  7760. #define KWDOFFSET 13
  7761. /* the following are keywords */
  7762. "!",
  7763. "case",
  7764. "do",
  7765. "done",
  7766. "elif",
  7767. "else",
  7768. "esac",
  7769. "fi",
  7770. "for",
  7771. #if BASH_FUNCTION
  7772. "function",
  7773. #endif
  7774. "if",
  7775. "in",
  7776. "then",
  7777. "until",
  7778. "while",
  7779. "{",
  7780. "}",
  7781. };
  7782. /* Wrapper around strcmp for qsort/bsearch/... */
  7783. static int
  7784. pstrcmp(const void *a, const void *b)
  7785. {
  7786. return strcmp((char*)a, *(char**)b);
  7787. }
  7788. static const char *const *
  7789. findkwd(const char *s)
  7790. {
  7791. return bsearch(s, tokname_array + KWDOFFSET,
  7792. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7793. sizeof(tokname_array[0]), pstrcmp);
  7794. }
  7795. /*
  7796. * Locate and print what a word is...
  7797. */
  7798. static int
  7799. describe_command(char *command, const char *path, int describe_command_verbose)
  7800. {
  7801. struct cmdentry entry;
  7802. #if ENABLE_ASH_ALIAS
  7803. const struct alias *ap;
  7804. #endif
  7805. path = path ? path : pathval();
  7806. if (describe_command_verbose) {
  7807. out1str(command);
  7808. }
  7809. /* First look at the keywords */
  7810. if (findkwd(command)) {
  7811. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7812. goto out;
  7813. }
  7814. #if ENABLE_ASH_ALIAS
  7815. /* Then look at the aliases */
  7816. ap = lookupalias(command, 0);
  7817. if (ap != NULL) {
  7818. if (!describe_command_verbose) {
  7819. out1str("alias ");
  7820. printalias(ap);
  7821. return 0;
  7822. }
  7823. out1fmt(" is an alias for %s", ap->val);
  7824. goto out;
  7825. }
  7826. #endif
  7827. /* Brute force */
  7828. find_command(command, &entry, DO_ABS, path);
  7829. switch (entry.cmdtype) {
  7830. case CMDNORMAL: {
  7831. int j = entry.u.index;
  7832. char *p;
  7833. if (j < 0) {
  7834. p = command;
  7835. } else {
  7836. do {
  7837. padvance(&path, command);
  7838. } while (--j >= 0);
  7839. p = stackblock();
  7840. }
  7841. if (describe_command_verbose) {
  7842. out1fmt(" is %s", p);
  7843. } else {
  7844. out1str(p);
  7845. }
  7846. break;
  7847. }
  7848. case CMDFUNCTION:
  7849. if (describe_command_verbose) {
  7850. /*out1str(" is a shell function");*/
  7851. out1str(" is a function"); /* bash says this */
  7852. } else {
  7853. out1str(command);
  7854. }
  7855. break;
  7856. case CMDBUILTIN:
  7857. if (describe_command_verbose) {
  7858. out1fmt(" is a %sshell builtin",
  7859. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7860. "special " : nullstr
  7861. );
  7862. } else {
  7863. out1str(command);
  7864. }
  7865. break;
  7866. default:
  7867. if (describe_command_verbose) {
  7868. out1str(": not found\n");
  7869. }
  7870. return 127;
  7871. }
  7872. out:
  7873. out1str("\n");
  7874. return 0;
  7875. }
  7876. static int FAST_FUNC
  7877. typecmd(int argc UNUSED_PARAM, char **argv)
  7878. {
  7879. int i = 1;
  7880. int err = 0;
  7881. int verbose = 1;
  7882. /* type -p ... ? (we don't bother checking for 'p') */
  7883. if (argv[1] && argv[1][0] == '-') {
  7884. i++;
  7885. verbose = 0;
  7886. }
  7887. while (argv[i]) {
  7888. err |= describe_command(argv[i++], NULL, verbose);
  7889. }
  7890. return err;
  7891. }
  7892. static struct strlist *
  7893. fill_arglist(struct arglist *arglist, union node **argpp)
  7894. {
  7895. struct strlist **lastp = arglist->lastp;
  7896. union node *argp;
  7897. while ((argp = *argpp) != NULL) {
  7898. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  7899. *argpp = argp->narg.next;
  7900. if (*lastp)
  7901. break;
  7902. }
  7903. return *lastp;
  7904. }
  7905. #if ENABLE_ASH_CMDCMD
  7906. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7907. static int
  7908. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  7909. {
  7910. struct strlist *sp = arglist->list;
  7911. char *cp, c;
  7912. for (;;) {
  7913. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  7914. if (!sp)
  7915. return 0;
  7916. cp = sp->text;
  7917. if (*cp++ != '-')
  7918. break;
  7919. c = *cp++;
  7920. if (!c)
  7921. break;
  7922. if (c == '-' && !*cp) {
  7923. if (!sp->next && !fill_arglist(arglist, argpp))
  7924. return 0;
  7925. sp = sp->next;
  7926. break;
  7927. }
  7928. do {
  7929. switch (c) {
  7930. case 'p':
  7931. *path = bb_default_path;
  7932. break;
  7933. default:
  7934. /* run 'typecmd' for other options */
  7935. return 0;
  7936. }
  7937. c = *cp++;
  7938. } while (c);
  7939. }
  7940. arglist->list = sp;
  7941. return DO_NOFUNC;
  7942. }
  7943. static int FAST_FUNC
  7944. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7945. {
  7946. char *cmd;
  7947. int c;
  7948. enum {
  7949. VERIFY_BRIEF = 1,
  7950. VERIFY_VERBOSE = 2,
  7951. } verify = 0;
  7952. const char *path = NULL;
  7953. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7954. * never reaches this function.
  7955. */
  7956. while ((c = nextopt("pvV")) != '\0')
  7957. if (c == 'V')
  7958. verify |= VERIFY_VERBOSE;
  7959. else if (c == 'v')
  7960. /*verify |= VERIFY_BRIEF*/;
  7961. #if DEBUG
  7962. else if (c != 'p')
  7963. abort();
  7964. #endif
  7965. else
  7966. path = bb_default_path;
  7967. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7968. cmd = *argptr;
  7969. if (/*verify && */ cmd)
  7970. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7971. return 0;
  7972. }
  7973. #endif
  7974. /*static int funcblocksize; // size of structures in function */
  7975. /*static int funcstringsize; // size of strings in node */
  7976. static void *funcblock; /* block to allocate function from */
  7977. static char *funcstring_end; /* end of block to allocate strings from */
  7978. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7979. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7980. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7981. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7982. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7983. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7984. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7985. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7986. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7987. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7988. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7989. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7990. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7991. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7992. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7993. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7994. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7995. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7996. #if BASH_REDIR_OUTPUT
  7997. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7998. #endif
  7999. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8000. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8001. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8002. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8003. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8004. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8005. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8006. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8007. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8008. };
  8009. static int calcsize(int funcblocksize, union node *n);
  8010. static int
  8011. sizenodelist(int funcblocksize, struct nodelist *lp)
  8012. {
  8013. while (lp) {
  8014. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8015. funcblocksize = calcsize(funcblocksize, lp->n);
  8016. lp = lp->next;
  8017. }
  8018. return funcblocksize;
  8019. }
  8020. static int
  8021. calcsize(int funcblocksize, union node *n)
  8022. {
  8023. if (n == NULL)
  8024. return funcblocksize;
  8025. funcblocksize += nodesize[n->type];
  8026. switch (n->type) {
  8027. case NCMD:
  8028. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8029. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8030. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8031. break;
  8032. case NPIPE:
  8033. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8034. break;
  8035. case NREDIR:
  8036. case NBACKGND:
  8037. case NSUBSHELL:
  8038. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8039. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8040. break;
  8041. case NAND:
  8042. case NOR:
  8043. case NSEMI:
  8044. case NWHILE:
  8045. case NUNTIL:
  8046. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8047. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8048. break;
  8049. case NIF:
  8050. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8051. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8052. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8053. break;
  8054. case NFOR:
  8055. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8056. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8057. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8058. break;
  8059. case NCASE:
  8060. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8061. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8062. break;
  8063. case NCLIST:
  8064. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8065. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8066. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8067. break;
  8068. case NDEFUN:
  8069. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8070. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8071. break;
  8072. case NARG:
  8073. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8074. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8075. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8076. break;
  8077. case NTO:
  8078. #if BASH_REDIR_OUTPUT
  8079. case NTO2:
  8080. #endif
  8081. case NCLOBBER:
  8082. case NFROM:
  8083. case NFROMTO:
  8084. case NAPPEND:
  8085. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8086. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8087. break;
  8088. case NTOFD:
  8089. case NFROMFD:
  8090. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8091. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8092. break;
  8093. case NHERE:
  8094. case NXHERE:
  8095. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8096. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8097. break;
  8098. case NNOT:
  8099. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8100. break;
  8101. };
  8102. return funcblocksize;
  8103. }
  8104. static char *
  8105. nodeckstrdup(char *s)
  8106. {
  8107. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8108. return strcpy(funcstring_end, s);
  8109. }
  8110. static union node *copynode(union node *);
  8111. static struct nodelist *
  8112. copynodelist(struct nodelist *lp)
  8113. {
  8114. struct nodelist *start;
  8115. struct nodelist **lpp;
  8116. lpp = &start;
  8117. while (lp) {
  8118. *lpp = funcblock;
  8119. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8120. (*lpp)->n = copynode(lp->n);
  8121. lp = lp->next;
  8122. lpp = &(*lpp)->next;
  8123. }
  8124. *lpp = NULL;
  8125. return start;
  8126. }
  8127. static union node *
  8128. copynode(union node *n)
  8129. {
  8130. union node *new;
  8131. if (n == NULL)
  8132. return NULL;
  8133. new = funcblock;
  8134. funcblock = (char *) funcblock + nodesize[n->type];
  8135. switch (n->type) {
  8136. case NCMD:
  8137. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8138. new->ncmd.args = copynode(n->ncmd.args);
  8139. new->ncmd.assign = copynode(n->ncmd.assign);
  8140. new->ncmd.linno = n->ncmd.linno;
  8141. break;
  8142. case NPIPE:
  8143. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8144. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8145. break;
  8146. case NREDIR:
  8147. case NBACKGND:
  8148. case NSUBSHELL:
  8149. new->nredir.redirect = copynode(n->nredir.redirect);
  8150. new->nredir.n = copynode(n->nredir.n);
  8151. new->nredir.linno = n->nredir.linno;
  8152. break;
  8153. case NAND:
  8154. case NOR:
  8155. case NSEMI:
  8156. case NWHILE:
  8157. case NUNTIL:
  8158. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8159. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8160. break;
  8161. case NIF:
  8162. new->nif.elsepart = copynode(n->nif.elsepart);
  8163. new->nif.ifpart = copynode(n->nif.ifpart);
  8164. new->nif.test = copynode(n->nif.test);
  8165. break;
  8166. case NFOR:
  8167. new->nfor.var = nodeckstrdup(n->nfor.var);
  8168. new->nfor.body = copynode(n->nfor.body);
  8169. new->nfor.args = copynode(n->nfor.args);
  8170. new->nfor.linno = n->nfor.linno;
  8171. break;
  8172. case NCASE:
  8173. new->ncase.cases = copynode(n->ncase.cases);
  8174. new->ncase.expr = copynode(n->ncase.expr);
  8175. new->ncase.linno = n->ncase.linno;
  8176. break;
  8177. case NCLIST:
  8178. new->nclist.body = copynode(n->nclist.body);
  8179. new->nclist.pattern = copynode(n->nclist.pattern);
  8180. new->nclist.next = copynode(n->nclist.next);
  8181. break;
  8182. case NDEFUN:
  8183. new->ndefun.body = copynode(n->ndefun.body);
  8184. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8185. new->ndefun.linno = n->ndefun.linno;
  8186. break;
  8187. case NARG:
  8188. new->narg.backquote = copynodelist(n->narg.backquote);
  8189. new->narg.text = nodeckstrdup(n->narg.text);
  8190. new->narg.next = copynode(n->narg.next);
  8191. break;
  8192. case NTO:
  8193. #if BASH_REDIR_OUTPUT
  8194. case NTO2:
  8195. #endif
  8196. case NCLOBBER:
  8197. case NFROM:
  8198. case NFROMTO:
  8199. case NAPPEND:
  8200. new->nfile.fname = copynode(n->nfile.fname);
  8201. new->nfile.fd = n->nfile.fd;
  8202. new->nfile.next = copynode(n->nfile.next);
  8203. break;
  8204. case NTOFD:
  8205. case NFROMFD:
  8206. new->ndup.vname = copynode(n->ndup.vname);
  8207. new->ndup.dupfd = n->ndup.dupfd;
  8208. new->ndup.fd = n->ndup.fd;
  8209. new->ndup.next = copynode(n->ndup.next);
  8210. break;
  8211. case NHERE:
  8212. case NXHERE:
  8213. new->nhere.doc = copynode(n->nhere.doc);
  8214. new->nhere.fd = n->nhere.fd;
  8215. new->nhere.next = copynode(n->nhere.next);
  8216. break;
  8217. case NNOT:
  8218. new->nnot.com = copynode(n->nnot.com);
  8219. break;
  8220. };
  8221. new->type = n->type;
  8222. return new;
  8223. }
  8224. /*
  8225. * Make a copy of a parse tree.
  8226. */
  8227. static struct funcnode *
  8228. copyfunc(union node *n)
  8229. {
  8230. struct funcnode *f;
  8231. size_t blocksize;
  8232. /*funcstringsize = 0;*/
  8233. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8234. f = ckzalloc(blocksize /* + funcstringsize */);
  8235. funcblock = (char *) f + offsetof(struct funcnode, n);
  8236. funcstring_end = (char *) f + blocksize;
  8237. copynode(n);
  8238. /* f->count = 0; - ckzalloc did it */
  8239. return f;
  8240. }
  8241. /*
  8242. * Define a shell function.
  8243. */
  8244. static void
  8245. defun(union node *func)
  8246. {
  8247. struct cmdentry entry;
  8248. INT_OFF;
  8249. entry.cmdtype = CMDFUNCTION;
  8250. entry.u.func = copyfunc(func);
  8251. addcmdentry(func->ndefun.text, &entry);
  8252. INT_ON;
  8253. }
  8254. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8255. #define SKIPBREAK (1 << 0)
  8256. #define SKIPCONT (1 << 1)
  8257. #define SKIPFUNC (1 << 2)
  8258. #define SKIPFUNCDEF (1 << 3)
  8259. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8260. static int skipcount; /* number of levels to skip */
  8261. static int loopnest; /* current loop nesting level */
  8262. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8263. /* Forward decl way out to parsing code - dotrap needs it */
  8264. static int evalstring(char *s, int flags);
  8265. /* Called to execute a trap.
  8266. * Single callsite - at the end of evaltree().
  8267. * If we return non-zero, evaltree raises EXEXIT exception.
  8268. *
  8269. * Perhaps we should avoid entering new trap handlers
  8270. * while we are executing a trap handler. [is it a TODO?]
  8271. */
  8272. static void
  8273. dotrap(void)
  8274. {
  8275. uint8_t *g;
  8276. int sig;
  8277. int status, last_status;
  8278. if (!pending_sig)
  8279. return;
  8280. status = savestatus;
  8281. last_status = status;
  8282. if (status < 0) {
  8283. status = exitstatus;
  8284. savestatus = status;
  8285. }
  8286. pending_sig = 0;
  8287. barrier();
  8288. TRACE(("dotrap entered\n"));
  8289. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8290. char *p;
  8291. if (!*g)
  8292. continue;
  8293. if (evalskip) {
  8294. pending_sig = sig;
  8295. break;
  8296. }
  8297. p = trap[sig];
  8298. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8299. * don't upset it by resetting gotsig[SIGINT-1] */
  8300. if (sig == SIGINT && !p)
  8301. continue;
  8302. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8303. *g = 0;
  8304. if (!p)
  8305. continue;
  8306. evalstring(p, 0);
  8307. if (evalskip != SKIPFUNC)
  8308. exitstatus = status;
  8309. }
  8310. savestatus = last_status;
  8311. TRACE(("dotrap returns\n"));
  8312. }
  8313. /* forward declarations - evaluation is fairly recursive business... */
  8314. static int evalloop(union node *, int);
  8315. static int evalfor(union node *, int);
  8316. static int evalcase(union node *, int);
  8317. static int evalsubshell(union node *, int);
  8318. static void expredir(union node *);
  8319. static int evalpipe(union node *, int);
  8320. static int evalcommand(union node *, int);
  8321. static int evalbltin(const struct builtincmd *, int, char **, int);
  8322. static void prehash(union node *);
  8323. /*
  8324. * Evaluate a parse tree. The value is left in the global variable
  8325. * exitstatus.
  8326. */
  8327. static int
  8328. evaltree(union node *n, int flags)
  8329. {
  8330. int checkexit = 0;
  8331. int (*evalfn)(union node *, int);
  8332. struct stackmark smark;
  8333. int status = 0;
  8334. setstackmark(&smark);
  8335. if (n == NULL) {
  8336. TRACE(("evaltree(NULL) called\n"));
  8337. goto out;
  8338. }
  8339. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8340. dotrap();
  8341. switch (n->type) {
  8342. default:
  8343. #if DEBUG
  8344. out1fmt("Node type = %d\n", n->type);
  8345. fflush_all();
  8346. break;
  8347. #endif
  8348. case NNOT:
  8349. status = !evaltree(n->nnot.com, EV_TESTED);
  8350. goto setstatus;
  8351. case NREDIR:
  8352. errlinno = lineno = n->nredir.linno;
  8353. if (funcline)
  8354. lineno -= funcline - 1;
  8355. expredir(n->nredir.redirect);
  8356. pushredir(n->nredir.redirect);
  8357. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8358. if (!status) {
  8359. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8360. }
  8361. if (n->nredir.redirect)
  8362. popredir(/*drop:*/ 0);
  8363. goto setstatus;
  8364. case NCMD:
  8365. evalfn = evalcommand;
  8366. checkexit:
  8367. if (eflag && !(flags & EV_TESTED))
  8368. checkexit = ~0;
  8369. goto calleval;
  8370. case NFOR:
  8371. evalfn = evalfor;
  8372. goto calleval;
  8373. case NWHILE:
  8374. case NUNTIL:
  8375. evalfn = evalloop;
  8376. goto calleval;
  8377. case NSUBSHELL:
  8378. case NBACKGND:
  8379. evalfn = evalsubshell;
  8380. goto checkexit;
  8381. case NPIPE:
  8382. evalfn = evalpipe;
  8383. goto checkexit;
  8384. case NCASE:
  8385. evalfn = evalcase;
  8386. goto calleval;
  8387. case NAND:
  8388. case NOR:
  8389. case NSEMI: {
  8390. #if NAND + 1 != NOR
  8391. #error NAND + 1 != NOR
  8392. #endif
  8393. #if NOR + 1 != NSEMI
  8394. #error NOR + 1 != NSEMI
  8395. #endif
  8396. unsigned is_or = n->type - NAND;
  8397. status = evaltree(
  8398. n->nbinary.ch1,
  8399. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8400. );
  8401. if ((!status) == is_or || evalskip)
  8402. break;
  8403. n = n->nbinary.ch2;
  8404. evaln:
  8405. evalfn = evaltree;
  8406. calleval:
  8407. status = evalfn(n, flags);
  8408. goto setstatus;
  8409. }
  8410. case NIF:
  8411. status = evaltree(n->nif.test, EV_TESTED);
  8412. if (evalskip)
  8413. break;
  8414. if (!status) {
  8415. n = n->nif.ifpart;
  8416. goto evaln;
  8417. }
  8418. if (n->nif.elsepart) {
  8419. n = n->nif.elsepart;
  8420. goto evaln;
  8421. }
  8422. status = 0;
  8423. goto setstatus;
  8424. case NDEFUN:
  8425. defun(n);
  8426. /* Not necessary. To test it:
  8427. * "false; f() { qwerty; }; echo $?" should print 0.
  8428. */
  8429. /* status = 0; */
  8430. setstatus:
  8431. exitstatus = status;
  8432. break;
  8433. }
  8434. out:
  8435. /* Order of checks below is important:
  8436. * signal handlers trigger before exit caused by "set -e".
  8437. */
  8438. dotrap();
  8439. if (checkexit & status)
  8440. raise_exception(EXEND);
  8441. if (flags & EV_EXIT)
  8442. raise_exception(EXEND);
  8443. popstackmark(&smark);
  8444. TRACE(("leaving evaltree (no interrupts)\n"));
  8445. return exitstatus;
  8446. }
  8447. static int
  8448. skiploop(void)
  8449. {
  8450. int skip = evalskip;
  8451. switch (skip) {
  8452. case 0:
  8453. break;
  8454. case SKIPBREAK:
  8455. case SKIPCONT:
  8456. if (--skipcount <= 0) {
  8457. evalskip = 0;
  8458. break;
  8459. }
  8460. skip = SKIPBREAK;
  8461. break;
  8462. }
  8463. return skip;
  8464. }
  8465. static int
  8466. evalloop(union node *n, int flags)
  8467. {
  8468. int skip;
  8469. int status;
  8470. loopnest++;
  8471. status = 0;
  8472. flags &= EV_TESTED;
  8473. do {
  8474. int i;
  8475. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8476. skip = skiploop();
  8477. if (skip == SKIPFUNC)
  8478. status = i;
  8479. if (skip)
  8480. continue;
  8481. if (n->type != NWHILE)
  8482. i = !i;
  8483. if (i != 0)
  8484. break;
  8485. status = evaltree(n->nbinary.ch2, flags);
  8486. skip = skiploop();
  8487. } while (!(skip & ~SKIPCONT));
  8488. loopnest--;
  8489. return status;
  8490. }
  8491. static int
  8492. evalfor(union node *n, int flags)
  8493. {
  8494. struct arglist arglist;
  8495. union node *argp;
  8496. struct strlist *sp;
  8497. int status = 0;
  8498. errlinno = lineno = n->ncase.linno;
  8499. if (funcline)
  8500. lineno -= funcline - 1;
  8501. arglist.list = NULL;
  8502. arglist.lastp = &arglist.list;
  8503. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8504. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8505. }
  8506. *arglist.lastp = NULL;
  8507. loopnest++;
  8508. flags &= EV_TESTED;
  8509. for (sp = arglist.list; sp; sp = sp->next) {
  8510. setvar0(n->nfor.var, sp->text);
  8511. status = evaltree(n->nfor.body, flags);
  8512. if (skiploop() & ~SKIPCONT)
  8513. break;
  8514. }
  8515. loopnest--;
  8516. return status;
  8517. }
  8518. static int
  8519. evalcase(union node *n, int flags)
  8520. {
  8521. union node *cp;
  8522. union node *patp;
  8523. struct arglist arglist;
  8524. int status = 0;
  8525. errlinno = lineno = n->ncase.linno;
  8526. if (funcline)
  8527. lineno -= funcline - 1;
  8528. arglist.list = NULL;
  8529. arglist.lastp = &arglist.list;
  8530. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8531. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8532. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8533. if (casematch(patp, arglist.list->text)) {
  8534. /* Ensure body is non-empty as otherwise
  8535. * EV_EXIT may prevent us from setting the
  8536. * exit status.
  8537. */
  8538. if (evalskip == 0 && cp->nclist.body) {
  8539. status = evaltree(cp->nclist.body, flags);
  8540. }
  8541. goto out;
  8542. }
  8543. }
  8544. }
  8545. out:
  8546. return status;
  8547. }
  8548. /*
  8549. * Kick off a subshell to evaluate a tree.
  8550. */
  8551. static int
  8552. evalsubshell(union node *n, int flags)
  8553. {
  8554. struct job *jp;
  8555. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8556. int status;
  8557. errlinno = lineno = n->nredir.linno;
  8558. if (funcline)
  8559. lineno -= funcline - 1;
  8560. expredir(n->nredir.redirect);
  8561. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8562. goto nofork;
  8563. INT_OFF;
  8564. if (backgnd == FORK_FG)
  8565. get_tty_state();
  8566. jp = makejob(/*n,*/ 1);
  8567. if (forkshell(jp, n, backgnd) == 0) {
  8568. /* child */
  8569. INT_ON;
  8570. flags |= EV_EXIT;
  8571. if (backgnd)
  8572. flags &= ~EV_TESTED;
  8573. nofork:
  8574. redirect(n->nredir.redirect, 0);
  8575. evaltreenr(n->nredir.n, flags);
  8576. /* never returns */
  8577. }
  8578. /* parent */
  8579. status = 0;
  8580. if (backgnd == FORK_FG)
  8581. status = waitforjob(jp);
  8582. INT_ON;
  8583. return status;
  8584. }
  8585. /*
  8586. * Compute the names of the files in a redirection list.
  8587. */
  8588. static void fixredir(union node *, const char *, int);
  8589. static void
  8590. expredir(union node *n)
  8591. {
  8592. union node *redir;
  8593. for (redir = n; redir; redir = redir->nfile.next) {
  8594. struct arglist fn;
  8595. fn.list = NULL;
  8596. fn.lastp = &fn.list;
  8597. switch (redir->type) {
  8598. case NFROMTO:
  8599. case NFROM:
  8600. case NTO:
  8601. #if BASH_REDIR_OUTPUT
  8602. case NTO2:
  8603. #endif
  8604. case NCLOBBER:
  8605. case NAPPEND:
  8606. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8607. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8608. #if BASH_REDIR_OUTPUT
  8609. store_expfname:
  8610. #endif
  8611. #if 0
  8612. // By the design of stack allocator, the loop of this kind:
  8613. // while true; do while true; do break; done </dev/null; done
  8614. // will look like a memory leak: ash plans to free expfname's
  8615. // of "/dev/null" as soon as it finishes running the loop
  8616. // (in this case, never).
  8617. // This "fix" is wrong:
  8618. if (redir->nfile.expfname)
  8619. stunalloc(redir->nfile.expfname);
  8620. // It results in corrupted state of stacked allocations.
  8621. #endif
  8622. redir->nfile.expfname = fn.list->text;
  8623. break;
  8624. case NFROMFD:
  8625. case NTOFD: /* >& */
  8626. if (redir->ndup.vname) {
  8627. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8628. if (fn.list == NULL)
  8629. ash_msg_and_raise_error("redir error");
  8630. #if BASH_REDIR_OUTPUT
  8631. if (!isdigit_str9(fn.list->text)) {
  8632. /* >&file, not >&fd */
  8633. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8634. ash_msg_and_raise_error("redir error");
  8635. redir->type = NTO2;
  8636. goto store_expfname;
  8637. }
  8638. #endif
  8639. fixredir(redir, fn.list->text, 1);
  8640. }
  8641. break;
  8642. }
  8643. }
  8644. }
  8645. /*
  8646. * Evaluate a pipeline. All the processes in the pipeline are children
  8647. * of the process creating the pipeline. (This differs from some versions
  8648. * of the shell, which make the last process in a pipeline the parent
  8649. * of all the rest.)
  8650. */
  8651. static int
  8652. evalpipe(union node *n, int flags)
  8653. {
  8654. struct job *jp;
  8655. struct nodelist *lp;
  8656. int pipelen;
  8657. int prevfd;
  8658. int pip[2];
  8659. int status = 0;
  8660. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8661. pipelen = 0;
  8662. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8663. pipelen++;
  8664. flags |= EV_EXIT;
  8665. INT_OFF;
  8666. if (n->npipe.pipe_backgnd == 0)
  8667. get_tty_state();
  8668. jp = makejob(/*n,*/ pipelen);
  8669. prevfd = -1;
  8670. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8671. prehash(lp->n);
  8672. pip[1] = -1;
  8673. if (lp->next) {
  8674. if (pipe(pip) < 0) {
  8675. close(prevfd);
  8676. ash_msg_and_raise_perror("can't create pipe");
  8677. }
  8678. }
  8679. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8680. /* child */
  8681. INT_ON;
  8682. if (pip[1] >= 0) {
  8683. close(pip[0]);
  8684. }
  8685. if (prevfd > 0) {
  8686. dup2(prevfd, 0);
  8687. close(prevfd);
  8688. }
  8689. if (pip[1] > 1) {
  8690. dup2(pip[1], 1);
  8691. close(pip[1]);
  8692. }
  8693. evaltreenr(lp->n, flags);
  8694. /* never returns */
  8695. }
  8696. /* parent */
  8697. if (prevfd >= 0)
  8698. close(prevfd);
  8699. prevfd = pip[0];
  8700. /* Don't want to trigger debugging */
  8701. if (pip[1] != -1)
  8702. close(pip[1]);
  8703. }
  8704. if (n->npipe.pipe_backgnd == 0) {
  8705. status = waitforjob(jp);
  8706. TRACE(("evalpipe: job done exit status %d\n", status));
  8707. }
  8708. INT_ON;
  8709. return status;
  8710. }
  8711. /* setinteractive needs this forward reference */
  8712. #if EDITING_HAS_get_exe_name
  8713. static const char *get_builtin_name(int i) FAST_FUNC;
  8714. #endif
  8715. /*
  8716. * Controls whether the shell is interactive or not.
  8717. */
  8718. static void
  8719. setinteractive(int on)
  8720. {
  8721. static smallint is_interactive;
  8722. if (++on == is_interactive)
  8723. return;
  8724. is_interactive = on;
  8725. setsignal(SIGINT);
  8726. setsignal(SIGQUIT);
  8727. setsignal(SIGTERM);
  8728. if (is_interactive > 1) {
  8729. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8730. /* Looks like they want an interactive shell */
  8731. static smallint did_banner;
  8732. if (!did_banner) {
  8733. /* note: ash and hush share this string */
  8734. out1fmt("\n\n%s %s\n"
  8735. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8736. "\n",
  8737. bb_banner,
  8738. "built-in shell (ash)"
  8739. );
  8740. did_banner = 1;
  8741. }
  8742. #endif
  8743. #if ENABLE_FEATURE_EDITING
  8744. if (!line_input_state) {
  8745. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8746. # if EDITING_HAS_get_exe_name
  8747. line_input_state->get_exe_name = get_builtin_name;
  8748. # endif
  8749. }
  8750. #endif
  8751. }
  8752. }
  8753. static void
  8754. optschanged(void)
  8755. {
  8756. #if DEBUG
  8757. opentrace();
  8758. #endif
  8759. setinteractive(iflag);
  8760. setjobctl(mflag);
  8761. #if ENABLE_FEATURE_EDITING_VI
  8762. if (line_input_state) {
  8763. if (viflag)
  8764. line_input_state->flags |= VI_MODE;
  8765. else
  8766. line_input_state->flags &= ~VI_MODE;
  8767. }
  8768. #else
  8769. viflag = 0; /* forcibly keep the option off */
  8770. #endif
  8771. }
  8772. struct localvar_list {
  8773. struct localvar_list *next;
  8774. struct localvar *lv;
  8775. };
  8776. static struct localvar_list *localvar_stack;
  8777. /*
  8778. * Called after a function returns.
  8779. * Interrupts must be off.
  8780. */
  8781. static void
  8782. poplocalvars(int keep)
  8783. {
  8784. struct localvar_list *ll;
  8785. struct localvar *lvp, *next;
  8786. struct var *vp;
  8787. INT_OFF;
  8788. ll = localvar_stack;
  8789. localvar_stack = ll->next;
  8790. next = ll->lv;
  8791. free(ll);
  8792. while ((lvp = next) != NULL) {
  8793. next = lvp->next;
  8794. vp = lvp->vp;
  8795. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8796. if (keep) {
  8797. int bits = VSTRFIXED;
  8798. if (lvp->flags != VUNSET) {
  8799. if (vp->var_text == lvp->text)
  8800. bits |= VTEXTFIXED;
  8801. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8802. free((char*)lvp->text);
  8803. }
  8804. vp->flags &= ~bits;
  8805. vp->flags |= (lvp->flags & bits);
  8806. if ((vp->flags &
  8807. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8808. unsetvar(vp->var_text);
  8809. } else if (vp == NULL) { /* $- saved */
  8810. memcpy(optlist, lvp->text, sizeof(optlist));
  8811. free((char*)lvp->text);
  8812. optschanged();
  8813. } else if (lvp->flags == VUNSET) {
  8814. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8815. unsetvar(vp->var_text);
  8816. } else {
  8817. if (vp->var_func)
  8818. vp->var_func(var_end(lvp->text));
  8819. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8820. free((char*)vp->var_text);
  8821. vp->flags = lvp->flags;
  8822. vp->var_text = lvp->text;
  8823. }
  8824. free(lvp);
  8825. }
  8826. INT_ON;
  8827. }
  8828. /*
  8829. * Create a new localvar environment.
  8830. */
  8831. static struct localvar_list *
  8832. pushlocalvars(int push)
  8833. {
  8834. struct localvar_list *ll;
  8835. struct localvar_list *top;
  8836. top = localvar_stack;
  8837. if (!push)
  8838. goto out;
  8839. INT_OFF;
  8840. ll = ckzalloc(sizeof(*ll));
  8841. /*ll->lv = NULL; - zalloc did it */
  8842. ll->next = top;
  8843. localvar_stack = ll;
  8844. INT_ON;
  8845. out:
  8846. return top;
  8847. }
  8848. static void
  8849. unwindlocalvars(struct localvar_list *stop)
  8850. {
  8851. while (localvar_stack != stop)
  8852. poplocalvars(0);
  8853. }
  8854. static int
  8855. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8856. {
  8857. volatile struct shparam saveparam;
  8858. struct jmploc *volatile savehandler;
  8859. struct jmploc jmploc;
  8860. int e;
  8861. int savefuncline;
  8862. saveparam = shellparam;
  8863. savefuncline = funcline;
  8864. savehandler = exception_handler;
  8865. e = setjmp(jmploc.loc);
  8866. if (e) {
  8867. goto funcdone;
  8868. }
  8869. INT_OFF;
  8870. exception_handler = &jmploc;
  8871. shellparam.malloced = 0;
  8872. func->count++;
  8873. funcline = func->n.ndefun.linno;
  8874. INT_ON;
  8875. shellparam.nparam = argc - 1;
  8876. shellparam.p = argv + 1;
  8877. #if ENABLE_ASH_GETOPTS
  8878. shellparam.optind = 1;
  8879. shellparam.optoff = -1;
  8880. #endif
  8881. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8882. funcdone:
  8883. INT_OFF;
  8884. funcline = savefuncline;
  8885. freefunc(func);
  8886. freeparam(&shellparam);
  8887. shellparam = saveparam;
  8888. exception_handler = savehandler;
  8889. INT_ON;
  8890. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  8891. return e;
  8892. }
  8893. /*
  8894. * Make a variable a local variable. When a variable is made local, it's
  8895. * value and flags are saved in a localvar structure. The saved values
  8896. * will be restored when the shell function returns. We handle the name
  8897. * "-" as a special case: it makes changes to "set +-options" local
  8898. * (options will be restored on return from the function).
  8899. */
  8900. static void
  8901. mklocal(char *name, int flags)
  8902. {
  8903. struct localvar *lvp;
  8904. struct var **vpp;
  8905. struct var *vp;
  8906. char *eq = strchr(name, '=');
  8907. INT_OFF;
  8908. /* Cater for duplicate "local". Examples:
  8909. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8910. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8911. */
  8912. lvp = localvar_stack->lv;
  8913. while (lvp) {
  8914. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8915. if (eq)
  8916. setvareq(name, 0);
  8917. /* else:
  8918. * it's a duplicate "local VAR" declaration, do nothing
  8919. */
  8920. goto ret;
  8921. }
  8922. lvp = lvp->next;
  8923. }
  8924. lvp = ckzalloc(sizeof(*lvp));
  8925. if (LONE_DASH(name)) {
  8926. char *p;
  8927. p = ckmalloc(sizeof(optlist));
  8928. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8929. vp = NULL;
  8930. } else {
  8931. vpp = hashvar(name);
  8932. vp = *findvar(vpp, name);
  8933. if (vp == NULL) {
  8934. /* variable did not exist yet */
  8935. if (eq)
  8936. vp = setvareq(name, VSTRFIXED | flags);
  8937. else
  8938. vp = setvar(name, NULL, VSTRFIXED | flags);
  8939. lvp->flags = VUNSET;
  8940. } else {
  8941. lvp->text = vp->var_text;
  8942. lvp->flags = vp->flags;
  8943. /* make sure neither "struct var" nor string gets freed
  8944. * during (un)setting:
  8945. */
  8946. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8947. if (eq)
  8948. setvareq(name, flags);
  8949. else
  8950. /* "local VAR" unsets VAR: */
  8951. setvar0(name, NULL);
  8952. }
  8953. }
  8954. lvp->vp = vp;
  8955. lvp->next = localvar_stack->lv;
  8956. localvar_stack->lv = lvp;
  8957. ret:
  8958. INT_ON;
  8959. }
  8960. /*
  8961. * The "local" command.
  8962. */
  8963. static int FAST_FUNC
  8964. localcmd(int argc UNUSED_PARAM, char **argv)
  8965. {
  8966. char *name;
  8967. if (!localvar_stack)
  8968. ash_msg_and_raise_error("not in a function");
  8969. argv = argptr;
  8970. while ((name = *argv++) != NULL) {
  8971. mklocal(name, 0);
  8972. }
  8973. return 0;
  8974. }
  8975. static int FAST_FUNC
  8976. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8977. {
  8978. return 1;
  8979. }
  8980. static int FAST_FUNC
  8981. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8982. {
  8983. return 0;
  8984. }
  8985. static int FAST_FUNC
  8986. execcmd(int argc UNUSED_PARAM, char **argv)
  8987. {
  8988. optionarg = NULL;
  8989. while (nextopt("a:") != '\0')
  8990. /* nextopt() sets optionarg to "-a ARGV0" */;
  8991. argv = argptr;
  8992. if (argv[0]) {
  8993. char *prog;
  8994. iflag = 0; /* exit on error */
  8995. mflag = 0;
  8996. optschanged();
  8997. /* We should set up signals for "exec CMD"
  8998. * the same way as for "CMD" without "exec".
  8999. * But optschanged->setinteractive->setsignal
  9000. * still thought we are a root shell. Therefore, for example,
  9001. * SIGQUIT is still set to IGN. Fix it:
  9002. */
  9003. shlvl++;
  9004. setsignal(SIGQUIT);
  9005. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9006. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9007. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9008. prog = argv[0];
  9009. if (optionarg)
  9010. argv[0] = optionarg;
  9011. shellexec(prog, argv, pathval(), 0);
  9012. /* NOTREACHED */
  9013. }
  9014. return 0;
  9015. }
  9016. /*
  9017. * The return command.
  9018. */
  9019. static int FAST_FUNC
  9020. returncmd(int argc UNUSED_PARAM, char **argv)
  9021. {
  9022. int skip;
  9023. int status;
  9024. /*
  9025. * If called outside a function, do what ksh does;
  9026. * skip the rest of the file.
  9027. */
  9028. if (argv[1]) {
  9029. skip = SKIPFUNC;
  9030. status = number(argv[1]);
  9031. } else {
  9032. skip = SKIPFUNCDEF;
  9033. status = exitstatus;
  9034. }
  9035. evalskip = skip;
  9036. return status;
  9037. }
  9038. /* Forward declarations for builtintab[] */
  9039. static int breakcmd(int, char **) FAST_FUNC;
  9040. static int dotcmd(int, char **) FAST_FUNC;
  9041. static int evalcmd(int, char **, int) FAST_FUNC;
  9042. static int exitcmd(int, char **) FAST_FUNC;
  9043. static int exportcmd(int, char **) FAST_FUNC;
  9044. #if ENABLE_ASH_GETOPTS
  9045. static int getoptscmd(int, char **) FAST_FUNC;
  9046. #endif
  9047. #if ENABLE_ASH_HELP
  9048. static int helpcmd(int, char **) FAST_FUNC;
  9049. #endif
  9050. #if MAX_HISTORY
  9051. static int historycmd(int, char **) FAST_FUNC;
  9052. #endif
  9053. #if ENABLE_FEATURE_SH_MATH
  9054. static int letcmd(int, char **) FAST_FUNC;
  9055. #endif
  9056. static int readcmd(int, char **) FAST_FUNC;
  9057. static int setcmd(int, char **) FAST_FUNC;
  9058. static int shiftcmd(int, char **) FAST_FUNC;
  9059. static int timescmd(int, char **) FAST_FUNC;
  9060. static int trapcmd(int, char **) FAST_FUNC;
  9061. static int umaskcmd(int, char **) FAST_FUNC;
  9062. static int unsetcmd(int, char **) FAST_FUNC;
  9063. static int ulimitcmd(int, char **) FAST_FUNC;
  9064. #define BUILTIN_NOSPEC "0"
  9065. #define BUILTIN_SPECIAL "1"
  9066. #define BUILTIN_REGULAR "2"
  9067. #define BUILTIN_SPEC_REG "3"
  9068. #define BUILTIN_ASSIGN "4"
  9069. #define BUILTIN_SPEC_ASSG "5"
  9070. #define BUILTIN_REG_ASSG "6"
  9071. #define BUILTIN_SPEC_REG_ASSG "7"
  9072. /* Stubs for calling non-FAST_FUNC's */
  9073. #if ENABLE_ASH_ECHO
  9074. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9075. #endif
  9076. #if ENABLE_ASH_PRINTF
  9077. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9078. #endif
  9079. #if ENABLE_ASH_TEST || BASH_TEST2
  9080. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9081. #endif
  9082. /* Keep these in proper order since it is searched via bsearch() */
  9083. static const struct builtincmd builtintab[] = {
  9084. { BUILTIN_SPEC_REG "." , dotcmd },
  9085. { BUILTIN_SPEC_REG ":" , truecmd },
  9086. #if ENABLE_ASH_TEST
  9087. { BUILTIN_REGULAR "[" , testcmd },
  9088. #endif
  9089. #if BASH_TEST2
  9090. { BUILTIN_REGULAR "[[" , testcmd },
  9091. #endif
  9092. #if ENABLE_ASH_ALIAS
  9093. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9094. #endif
  9095. #if JOBS
  9096. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9097. #endif
  9098. { BUILTIN_SPEC_REG "break" , breakcmd },
  9099. { BUILTIN_REGULAR "cd" , cdcmd },
  9100. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9101. #if ENABLE_ASH_CMDCMD
  9102. { BUILTIN_REGULAR "command" , commandcmd },
  9103. #endif
  9104. { BUILTIN_SPEC_REG "continue", breakcmd },
  9105. #if ENABLE_ASH_ECHO
  9106. { BUILTIN_REGULAR "echo" , echocmd },
  9107. #endif
  9108. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9109. { BUILTIN_SPEC_REG "exec" , execcmd },
  9110. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9111. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9112. { BUILTIN_REGULAR "false" , falsecmd },
  9113. #if JOBS
  9114. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9115. #endif
  9116. #if ENABLE_ASH_GETOPTS
  9117. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9118. #endif
  9119. { BUILTIN_REGULAR "hash" , hashcmd },
  9120. #if ENABLE_ASH_HELP
  9121. { BUILTIN_NOSPEC "help" , helpcmd },
  9122. #endif
  9123. #if MAX_HISTORY
  9124. { BUILTIN_NOSPEC "history" , historycmd },
  9125. #endif
  9126. #if JOBS
  9127. { BUILTIN_REGULAR "jobs" , jobscmd },
  9128. { BUILTIN_REGULAR "kill" , killcmd },
  9129. #endif
  9130. #if ENABLE_FEATURE_SH_MATH
  9131. { BUILTIN_NOSPEC "let" , letcmd },
  9132. #endif
  9133. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9134. #if ENABLE_ASH_PRINTF
  9135. { BUILTIN_REGULAR "printf" , printfcmd },
  9136. #endif
  9137. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9138. { BUILTIN_REGULAR "read" , readcmd },
  9139. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9140. { BUILTIN_SPEC_REG "return" , returncmd },
  9141. { BUILTIN_SPEC_REG "set" , setcmd },
  9142. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9143. #if BASH_SOURCE
  9144. { BUILTIN_SPEC_REG "source" , dotcmd },
  9145. #endif
  9146. #if ENABLE_ASH_TEST
  9147. { BUILTIN_REGULAR "test" , testcmd },
  9148. #endif
  9149. { BUILTIN_SPEC_REG "times" , timescmd },
  9150. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9151. { BUILTIN_REGULAR "true" , truecmd },
  9152. { BUILTIN_REGULAR "type" , typecmd },
  9153. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9154. { BUILTIN_REGULAR "umask" , umaskcmd },
  9155. #if ENABLE_ASH_ALIAS
  9156. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9157. #endif
  9158. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9159. { BUILTIN_REGULAR "wait" , waitcmd },
  9160. };
  9161. /* Should match the above table! */
  9162. #define COMMANDCMD (builtintab + \
  9163. /* . : */ 2 + \
  9164. /* [ */ 1 * ENABLE_ASH_TEST + \
  9165. /* [[ */ 1 * BASH_TEST2 + \
  9166. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9167. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9168. /* break cd cddir */ 3)
  9169. #define EVALCMD (COMMANDCMD + \
  9170. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9171. /* continue */ 1 + \
  9172. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9173. 0)
  9174. #define EXECCMD (EVALCMD + \
  9175. /* eval */ 1)
  9176. /*
  9177. * Search the table of builtin commands.
  9178. */
  9179. static int
  9180. pstrcmp1(const void *a, const void *b)
  9181. {
  9182. return strcmp((char*)a, *(char**)b + 1);
  9183. }
  9184. static struct builtincmd *
  9185. find_builtin(const char *name)
  9186. {
  9187. struct builtincmd *bp;
  9188. bp = bsearch(
  9189. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9190. pstrcmp1
  9191. );
  9192. return bp;
  9193. }
  9194. #if EDITING_HAS_get_exe_name
  9195. static const char * FAST_FUNC
  9196. get_builtin_name(int i)
  9197. {
  9198. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9199. }
  9200. #endif
  9201. /*
  9202. * Execute a simple command.
  9203. */
  9204. static void unwindfiles(struct parsefile *stop);
  9205. static int
  9206. isassignment(const char *p)
  9207. {
  9208. const char *q = endofname(p);
  9209. if (p == q)
  9210. return 0;
  9211. return *q == '=';
  9212. }
  9213. static int FAST_FUNC
  9214. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9215. {
  9216. /* Preserve exitstatus of a previous possible redirection
  9217. * as POSIX mandates */
  9218. return back_exitstatus;
  9219. }
  9220. static int
  9221. evalcommand(union node *cmd, int flags)
  9222. {
  9223. static const struct builtincmd null_bltin = {
  9224. BUILTIN_REGULAR "", bltincmd
  9225. };
  9226. struct localvar_list *localvar_stop;
  9227. struct parsefile *file_stop;
  9228. struct redirtab *redir_stop;
  9229. union node *argp;
  9230. struct arglist arglist;
  9231. struct arglist varlist;
  9232. char **argv;
  9233. int argc;
  9234. struct strlist *osp;
  9235. const struct strlist *sp;
  9236. struct cmdentry cmdentry;
  9237. struct job *jp;
  9238. char *lastarg;
  9239. const char *path;
  9240. int spclbltin;
  9241. int cmd_flag;
  9242. int status;
  9243. char **nargv;
  9244. smallint cmd_is_exec;
  9245. int vflags;
  9246. int vlocal;
  9247. errlinno = lineno = cmd->ncmd.linno;
  9248. if (funcline)
  9249. lineno -= funcline - 1;
  9250. /* First expand the arguments. */
  9251. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9252. file_stop = g_parsefile;
  9253. back_exitstatus = 0;
  9254. cmdentry.cmdtype = CMDBUILTIN;
  9255. cmdentry.u.cmd = &null_bltin;
  9256. varlist.lastp = &varlist.list;
  9257. *varlist.lastp = NULL;
  9258. arglist.lastp = &arglist.list;
  9259. *arglist.lastp = NULL;
  9260. cmd_flag = 0;
  9261. cmd_is_exec = 0;
  9262. spclbltin = -1;
  9263. vflags = 0;
  9264. vlocal = 0;
  9265. path = NULL;
  9266. argc = 0;
  9267. argp = cmd->ncmd.args;
  9268. osp = fill_arglist(&arglist, &argp);
  9269. if (osp) {
  9270. int pseudovarflag = 0;
  9271. for (;;) {
  9272. find_command(arglist.list->text, &cmdentry,
  9273. cmd_flag | DO_REGBLTIN, pathval());
  9274. vlocal++;
  9275. /* implement bltin and command here */
  9276. if (cmdentry.cmdtype != CMDBUILTIN)
  9277. break;
  9278. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9279. if (spclbltin < 0) {
  9280. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9281. vlocal = !spclbltin;
  9282. }
  9283. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9284. #if ENABLE_ASH_CMDCMD
  9285. if (cmdentry.u.cmd != COMMANDCMD)
  9286. break;
  9287. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9288. if (!cmd_flag)
  9289. #endif
  9290. break;
  9291. }
  9292. for (; argp; argp = argp->narg.next)
  9293. expandarg(argp, &arglist,
  9294. pseudovarflag &&
  9295. isassignment(argp->narg.text) ?
  9296. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9297. for (sp = arglist.list; sp; sp = sp->next)
  9298. argc++;
  9299. if (cmd_is_exec && argc > 1)
  9300. vflags = VEXPORT;
  9301. }
  9302. localvar_stop = pushlocalvars(vlocal);
  9303. /* Reserve one extra spot at the front for shellexec. */
  9304. nargv = stalloc(sizeof(char *) * (argc + 2));
  9305. argv = ++nargv;
  9306. for (sp = arglist.list; sp; sp = sp->next) {
  9307. TRACE(("evalcommand arg: %s\n", sp->text));
  9308. *nargv++ = sp->text;
  9309. }
  9310. *nargv = NULL;
  9311. lastarg = NULL;
  9312. if (iflag && funcline == 0 && argc > 0)
  9313. lastarg = nargv[-1];
  9314. expredir(cmd->ncmd.redirect);
  9315. redir_stop = pushredir(cmd->ncmd.redirect);
  9316. preverrout_fd = 2;
  9317. if (BASH_XTRACEFD && xflag) {
  9318. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9319. * we do not emulate this. We only use its value.
  9320. */
  9321. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9322. if (xtracefd && is_number(xtracefd))
  9323. preverrout_fd = atoi(xtracefd);
  9324. }
  9325. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9326. if (status) {
  9327. bail:
  9328. exitstatus = status;
  9329. /* We have a redirection error. */
  9330. if (spclbltin > 0)
  9331. raise_exception(EXERROR);
  9332. goto out;
  9333. }
  9334. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9335. struct strlist **spp;
  9336. spp = varlist.lastp;
  9337. expandarg(argp, &varlist, EXP_VARTILDE);
  9338. if (vlocal)
  9339. mklocal((*spp)->text, VEXPORT);
  9340. else
  9341. setvareq((*spp)->text, vflags);
  9342. }
  9343. /* Print the command if xflag is set. */
  9344. if (xflag) {
  9345. const char *pfx = "";
  9346. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9347. sp = varlist.list;
  9348. while (sp) {
  9349. char *varval = sp->text;
  9350. char *eq = strchrnul(varval, '=');
  9351. if (*eq)
  9352. eq++;
  9353. fdprintf(preverrout_fd, "%s%.*s%s",
  9354. pfx,
  9355. (int)(eq - varval), varval,
  9356. maybe_single_quote(eq)
  9357. );
  9358. sp = sp->next;
  9359. pfx = " ";
  9360. }
  9361. sp = arglist.list;
  9362. while (sp) {
  9363. fdprintf(preverrout_fd, "%s%s",
  9364. pfx,
  9365. /* always quote if matches reserved word: */
  9366. findkwd(sp->text)
  9367. ? single_quote(sp->text)
  9368. : maybe_single_quote(sp->text)
  9369. );
  9370. sp = sp->next;
  9371. pfx = " ";
  9372. }
  9373. safe_write(preverrout_fd, "\n", 1);
  9374. }
  9375. /* Now locate the command. */
  9376. if (cmdentry.cmdtype != CMDBUILTIN
  9377. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9378. ) {
  9379. path = path ? path : pathval();
  9380. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9381. }
  9382. jp = NULL;
  9383. /* Execute the command. */
  9384. switch (cmdentry.cmdtype) {
  9385. case CMDUNKNOWN:
  9386. status = 127;
  9387. flush_stdout_stderr();
  9388. goto bail;
  9389. default: {
  9390. #if ENABLE_FEATURE_SH_STANDALONE \
  9391. && ENABLE_FEATURE_SH_NOFORK \
  9392. && NUM_APPLETS > 1
  9393. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9394. * around run_nofork_applet() call.
  9395. * (2) Should this check also be done in forkshell()?
  9396. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9397. */
  9398. /* find_command() encodes applet_no as (-2 - applet_no) */
  9399. int applet_no = (- cmdentry.u.index - 2);
  9400. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9401. char **sv_environ;
  9402. INT_OFF;
  9403. sv_environ = environ;
  9404. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9405. /*
  9406. * Run <applet>_main().
  9407. * Signals (^C) can't interrupt here.
  9408. * Otherwise we can mangle stdio or malloc internal state.
  9409. * This makes applets which can run for a long time
  9410. * and/or wait for user input ineligible for NOFORK:
  9411. * for example, "yes" or "rm" (rm -i waits for input).
  9412. */
  9413. exitstatus = run_nofork_applet(applet_no, argv);
  9414. environ = sv_environ;
  9415. /*
  9416. * Try enabling NOFORK for "yes" applet.
  9417. * ^C _will_ stop it (write returns EINTR),
  9418. * but this causes stdout FILE to be stuck
  9419. * and needing clearerr(). What if other applets
  9420. * also can get EINTRs? Do we need to switch
  9421. * our signals to SA_RESTART?
  9422. */
  9423. /*clearerr(stdout);*/
  9424. INT_ON;
  9425. break;
  9426. }
  9427. #endif
  9428. /* Can we avoid forking? For example, very last command
  9429. * in a script or a subshell does not need forking,
  9430. * we can just exec it.
  9431. */
  9432. if (!(flags & EV_EXIT) || may_have_traps) {
  9433. /* No, forking off a child is necessary */
  9434. INT_OFF;
  9435. get_tty_state();
  9436. jp = makejob(/*cmd,*/ 1);
  9437. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9438. /* parent */
  9439. break;
  9440. }
  9441. /* child */
  9442. FORCE_INT_ON;
  9443. /* fall through to exec'ing external program */
  9444. }
  9445. shellexec(argv[0], argv, path, cmdentry.u.index);
  9446. /* NOTREACHED */
  9447. } /* default */
  9448. case CMDBUILTIN:
  9449. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9450. && !(exception_type == EXERROR && spclbltin <= 0)
  9451. ) {
  9452. raise:
  9453. longjmp(exception_handler->loc, 1);
  9454. }
  9455. break;
  9456. case CMDFUNCTION:
  9457. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9458. goto raise;
  9459. break;
  9460. } /* switch */
  9461. status = waitforjob(jp);
  9462. if (jp)
  9463. TRACE(("forked child exited with %d\n", status));
  9464. FORCE_INT_ON;
  9465. out:
  9466. if (cmd->ncmd.redirect)
  9467. popredir(/*drop:*/ cmd_is_exec);
  9468. unwindredir(redir_stop);
  9469. unwindfiles(file_stop);
  9470. unwindlocalvars(localvar_stop);
  9471. if (lastarg) {
  9472. /* dsl: I think this is intended to be used to support
  9473. * '_' in 'vi' command mode during line editing...
  9474. * However I implemented that within libedit itself.
  9475. */
  9476. setvar0("_", lastarg);
  9477. }
  9478. return status;
  9479. }
  9480. static int
  9481. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9482. {
  9483. char *volatile savecmdname;
  9484. struct jmploc *volatile savehandler;
  9485. struct jmploc jmploc;
  9486. int status;
  9487. int i;
  9488. savecmdname = commandname;
  9489. savehandler = exception_handler;
  9490. i = setjmp(jmploc.loc);
  9491. if (i)
  9492. goto cmddone;
  9493. exception_handler = &jmploc;
  9494. commandname = argv[0];
  9495. argptr = argv + 1;
  9496. optptr = NULL; /* initialize nextopt */
  9497. if (cmd == EVALCMD)
  9498. status = evalcmd(argc, argv, flags);
  9499. else
  9500. status = (*cmd->builtin)(argc, argv);
  9501. flush_stdout_stderr();
  9502. status |= ferror(stdout);
  9503. exitstatus = status;
  9504. cmddone:
  9505. clearerr(stdout);
  9506. commandname = savecmdname;
  9507. exception_handler = savehandler;
  9508. return i;
  9509. }
  9510. static int
  9511. goodname(const char *p)
  9512. {
  9513. return endofname(p)[0] == '\0';
  9514. }
  9515. /*
  9516. * Search for a command. This is called before we fork so that the
  9517. * location of the command will be available in the parent as well as
  9518. * the child. The check for "goodname" is an overly conservative
  9519. * check that the name will not be subject to expansion.
  9520. */
  9521. static void
  9522. prehash(union node *n)
  9523. {
  9524. struct cmdentry entry;
  9525. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9526. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9527. }
  9528. /* ============ Builtin commands
  9529. *
  9530. * Builtin commands whose functions are closely tied to evaluation
  9531. * are implemented here.
  9532. */
  9533. /*
  9534. * Handle break and continue commands. Break, continue, and return are
  9535. * all handled by setting the evalskip flag. The evaluation routines
  9536. * above all check this flag, and if it is set they start skipping
  9537. * commands rather than executing them. The variable skipcount is
  9538. * the number of loops to break/continue, or the number of function
  9539. * levels to return. (The latter is always 1.) It should probably
  9540. * be an error to break out of more loops than exist, but it isn't
  9541. * in the standard shell so we don't make it one here.
  9542. */
  9543. static int FAST_FUNC
  9544. breakcmd(int argc UNUSED_PARAM, char **argv)
  9545. {
  9546. int n = argv[1] ? number(argv[1]) : 1;
  9547. if (n <= 0)
  9548. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9549. if (n > loopnest)
  9550. n = loopnest;
  9551. if (n > 0) {
  9552. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9553. skipcount = n;
  9554. }
  9555. return 0;
  9556. }
  9557. /*
  9558. * This implements the input routines used by the parser.
  9559. */
  9560. enum {
  9561. INPUT_PUSH_FILE = 1,
  9562. INPUT_NOFILE_OK = 2,
  9563. };
  9564. static smallint checkkwd;
  9565. /* values of checkkwd variable */
  9566. #define CHKALIAS 0x1
  9567. #define CHKKWD 0x2
  9568. #define CHKNL 0x4
  9569. #define CHKEOFMARK 0x8
  9570. /*
  9571. * Push a string back onto the input at this current parsefile level.
  9572. * We handle aliases this way.
  9573. */
  9574. #if !ENABLE_ASH_ALIAS
  9575. #define pushstring(s, ap) pushstring(s)
  9576. #endif
  9577. static void
  9578. pushstring(char *s, struct alias *ap)
  9579. {
  9580. struct strpush *sp;
  9581. int len;
  9582. len = strlen(s);
  9583. INT_OFF;
  9584. if (g_parsefile->strpush) {
  9585. sp = ckzalloc(sizeof(*sp));
  9586. sp->prev = g_parsefile->strpush;
  9587. } else {
  9588. sp = &(g_parsefile->basestrpush);
  9589. }
  9590. g_parsefile->strpush = sp;
  9591. sp->prev_string = g_parsefile->next_to_pgetc;
  9592. sp->prev_left_in_line = g_parsefile->left_in_line;
  9593. sp->unget = g_parsefile->unget;
  9594. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9595. #if ENABLE_ASH_ALIAS
  9596. sp->ap = ap;
  9597. if (ap) {
  9598. ap->flag |= ALIASINUSE;
  9599. sp->string = s;
  9600. }
  9601. #endif
  9602. g_parsefile->next_to_pgetc = s;
  9603. g_parsefile->left_in_line = len;
  9604. g_parsefile->unget = 0;
  9605. INT_ON;
  9606. }
  9607. static void
  9608. popstring(void)
  9609. {
  9610. struct strpush *sp = g_parsefile->strpush;
  9611. INT_OFF;
  9612. #if ENABLE_ASH_ALIAS
  9613. if (sp->ap) {
  9614. if (g_parsefile->next_to_pgetc[-1] == ' '
  9615. || g_parsefile->next_to_pgetc[-1] == '\t'
  9616. ) {
  9617. checkkwd |= CHKALIAS;
  9618. }
  9619. if (sp->string != sp->ap->val) {
  9620. free(sp->string);
  9621. }
  9622. sp->ap->flag &= ~ALIASINUSE;
  9623. if (sp->ap->flag & ALIASDEAD) {
  9624. unalias(sp->ap->name);
  9625. }
  9626. }
  9627. #endif
  9628. g_parsefile->next_to_pgetc = sp->prev_string;
  9629. g_parsefile->left_in_line = sp->prev_left_in_line;
  9630. g_parsefile->unget = sp->unget;
  9631. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9632. g_parsefile->strpush = sp->prev;
  9633. if (sp != &(g_parsefile->basestrpush))
  9634. free(sp);
  9635. INT_ON;
  9636. }
  9637. static int
  9638. preadfd(void)
  9639. {
  9640. int nr;
  9641. char *buf = g_parsefile->buf;
  9642. g_parsefile->next_to_pgetc = buf;
  9643. #if ENABLE_FEATURE_EDITING
  9644. /* retry: */
  9645. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9646. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9647. else {
  9648. # if ENABLE_ASH_IDLE_TIMEOUT
  9649. int timeout = -1;
  9650. const char *tmout_var = lookupvar("TMOUT");
  9651. if (tmout_var) {
  9652. timeout = atoi(tmout_var) * 1000;
  9653. if (timeout <= 0)
  9654. timeout = -1;
  9655. }
  9656. line_input_state->timeout = timeout;
  9657. # endif
  9658. # if ENABLE_FEATURE_TAB_COMPLETION
  9659. line_input_state->path_lookup = pathval();
  9660. # endif
  9661. reinit_unicode_for_ash();
  9662. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9663. if (nr == 0) {
  9664. /* ^C pressed, "convert" to SIGINT */
  9665. write(STDOUT_FILENO, "^C", 2);
  9666. raise(SIGINT);
  9667. if (trap[SIGINT]) {
  9668. buf[0] = '\n';
  9669. buf[1] = '\0';
  9670. return 1;
  9671. }
  9672. exitstatus = 128 + SIGINT;
  9673. return -1;
  9674. }
  9675. if (nr < 0) {
  9676. if (errno == 0) {
  9677. /* Ctrl+D pressed */
  9678. nr = 0;
  9679. }
  9680. # if ENABLE_ASH_IDLE_TIMEOUT
  9681. else if (errno == EAGAIN && timeout > 0) {
  9682. puts("\007timed out waiting for input: auto-logout");
  9683. exitshell();
  9684. }
  9685. # endif
  9686. }
  9687. }
  9688. #else
  9689. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9690. #endif
  9691. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9692. if (nr < 0) {
  9693. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9694. int flags = fcntl(0, F_GETFL);
  9695. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9696. flags &= ~O_NONBLOCK;
  9697. if (fcntl(0, F_SETFL, flags) >= 0) {
  9698. out2str("sh: turning off NDELAY mode\n");
  9699. goto retry;
  9700. }
  9701. }
  9702. }
  9703. }
  9704. #endif
  9705. return nr;
  9706. }
  9707. /*
  9708. * Refill the input buffer and return the next input character:
  9709. *
  9710. * 1) If a string was pushed back on the input, pop it;
  9711. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9712. * or we are reading from a string so we can't refill the buffer,
  9713. * return EOF.
  9714. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9715. * 4) Process input up to the next newline, deleting nul characters.
  9716. */
  9717. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9718. #define pgetc_debug(...) ((void)0)
  9719. static int pgetc(void);
  9720. static int
  9721. preadbuffer(void)
  9722. {
  9723. char *q;
  9724. int more;
  9725. if (g_parsefile->strpush) {
  9726. #if ENABLE_ASH_ALIAS
  9727. if (g_parsefile->left_in_line == -1
  9728. && g_parsefile->strpush->ap
  9729. && g_parsefile->next_to_pgetc[-1] != ' '
  9730. && g_parsefile->next_to_pgetc[-1] != '\t'
  9731. ) {
  9732. pgetc_debug("preadbuffer PEOA");
  9733. return PEOA;
  9734. }
  9735. #endif
  9736. popstring();
  9737. return pgetc();
  9738. }
  9739. /* on both branches above g_parsefile->left_in_line < 0.
  9740. * "pgetc" needs refilling.
  9741. */
  9742. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9743. * pungetc() may increment it a few times.
  9744. * Assuming it won't increment it to less than -90.
  9745. */
  9746. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9747. pgetc_debug("preadbuffer PEOF1");
  9748. /* even in failure keep left_in_line and next_to_pgetc
  9749. * in lock step, for correct multi-layer pungetc.
  9750. * left_in_line was decremented before preadbuffer(),
  9751. * must inc next_to_pgetc: */
  9752. g_parsefile->next_to_pgetc++;
  9753. return PEOF;
  9754. }
  9755. more = g_parsefile->left_in_buffer;
  9756. if (more <= 0) {
  9757. flush_stdout_stderr();
  9758. again:
  9759. more = preadfd();
  9760. if (more <= 0) {
  9761. /* don't try reading again */
  9762. g_parsefile->left_in_line = -99;
  9763. pgetc_debug("preadbuffer PEOF2");
  9764. g_parsefile->next_to_pgetc++;
  9765. return PEOF;
  9766. }
  9767. }
  9768. /* Find out where's the end of line.
  9769. * Set g_parsefile->left_in_line
  9770. * and g_parsefile->left_in_buffer acordingly.
  9771. * NUL chars are deleted.
  9772. */
  9773. q = g_parsefile->next_to_pgetc;
  9774. for (;;) {
  9775. char c;
  9776. more--;
  9777. c = *q;
  9778. if (c == '\0') {
  9779. memmove(q, q + 1, more);
  9780. } else {
  9781. q++;
  9782. if (c == '\n') {
  9783. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9784. break;
  9785. }
  9786. }
  9787. if (more <= 0) {
  9788. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9789. if (g_parsefile->left_in_line < 0)
  9790. goto again;
  9791. break;
  9792. }
  9793. }
  9794. g_parsefile->left_in_buffer = more;
  9795. if (vflag) {
  9796. char save = *q;
  9797. *q = '\0';
  9798. out2str(g_parsefile->next_to_pgetc);
  9799. *q = save;
  9800. }
  9801. pgetc_debug("preadbuffer at %d:%p'%s'",
  9802. g_parsefile->left_in_line,
  9803. g_parsefile->next_to_pgetc,
  9804. g_parsefile->next_to_pgetc);
  9805. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9806. }
  9807. static void
  9808. nlprompt(void)
  9809. {
  9810. g_parsefile->linno++;
  9811. setprompt_if(doprompt, 2);
  9812. }
  9813. static void
  9814. nlnoprompt(void)
  9815. {
  9816. g_parsefile->linno++;
  9817. needprompt = doprompt;
  9818. }
  9819. static int
  9820. pgetc(void)
  9821. {
  9822. int c;
  9823. pgetc_debug("pgetc at %d:%p'%s'",
  9824. g_parsefile->left_in_line,
  9825. g_parsefile->next_to_pgetc,
  9826. g_parsefile->next_to_pgetc);
  9827. if (g_parsefile->unget)
  9828. return g_parsefile->lastc[--g_parsefile->unget];
  9829. if (--g_parsefile->left_in_line >= 0)
  9830. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9831. else
  9832. c = preadbuffer();
  9833. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9834. g_parsefile->lastc[0] = c;
  9835. return c;
  9836. }
  9837. #if ENABLE_ASH_ALIAS
  9838. static int
  9839. pgetc_without_PEOA(void)
  9840. {
  9841. int c;
  9842. do {
  9843. pgetc_debug("pgetc at %d:%p'%s'",
  9844. g_parsefile->left_in_line,
  9845. g_parsefile->next_to_pgetc,
  9846. g_parsefile->next_to_pgetc);
  9847. c = pgetc();
  9848. } while (c == PEOA);
  9849. return c;
  9850. }
  9851. #else
  9852. # define pgetc_without_PEOA() pgetc()
  9853. #endif
  9854. /*
  9855. * Undo a call to pgetc. Only two characters may be pushed back.
  9856. * PEOF may be pushed back.
  9857. */
  9858. static void
  9859. pungetc(void)
  9860. {
  9861. g_parsefile->unget++;
  9862. }
  9863. /* This one eats backslash+newline */
  9864. static int
  9865. pgetc_eatbnl(void)
  9866. {
  9867. int c;
  9868. while ((c = pgetc()) == '\\') {
  9869. if (pgetc() != '\n') {
  9870. pungetc();
  9871. break;
  9872. }
  9873. nlprompt();
  9874. }
  9875. return c;
  9876. }
  9877. struct synstack {
  9878. smalluint syntax;
  9879. uint8_t innerdq :1;
  9880. uint8_t varpushed :1;
  9881. uint8_t dblquote :1;
  9882. int varnest; /* levels of variables expansion */
  9883. int dqvarnest; /* levels of variables expansion within double quotes */
  9884. int parenlevel; /* levels of parens in arithmetic */
  9885. struct synstack *prev;
  9886. struct synstack *next;
  9887. };
  9888. static int
  9889. pgetc_top(struct synstack *stack)
  9890. {
  9891. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  9892. }
  9893. static void
  9894. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9895. {
  9896. memset(next, 0, sizeof(*next));
  9897. next->syntax = syntax;
  9898. next->next = *stack;
  9899. (*stack)->prev = next;
  9900. *stack = next;
  9901. }
  9902. static ALWAYS_INLINE void
  9903. synstack_pop(struct synstack **stack)
  9904. {
  9905. *stack = (*stack)->next;
  9906. }
  9907. /*
  9908. * To handle the "." command, a stack of input files is used. Pushfile
  9909. * adds a new entry to the stack and popfile restores the previous level.
  9910. */
  9911. static void
  9912. pushfile(void)
  9913. {
  9914. struct parsefile *pf;
  9915. pf = ckzalloc(sizeof(*pf));
  9916. pf->prev = g_parsefile;
  9917. pf->pf_fd = -1;
  9918. /*pf->strpush = NULL; - ckzalloc did it */
  9919. /*pf->basestrpush.prev = NULL;*/
  9920. /*pf->unget = 0;*/
  9921. g_parsefile = pf;
  9922. }
  9923. static void
  9924. popfile(void)
  9925. {
  9926. struct parsefile *pf = g_parsefile;
  9927. if (pf == &basepf)
  9928. return;
  9929. INT_OFF;
  9930. if (pf->pf_fd >= 0)
  9931. close(pf->pf_fd);
  9932. free(pf->buf);
  9933. while (pf->strpush)
  9934. popstring();
  9935. g_parsefile = pf->prev;
  9936. free(pf);
  9937. INT_ON;
  9938. }
  9939. static void
  9940. unwindfiles(struct parsefile *stop)
  9941. {
  9942. while (g_parsefile != stop)
  9943. popfile();
  9944. }
  9945. /*
  9946. * Return to top level.
  9947. */
  9948. static void
  9949. popallfiles(void)
  9950. {
  9951. unwindfiles(&basepf);
  9952. }
  9953. /*
  9954. * Close the file(s) that the shell is reading commands from. Called
  9955. * after a fork is done.
  9956. */
  9957. static void
  9958. closescript(void)
  9959. {
  9960. popallfiles();
  9961. if (g_parsefile->pf_fd > 0) {
  9962. close(g_parsefile->pf_fd);
  9963. g_parsefile->pf_fd = 0;
  9964. }
  9965. }
  9966. /*
  9967. * Like setinputfile, but takes an open file descriptor. Call this with
  9968. * interrupts off.
  9969. */
  9970. static void
  9971. setinputfd(int fd, int push)
  9972. {
  9973. if (push) {
  9974. pushfile();
  9975. g_parsefile->buf = NULL;
  9976. }
  9977. g_parsefile->pf_fd = fd;
  9978. if (g_parsefile->buf == NULL)
  9979. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9980. g_parsefile->left_in_buffer = 0;
  9981. g_parsefile->left_in_line = 0;
  9982. g_parsefile->linno = 1;
  9983. }
  9984. /*
  9985. * Set the input to take input from a file. If push is set, push the
  9986. * old input onto the stack first.
  9987. */
  9988. static int
  9989. setinputfile(const char *fname, int flags)
  9990. {
  9991. int fd;
  9992. INT_OFF;
  9993. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9994. if (fd < 0) {
  9995. if (flags & INPUT_NOFILE_OK)
  9996. goto out;
  9997. exitstatus = 127;
  9998. ash_msg_and_raise_perror("can't open '%s'", fname);
  9999. }
  10000. if (fd < 10)
  10001. fd = savefd(fd);
  10002. else if (O_CLOEXEC == 0) /* old libc */
  10003. close_on_exec_on(fd);
  10004. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10005. out:
  10006. INT_ON;
  10007. return fd;
  10008. }
  10009. /*
  10010. * Like setinputfile, but takes input from a string.
  10011. */
  10012. static void
  10013. setinputstring(char *string)
  10014. {
  10015. INT_OFF;
  10016. pushfile();
  10017. g_parsefile->next_to_pgetc = string;
  10018. g_parsefile->left_in_line = strlen(string);
  10019. g_parsefile->buf = NULL;
  10020. g_parsefile->linno = 1;
  10021. INT_ON;
  10022. }
  10023. /*
  10024. * Routines to check for mail.
  10025. */
  10026. #if ENABLE_ASH_MAIL
  10027. /* Hash of mtimes of mailboxes */
  10028. static unsigned mailtime_hash;
  10029. /* Set if MAIL or MAILPATH is changed. */
  10030. static smallint mail_var_path_changed;
  10031. /*
  10032. * Print appropriate message(s) if mail has arrived.
  10033. * If mail_var_path_changed is set,
  10034. * then the value of MAIL has mail_var_path_changed,
  10035. * so we just update the values.
  10036. */
  10037. static void
  10038. chkmail(void)
  10039. {
  10040. const char *mpath;
  10041. char *p;
  10042. char *q;
  10043. unsigned new_hash;
  10044. struct stackmark smark;
  10045. struct stat statb;
  10046. setstackmark(&smark);
  10047. mpath = mpathset() ? mpathval() : mailval();
  10048. new_hash = 0;
  10049. for (;;) {
  10050. int len;
  10051. len = padvance_magic(&mpath, nullstr, 2);
  10052. if (!len)
  10053. break;
  10054. p = stackblock();
  10055. break;
  10056. if (*p == '\0')
  10057. continue;
  10058. for (q = p; *q; q++)
  10059. continue;
  10060. #if DEBUG
  10061. if (q[-1] != '/')
  10062. abort();
  10063. #endif
  10064. q[-1] = '\0'; /* delete trailing '/' */
  10065. if (stat(p, &statb) < 0) {
  10066. continue;
  10067. }
  10068. /* Very simplistic "hash": just a sum of all mtimes */
  10069. new_hash += (unsigned)statb.st_mtime;
  10070. }
  10071. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10072. if (mailtime_hash != 0)
  10073. out2str("you have mail\n");
  10074. mailtime_hash = new_hash;
  10075. }
  10076. mail_var_path_changed = 0;
  10077. popstackmark(&smark);
  10078. }
  10079. static void FAST_FUNC
  10080. changemail(const char *val UNUSED_PARAM)
  10081. {
  10082. mail_var_path_changed = 1;
  10083. }
  10084. #endif /* ASH_MAIL */
  10085. /* ============ ??? */
  10086. /*
  10087. * Set the shell parameters.
  10088. */
  10089. static void
  10090. setparam(char **argv)
  10091. {
  10092. char **newparam;
  10093. char **ap;
  10094. int nparam;
  10095. for (nparam = 0; argv[nparam]; nparam++)
  10096. continue;
  10097. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10098. while (*argv) {
  10099. *ap++ = ckstrdup(*argv++);
  10100. }
  10101. *ap = NULL;
  10102. freeparam(&shellparam);
  10103. shellparam.malloced = 1;
  10104. shellparam.nparam = nparam;
  10105. shellparam.p = newparam;
  10106. #if ENABLE_ASH_GETOPTS
  10107. shellparam.optind = 1;
  10108. shellparam.optoff = -1;
  10109. #endif
  10110. }
  10111. /*
  10112. * Process shell options. The global variable argptr contains a pointer
  10113. * to the argument list; we advance it past the options.
  10114. *
  10115. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10116. * For a non-interactive shell, an error condition encountered
  10117. * by a special built-in ... shall cause the shell to write a diagnostic message
  10118. * to standard error and exit as shown in the following table:
  10119. * Error Special Built-In
  10120. * ...
  10121. * Utility syntax error (option or operand error) Shall exit
  10122. * ...
  10123. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10124. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10125. * and shell continues), and people rely on this behavior!
  10126. * Testcase:
  10127. * set -o barfoo 2>/dev/null
  10128. * echo $?
  10129. *
  10130. * Oh well. Let's mimic that.
  10131. */
  10132. static int
  10133. plus_minus_o(char *name, int val)
  10134. {
  10135. int i;
  10136. if (name) {
  10137. for (i = 0; i < NOPTS; i++) {
  10138. if (strcmp(name, optnames(i)) == 0) {
  10139. optlist[i] = val;
  10140. return 0;
  10141. }
  10142. }
  10143. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10144. return 1;
  10145. }
  10146. for (i = 0; i < NOPTS; i++) {
  10147. if (optnames(i)[0] == '\0')
  10148. continue;
  10149. if (val) {
  10150. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10151. } else {
  10152. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10153. }
  10154. }
  10155. return 0;
  10156. }
  10157. static void
  10158. setoption(int flag, int val)
  10159. {
  10160. int i;
  10161. for (i = 0; i < NOPTS; i++) {
  10162. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10163. optlist[i] = val;
  10164. return;
  10165. }
  10166. }
  10167. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10168. /* NOTREACHED */
  10169. }
  10170. /* If login_sh is not NULL, we are called to parse command line opts,
  10171. * not "set -opts"
  10172. */
  10173. static int
  10174. options(int *login_sh)
  10175. {
  10176. char *p;
  10177. int val;
  10178. int c;
  10179. if (login_sh)
  10180. minusc = NULL;
  10181. while ((p = *argptr) != NULL) {
  10182. c = *p++;
  10183. if (c != '-' && c != '+')
  10184. break;
  10185. argptr++;
  10186. val = 0; /* val = 0 if c == '+' */
  10187. if (c == '-') {
  10188. val = 1;
  10189. if (p[0] == '\0' || LONE_DASH(p)) {
  10190. if (!login_sh) {
  10191. /* "-" means turn off -x and -v */
  10192. if (p[0] == '\0')
  10193. xflag = vflag = 0;
  10194. /* "--" means reset params */
  10195. else if (*argptr == NULL)
  10196. setparam(argptr);
  10197. }
  10198. break; /* "-" or "--" terminates options */
  10199. }
  10200. }
  10201. /* first char was + or - */
  10202. while ((c = *p++) != '\0') {
  10203. if (login_sh) {
  10204. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10205. if (c == 'c') {
  10206. minusc = p; /* command is after shell args */
  10207. cflag = 1;
  10208. continue;
  10209. }
  10210. if (c == 's') { /* -s, +s */
  10211. sflag = 1;
  10212. continue;
  10213. }
  10214. if (c == 'i') { /* -i, +i */
  10215. iflag = 1;
  10216. continue;
  10217. }
  10218. if (c == 'l') {
  10219. *login_sh = 1; /* -l or +l == --login */
  10220. continue;
  10221. }
  10222. /* bash does not accept +-login, we also won't */
  10223. if (val && (c == '-')) { /* long options */
  10224. if (strcmp(p, "login") == 0) {
  10225. *login_sh = 1;
  10226. }
  10227. break;
  10228. }
  10229. }
  10230. if (c == 'o') {
  10231. if (plus_minus_o(*argptr, val)) {
  10232. /* it already printed err message */
  10233. return 1; /* error */
  10234. }
  10235. if (*argptr)
  10236. argptr++;
  10237. } else {
  10238. setoption(c, val);
  10239. }
  10240. }
  10241. }
  10242. return 0;
  10243. }
  10244. /*
  10245. * The shift builtin command.
  10246. */
  10247. static int FAST_FUNC
  10248. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10249. {
  10250. int n;
  10251. char **ap1, **ap2;
  10252. n = 1;
  10253. if (argv[1])
  10254. n = number(argv[1]);
  10255. if (n > shellparam.nparam)
  10256. return 1;
  10257. INT_OFF;
  10258. shellparam.nparam -= n;
  10259. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10260. if (shellparam.malloced)
  10261. free(*ap1);
  10262. }
  10263. ap2 = shellparam.p;
  10264. while ((*ap2++ = *ap1++) != NULL)
  10265. continue;
  10266. #if ENABLE_ASH_GETOPTS
  10267. shellparam.optind = 1;
  10268. shellparam.optoff = -1;
  10269. #endif
  10270. INT_ON;
  10271. return 0;
  10272. }
  10273. /*
  10274. * POSIX requires that 'set' (but not export or readonly) output the
  10275. * variables in lexicographic order - by the locale's collating order (sigh).
  10276. * Maybe we could keep them in an ordered balanced binary tree
  10277. * instead of hashed lists.
  10278. * For now just roll 'em through qsort for printing...
  10279. */
  10280. static int
  10281. showvars(const char *sep_prefix, int on, int off)
  10282. {
  10283. const char *sep;
  10284. char **ep, **epend;
  10285. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10286. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10287. sep = *sep_prefix ? " " : sep_prefix;
  10288. for (; ep < epend; ep++) {
  10289. const char *p;
  10290. const char *q;
  10291. p = endofname(*ep);
  10292. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10293. * makes "export -p" to have output not suitable for "eval":
  10294. * import os
  10295. * os.environ["test-test"]="test"
  10296. * if os.fork() == 0:
  10297. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10298. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10299. */
  10300. q = nullstr;
  10301. if (*p == '=')
  10302. q = single_quote(++p);
  10303. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10304. }
  10305. return 0;
  10306. }
  10307. /*
  10308. * The set command builtin.
  10309. */
  10310. static int FAST_FUNC
  10311. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10312. {
  10313. int retval;
  10314. if (!argv[1])
  10315. return showvars(nullstr, 0, VUNSET);
  10316. INT_OFF;
  10317. retval = options(/*login_sh:*/ NULL);
  10318. if (retval == 0) { /* if no parse error... */
  10319. optschanged();
  10320. if (*argptr != NULL) {
  10321. setparam(argptr);
  10322. }
  10323. }
  10324. INT_ON;
  10325. return retval;
  10326. }
  10327. #if ENABLE_ASH_RANDOM_SUPPORT
  10328. static void FAST_FUNC
  10329. change_random(const char *value)
  10330. {
  10331. uint32_t t;
  10332. if (value == NULL) {
  10333. /* "get", generate */
  10334. t = next_random(&random_gen);
  10335. /* set without recursion */
  10336. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10337. vrandom.flags &= ~VNOFUNC;
  10338. } else {
  10339. /* set/reset */
  10340. t = strtoul(value, NULL, 10);
  10341. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10342. }
  10343. }
  10344. #endif
  10345. #if BASH_EPOCH_VARS
  10346. static void FAST_FUNC
  10347. change_epoch(struct var *vepoch, const char *fmt)
  10348. {
  10349. struct timeval tv;
  10350. char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  10351. gettimeofday(&tv, NULL);
  10352. sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
  10353. setvar(vepoch->var_text, buffer, VNOFUNC);
  10354. vepoch->flags &= ~VNOFUNC;
  10355. }
  10356. static void FAST_FUNC
  10357. change_seconds(const char *value UNUSED_PARAM)
  10358. {
  10359. change_epoch(&vepochs, "%lu");
  10360. }
  10361. static void FAST_FUNC
  10362. change_realtime(const char *value UNUSED_PARAM)
  10363. {
  10364. change_epoch(&vepochr, "%lu.%06u");
  10365. }
  10366. #endif
  10367. #if ENABLE_ASH_GETOPTS
  10368. static int
  10369. getopts(char *optstr, char *optvar, char **optfirst)
  10370. {
  10371. char *p, *q;
  10372. char c = '?';
  10373. int done = 0;
  10374. char sbuf[2];
  10375. char **optnext;
  10376. int ind = shellparam.optind;
  10377. int off = shellparam.optoff;
  10378. sbuf[1] = '\0';
  10379. shellparam.optind = -1;
  10380. optnext = optfirst + ind - 1;
  10381. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10382. p = NULL;
  10383. else
  10384. p = optnext[-1] + off;
  10385. if (p == NULL || *p == '\0') {
  10386. /* Current word is done, advance */
  10387. p = *optnext;
  10388. if (p == NULL || *p != '-' || *++p == '\0') {
  10389. atend:
  10390. unsetvar("OPTARG");
  10391. p = NULL;
  10392. done = 1;
  10393. goto out;
  10394. }
  10395. optnext++;
  10396. if (LONE_DASH(p)) /* check for "--" */
  10397. goto atend;
  10398. }
  10399. c = *p++;
  10400. for (q = optstr; *q != c;) {
  10401. if (*q == '\0') {
  10402. /* OPTERR is a bashism */
  10403. const char *cp = lookupvar("OPTERR");
  10404. if ((cp && LONE_CHAR(cp, '0'))
  10405. || (optstr[0] == ':')
  10406. ) {
  10407. sbuf[0] = c;
  10408. /*sbuf[1] = '\0'; - already is */
  10409. setvar0("OPTARG", sbuf);
  10410. } else {
  10411. fprintf(stderr, "Illegal option -%c\n", c);
  10412. unsetvar("OPTARG");
  10413. }
  10414. c = '?';
  10415. goto out;
  10416. }
  10417. if (*++q == ':')
  10418. q++;
  10419. }
  10420. if (*++q == ':') {
  10421. if (*p == '\0' && (p = *optnext) == NULL) {
  10422. /* OPTERR is a bashism */
  10423. const char *cp = lookupvar("OPTERR");
  10424. if ((cp && LONE_CHAR(cp, '0'))
  10425. || (optstr[0] == ':')
  10426. ) {
  10427. sbuf[0] = c;
  10428. /*sbuf[1] = '\0'; - already is */
  10429. setvar0("OPTARG", sbuf);
  10430. c = ':';
  10431. } else {
  10432. fprintf(stderr, "No arg for -%c option\n", c);
  10433. unsetvar("OPTARG");
  10434. c = '?';
  10435. }
  10436. goto out;
  10437. }
  10438. if (p == *optnext)
  10439. optnext++;
  10440. setvar0("OPTARG", p);
  10441. p = NULL;
  10442. } else
  10443. setvar0("OPTARG", nullstr);
  10444. out:
  10445. ind = optnext - optfirst + 1;
  10446. setvar("OPTIND", itoa(ind), VNOFUNC);
  10447. sbuf[0] = c;
  10448. /*sbuf[1] = '\0'; - already is */
  10449. setvar0(optvar, sbuf);
  10450. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10451. shellparam.optind = ind;
  10452. return done;
  10453. }
  10454. /*
  10455. * The getopts builtin. Shellparam.optnext points to the next argument
  10456. * to be processed. Shellparam.optptr points to the next character to
  10457. * be processed in the current argument. If shellparam.optnext is NULL,
  10458. * then it's the first time getopts has been called.
  10459. */
  10460. static int FAST_FUNC
  10461. getoptscmd(int argc, char **argv)
  10462. {
  10463. char **optbase;
  10464. if (argc < 3)
  10465. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10466. if (argc == 3) {
  10467. optbase = shellparam.p;
  10468. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10469. shellparam.optind = 1;
  10470. shellparam.optoff = -1;
  10471. }
  10472. } else {
  10473. optbase = &argv[3];
  10474. if ((unsigned)shellparam.optind > argc - 2) {
  10475. shellparam.optind = 1;
  10476. shellparam.optoff = -1;
  10477. }
  10478. }
  10479. return getopts(argv[1], argv[2], optbase);
  10480. }
  10481. #endif /* ASH_GETOPTS */
  10482. /* ============ Shell parser */
  10483. struct heredoc {
  10484. struct heredoc *next; /* next here document in list */
  10485. union node *here; /* redirection node */
  10486. char *eofmark; /* string indicating end of input */
  10487. smallint striptabs; /* if set, strip leading tabs */
  10488. };
  10489. static smallint tokpushback; /* last token pushed back */
  10490. static smallint quoteflag; /* set if (part of) last token was quoted */
  10491. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10492. static struct heredoc *heredoclist; /* list of here documents to read */
  10493. static char *wordtext; /* text of last word returned by readtoken */
  10494. static struct nodelist *backquotelist;
  10495. static union node *redirnode;
  10496. static struct heredoc *heredoc;
  10497. static const char *
  10498. tokname(char *buf, int tok)
  10499. {
  10500. if (tok < TSEMI)
  10501. return tokname_array[tok];
  10502. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10503. return buf;
  10504. }
  10505. /* raise_error_unexpected_syntax:
  10506. * Called when an unexpected token is read during the parse. The argument
  10507. * is the token that is expected, or -1 if more than one type of token can
  10508. * occur at this point.
  10509. */
  10510. static void raise_error_unexpected_syntax(int) NORETURN;
  10511. static void
  10512. raise_error_unexpected_syntax(int token)
  10513. {
  10514. char msg[64];
  10515. char buf[16];
  10516. int l;
  10517. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10518. if (token >= 0)
  10519. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10520. raise_error_syntax(msg);
  10521. /* NOTREACHED */
  10522. }
  10523. /* parsing is heavily cross-recursive, need these forward decls */
  10524. static union node *andor(void);
  10525. static union node *pipeline(void);
  10526. static union node *parse_command(void);
  10527. static void parseheredoc(void);
  10528. static int peektoken(void);
  10529. static int readtoken(void);
  10530. static union node *
  10531. list(int nlflag)
  10532. {
  10533. union node *n1, *n2, *n3;
  10534. int tok;
  10535. n1 = NULL;
  10536. for (;;) {
  10537. switch (readtoken()) {
  10538. case TNL:
  10539. if (!(nlflag & 1))
  10540. break;
  10541. parseheredoc();
  10542. return n1;
  10543. case TEOF:
  10544. if (!n1 && (nlflag & 1))
  10545. n1 = NODE_EOF;
  10546. parseheredoc();
  10547. tokpushback++;
  10548. lasttoken = TEOF;
  10549. return n1;
  10550. }
  10551. tokpushback++;
  10552. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10553. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10554. return n1;
  10555. nlflag |= 2;
  10556. n2 = andor();
  10557. tok = readtoken();
  10558. if (tok == TBACKGND) {
  10559. if (n2->type == NPIPE) {
  10560. n2->npipe.pipe_backgnd = 1;
  10561. } else {
  10562. if (n2->type != NREDIR) {
  10563. n3 = stzalloc(sizeof(struct nredir));
  10564. n3->nredir.n = n2;
  10565. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10566. n2 = n3;
  10567. }
  10568. n2->type = NBACKGND;
  10569. }
  10570. }
  10571. if (n1 == NULL) {
  10572. n1 = n2;
  10573. } else {
  10574. n3 = stzalloc(sizeof(struct nbinary));
  10575. n3->type = NSEMI;
  10576. n3->nbinary.ch1 = n1;
  10577. n3->nbinary.ch2 = n2;
  10578. n1 = n3;
  10579. }
  10580. switch (tok) {
  10581. case TNL:
  10582. case TEOF:
  10583. tokpushback = 1;
  10584. /* fall through */
  10585. case TBACKGND:
  10586. case TSEMI:
  10587. break;
  10588. default:
  10589. if ((nlflag & 1))
  10590. raise_error_unexpected_syntax(-1);
  10591. tokpushback = 1;
  10592. return n1;
  10593. }
  10594. }
  10595. }
  10596. static union node *
  10597. andor(void)
  10598. {
  10599. union node *n1, *n2, *n3;
  10600. int t;
  10601. n1 = pipeline();
  10602. for (;;) {
  10603. t = readtoken();
  10604. if (t == TAND) {
  10605. t = NAND;
  10606. } else if (t == TOR) {
  10607. t = NOR;
  10608. } else {
  10609. tokpushback = 1;
  10610. return n1;
  10611. }
  10612. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10613. n2 = pipeline();
  10614. n3 = stzalloc(sizeof(struct nbinary));
  10615. n3->type = t;
  10616. n3->nbinary.ch1 = n1;
  10617. n3->nbinary.ch2 = n2;
  10618. n1 = n3;
  10619. }
  10620. }
  10621. static union node *
  10622. pipeline(void)
  10623. {
  10624. union node *n1, *n2, *pipenode;
  10625. struct nodelist *lp, *prev;
  10626. int negate;
  10627. negate = 0;
  10628. TRACE(("pipeline: entered\n"));
  10629. if (readtoken() == TNOT) {
  10630. negate = !negate;
  10631. checkkwd = CHKKWD | CHKALIAS;
  10632. } else
  10633. tokpushback = 1;
  10634. n1 = parse_command();
  10635. if (readtoken() == TPIPE) {
  10636. pipenode = stzalloc(sizeof(struct npipe));
  10637. pipenode->type = NPIPE;
  10638. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10639. lp = stzalloc(sizeof(struct nodelist));
  10640. pipenode->npipe.cmdlist = lp;
  10641. lp->n = n1;
  10642. do {
  10643. prev = lp;
  10644. lp = stzalloc(sizeof(struct nodelist));
  10645. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10646. lp->n = parse_command();
  10647. prev->next = lp;
  10648. } while (readtoken() == TPIPE);
  10649. lp->next = NULL;
  10650. n1 = pipenode;
  10651. }
  10652. tokpushback = 1;
  10653. if (negate) {
  10654. n2 = stzalloc(sizeof(struct nnot));
  10655. n2->type = NNOT;
  10656. n2->nnot.com = n1;
  10657. return n2;
  10658. }
  10659. return n1;
  10660. }
  10661. static union node *
  10662. makename(void)
  10663. {
  10664. union node *n;
  10665. n = stzalloc(sizeof(struct narg));
  10666. n->type = NARG;
  10667. /*n->narg.next = NULL; - stzalloc did it */
  10668. n->narg.text = wordtext;
  10669. n->narg.backquote = backquotelist;
  10670. return n;
  10671. }
  10672. static void
  10673. fixredir(union node *n, const char *text, int err)
  10674. {
  10675. int fd;
  10676. TRACE(("Fix redir %s %d\n", text, err));
  10677. if (!err)
  10678. n->ndup.vname = NULL;
  10679. fd = bb_strtou(text, NULL, 10);
  10680. if (!errno && fd >= 0)
  10681. n->ndup.dupfd = fd;
  10682. else if (LONE_DASH(text))
  10683. n->ndup.dupfd = -1;
  10684. else {
  10685. if (err)
  10686. raise_error_syntax("bad fd number");
  10687. n->ndup.vname = makename();
  10688. }
  10689. }
  10690. static void
  10691. parsefname(void)
  10692. {
  10693. union node *n = redirnode;
  10694. if (n->type == NHERE)
  10695. checkkwd = CHKEOFMARK;
  10696. if (readtoken() != TWORD)
  10697. raise_error_unexpected_syntax(-1);
  10698. if (n->type == NHERE) {
  10699. struct heredoc *here = heredoc;
  10700. struct heredoc *p;
  10701. if (quoteflag == 0)
  10702. n->type = NXHERE;
  10703. TRACE(("Here document %d\n", n->type));
  10704. rmescapes(wordtext, 0, NULL);
  10705. here->eofmark = wordtext;
  10706. here->next = NULL;
  10707. if (heredoclist == NULL)
  10708. heredoclist = here;
  10709. else {
  10710. for (p = heredoclist; p->next; p = p->next)
  10711. continue;
  10712. p->next = here;
  10713. }
  10714. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10715. fixredir(n, wordtext, 0);
  10716. } else {
  10717. n->nfile.fname = makename();
  10718. }
  10719. }
  10720. static union node *
  10721. simplecmd(void)
  10722. {
  10723. union node *args, **app;
  10724. union node *n = NULL;
  10725. union node *vars, **vpp;
  10726. union node **rpp, *redir;
  10727. int savecheckkwd;
  10728. int savelinno;
  10729. #if BASH_TEST2
  10730. smallint double_brackets_flag = 0;
  10731. #endif
  10732. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10733. args = NULL;
  10734. app = &args;
  10735. vars = NULL;
  10736. vpp = &vars;
  10737. redir = NULL;
  10738. rpp = &redir;
  10739. savecheckkwd = CHKALIAS;
  10740. savelinno = g_parsefile->linno;
  10741. for (;;) {
  10742. int t;
  10743. checkkwd = savecheckkwd;
  10744. t = readtoken();
  10745. switch (t) {
  10746. #if BASH_FUNCTION
  10747. case TFUNCTION:
  10748. if (peektoken() != TWORD)
  10749. raise_error_unexpected_syntax(TWORD);
  10750. function_flag = 1;
  10751. break;
  10752. #endif
  10753. #if BASH_TEST2
  10754. case TAND: /* "&&" */
  10755. case TOR: /* "||" */
  10756. if (!double_brackets_flag) {
  10757. tokpushback = 1;
  10758. goto out;
  10759. }
  10760. /* pass "&&" or "||" to [[ ]] as literal args */
  10761. wordtext = (char *) (t == TAND ? "&&" : "||");
  10762. #endif
  10763. case TWORD:
  10764. n = stzalloc(sizeof(struct narg));
  10765. n->type = NARG;
  10766. /*n->narg.next = NULL; - stzalloc did it */
  10767. n->narg.text = wordtext;
  10768. #if BASH_TEST2
  10769. if (strcmp("[[", wordtext) == 0)
  10770. double_brackets_flag = 1;
  10771. else if (strcmp("]]", wordtext) == 0)
  10772. double_brackets_flag = 0;
  10773. #endif
  10774. n->narg.backquote = backquotelist;
  10775. if (savecheckkwd && isassignment(wordtext)) {
  10776. *vpp = n;
  10777. vpp = &n->narg.next;
  10778. } else {
  10779. *app = n;
  10780. app = &n->narg.next;
  10781. savecheckkwd = 0;
  10782. }
  10783. #if BASH_FUNCTION
  10784. if (function_flag) {
  10785. checkkwd = CHKNL | CHKKWD;
  10786. switch (peektoken()) {
  10787. case TBEGIN:
  10788. case TIF:
  10789. case TCASE:
  10790. case TUNTIL:
  10791. case TWHILE:
  10792. case TFOR:
  10793. goto do_func;
  10794. case TLP:
  10795. function_flag = 0;
  10796. break;
  10797. # if BASH_TEST2
  10798. case TWORD:
  10799. if (strcmp("[[", wordtext) == 0)
  10800. goto do_func;
  10801. /* fall through */
  10802. # endif
  10803. default:
  10804. raise_error_unexpected_syntax(-1);
  10805. }
  10806. }
  10807. #endif
  10808. break;
  10809. case TREDIR:
  10810. *rpp = n = redirnode;
  10811. rpp = &n->nfile.next;
  10812. parsefname(); /* read name of redirection file */
  10813. break;
  10814. case TLP:
  10815. IF_BASH_FUNCTION(do_func:)
  10816. if (args && app == &args->narg.next
  10817. && !vars && !redir
  10818. ) {
  10819. struct builtincmd *bcmd;
  10820. const char *name;
  10821. /* We have a function */
  10822. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10823. raise_error_unexpected_syntax(TRP);
  10824. name = n->narg.text;
  10825. if (!goodname(name)
  10826. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10827. ) {
  10828. raise_error_syntax("bad function name");
  10829. }
  10830. n->type = NDEFUN;
  10831. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10832. n->ndefun.text = n->narg.text;
  10833. n->ndefun.linno = g_parsefile->linno;
  10834. n->ndefun.body = parse_command();
  10835. return n;
  10836. }
  10837. IF_BASH_FUNCTION(function_flag = 0;)
  10838. /* fall through */
  10839. default:
  10840. tokpushback = 1;
  10841. goto out;
  10842. }
  10843. }
  10844. out:
  10845. *app = NULL;
  10846. *vpp = NULL;
  10847. *rpp = NULL;
  10848. n = stzalloc(sizeof(struct ncmd));
  10849. if (NCMD != 0)
  10850. n->type = NCMD;
  10851. n->ncmd.linno = savelinno;
  10852. n->ncmd.args = args;
  10853. n->ncmd.assign = vars;
  10854. n->ncmd.redirect = redir;
  10855. return n;
  10856. }
  10857. static union node *
  10858. parse_command(void)
  10859. {
  10860. union node *n1, *n2;
  10861. union node *ap, **app;
  10862. union node *cp, **cpp;
  10863. union node *redir, **rpp;
  10864. union node **rpp2;
  10865. int t;
  10866. int savelinno;
  10867. redir = NULL;
  10868. rpp2 = &redir;
  10869. savelinno = g_parsefile->linno;
  10870. switch (readtoken()) {
  10871. default:
  10872. raise_error_unexpected_syntax(-1);
  10873. /* NOTREACHED */
  10874. case TIF:
  10875. n1 = stzalloc(sizeof(struct nif));
  10876. n1->type = NIF;
  10877. n1->nif.test = list(0);
  10878. if (readtoken() != TTHEN)
  10879. raise_error_unexpected_syntax(TTHEN);
  10880. n1->nif.ifpart = list(0);
  10881. n2 = n1;
  10882. while (readtoken() == TELIF) {
  10883. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10884. n2 = n2->nif.elsepart;
  10885. n2->type = NIF;
  10886. n2->nif.test = list(0);
  10887. if (readtoken() != TTHEN)
  10888. raise_error_unexpected_syntax(TTHEN);
  10889. n2->nif.ifpart = list(0);
  10890. }
  10891. if (lasttoken == TELSE)
  10892. n2->nif.elsepart = list(0);
  10893. else {
  10894. n2->nif.elsepart = NULL;
  10895. tokpushback = 1;
  10896. }
  10897. t = TFI;
  10898. break;
  10899. case TWHILE:
  10900. case TUNTIL: {
  10901. int got;
  10902. n1 = stzalloc(sizeof(struct nbinary));
  10903. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10904. n1->nbinary.ch1 = list(0);
  10905. got = readtoken();
  10906. if (got != TDO) {
  10907. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10908. got == TWORD ? wordtext : ""));
  10909. raise_error_unexpected_syntax(TDO);
  10910. }
  10911. n1->nbinary.ch2 = list(0);
  10912. t = TDONE;
  10913. break;
  10914. }
  10915. case TFOR:
  10916. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10917. raise_error_syntax("bad for loop variable");
  10918. n1 = stzalloc(sizeof(struct nfor));
  10919. n1->type = NFOR;
  10920. n1->nfor.linno = savelinno;
  10921. n1->nfor.var = wordtext;
  10922. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10923. if (readtoken() == TIN) {
  10924. app = &ap;
  10925. while (readtoken() == TWORD) {
  10926. n2 = stzalloc(sizeof(struct narg));
  10927. n2->type = NARG;
  10928. /*n2->narg.next = NULL; - stzalloc did it */
  10929. n2->narg.text = wordtext;
  10930. n2->narg.backquote = backquotelist;
  10931. *app = n2;
  10932. app = &n2->narg.next;
  10933. }
  10934. *app = NULL;
  10935. n1->nfor.args = ap;
  10936. if (lasttoken != TNL && lasttoken != TSEMI)
  10937. raise_error_unexpected_syntax(-1);
  10938. } else {
  10939. n2 = stzalloc(sizeof(struct narg));
  10940. n2->type = NARG;
  10941. /*n2->narg.next = NULL; - stzalloc did it */
  10942. n2->narg.text = (char *)dolatstr;
  10943. /*n2->narg.backquote = NULL;*/
  10944. n1->nfor.args = n2;
  10945. /*
  10946. * Newline or semicolon here is optional (but note
  10947. * that the original Bourne shell only allowed NL).
  10948. */
  10949. if (lasttoken != TSEMI)
  10950. tokpushback = 1;
  10951. }
  10952. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10953. if (readtoken() != TDO)
  10954. raise_error_unexpected_syntax(TDO);
  10955. n1->nfor.body = list(0);
  10956. t = TDONE;
  10957. break;
  10958. case TCASE:
  10959. n1 = stzalloc(sizeof(struct ncase));
  10960. n1->type = NCASE;
  10961. n1->ncase.linno = savelinno;
  10962. if (readtoken() != TWORD)
  10963. raise_error_unexpected_syntax(TWORD);
  10964. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10965. n2->type = NARG;
  10966. /*n2->narg.next = NULL; - stzalloc did it */
  10967. n2->narg.text = wordtext;
  10968. n2->narg.backquote = backquotelist;
  10969. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10970. if (readtoken() != TIN)
  10971. raise_error_unexpected_syntax(TIN);
  10972. cpp = &n1->ncase.cases;
  10973. next_case:
  10974. checkkwd = CHKNL | CHKKWD;
  10975. t = readtoken();
  10976. while (t != TESAC) {
  10977. if (lasttoken == TLP)
  10978. readtoken();
  10979. *cpp = cp = stzalloc(sizeof(struct nclist));
  10980. cp->type = NCLIST;
  10981. app = &cp->nclist.pattern;
  10982. for (;;) {
  10983. *app = ap = stzalloc(sizeof(struct narg));
  10984. ap->type = NARG;
  10985. /*ap->narg.next = NULL; - stzalloc did it */
  10986. ap->narg.text = wordtext;
  10987. ap->narg.backquote = backquotelist;
  10988. if (readtoken() != TPIPE)
  10989. break;
  10990. app = &ap->narg.next;
  10991. readtoken();
  10992. }
  10993. //ap->narg.next = NULL;
  10994. if (lasttoken != TRP)
  10995. raise_error_unexpected_syntax(TRP);
  10996. cp->nclist.body = list(2);
  10997. cpp = &cp->nclist.next;
  10998. checkkwd = CHKNL | CHKKWD;
  10999. t = readtoken();
  11000. if (t != TESAC) {
  11001. if (t != TENDCASE)
  11002. raise_error_unexpected_syntax(TENDCASE);
  11003. goto next_case;
  11004. }
  11005. }
  11006. *cpp = NULL;
  11007. goto redir;
  11008. case TLP:
  11009. n1 = stzalloc(sizeof(struct nredir));
  11010. n1->type = NSUBSHELL;
  11011. n1->nredir.linno = savelinno;
  11012. n1->nredir.n = list(0);
  11013. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11014. t = TRP;
  11015. break;
  11016. case TBEGIN:
  11017. n1 = list(0);
  11018. t = TEND;
  11019. break;
  11020. IF_BASH_FUNCTION(case TFUNCTION:)
  11021. case TWORD:
  11022. case TREDIR:
  11023. tokpushback = 1;
  11024. return simplecmd();
  11025. }
  11026. if (readtoken() != t)
  11027. raise_error_unexpected_syntax(t);
  11028. redir:
  11029. /* Now check for redirection which may follow command */
  11030. checkkwd = CHKKWD | CHKALIAS;
  11031. rpp = rpp2;
  11032. while (readtoken() == TREDIR) {
  11033. *rpp = n2 = redirnode;
  11034. rpp = &n2->nfile.next;
  11035. parsefname();
  11036. }
  11037. tokpushback = 1;
  11038. *rpp = NULL;
  11039. if (redir) {
  11040. if (n1->type != NSUBSHELL) {
  11041. n2 = stzalloc(sizeof(struct nredir));
  11042. n2->type = NREDIR;
  11043. n2->nredir.linno = savelinno;
  11044. n2->nredir.n = n1;
  11045. n1 = n2;
  11046. }
  11047. n1->nredir.redirect = redir;
  11048. }
  11049. return n1;
  11050. }
  11051. #if BASH_DOLLAR_SQUOTE
  11052. static int
  11053. decode_dollar_squote(void)
  11054. {
  11055. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11056. int c, cnt;
  11057. char *p;
  11058. char buf[4];
  11059. c = pgetc();
  11060. p = strchr(C_escapes, c);
  11061. if (p) {
  11062. buf[0] = c;
  11063. p = buf;
  11064. cnt = 3;
  11065. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11066. do {
  11067. c = pgetc();
  11068. *++p = c;
  11069. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11070. pungetc();
  11071. } else if (c == 'x') { /* \xHH */
  11072. do {
  11073. c = pgetc();
  11074. *++p = c;
  11075. } while (isxdigit(c) && --cnt);
  11076. pungetc();
  11077. if (cnt == 3) { /* \x but next char is "bad" */
  11078. c = 'x';
  11079. goto unrecognized;
  11080. }
  11081. } else { /* simple seq like \\ or \t */
  11082. p++;
  11083. }
  11084. *p = '\0';
  11085. p = buf;
  11086. c = bb_process_escape_sequence((void*)&p);
  11087. } else { /* unrecognized "\z": print both chars unless ' or " */
  11088. if (c != '\'' && c != '"') {
  11089. unrecognized:
  11090. c |= 0x100; /* "please encode \, then me" */
  11091. }
  11092. }
  11093. return c;
  11094. }
  11095. #endif
  11096. /* Used by expandstr to get here-doc like behaviour. */
  11097. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11098. static ALWAYS_INLINE int
  11099. realeofmark(const char *eofmark)
  11100. {
  11101. return eofmark && eofmark != FAKEEOFMARK;
  11102. }
  11103. /*
  11104. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11105. * is not NULL, read a here document. In the latter case, eofmark is the
  11106. * word which marks the end of the document and striptabs is true if
  11107. * leading tabs should be stripped from the document. The argument c
  11108. * is the first character of the input token or document.
  11109. *
  11110. * Because C does not have internal subroutines, I have simulated them
  11111. * using goto's to implement the subroutine linkage. The following macros
  11112. * will run code that appears at the end of readtoken1.
  11113. */
  11114. #define CHECKEND() {goto checkend; checkend_return:;}
  11115. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11116. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11117. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11118. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11119. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11120. static int
  11121. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11122. {
  11123. /* NB: syntax parameter fits into smallint */
  11124. /* c parameter is an unsigned char or PEOF or PEOA */
  11125. char *out;
  11126. size_t len;
  11127. struct nodelist *bqlist;
  11128. smallint quotef;
  11129. smallint oldstyle;
  11130. smallint pssyntax; /* we are expanding a prompt string */
  11131. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11132. /* syntax stack */
  11133. struct synstack synbase = { };
  11134. struct synstack *synstack = &synbase;
  11135. #if ENABLE_ASH_EXPAND_PRMT
  11136. pssyntax = (syntax == PSSYNTAX);
  11137. if (pssyntax)
  11138. syntax = DQSYNTAX;
  11139. #else
  11140. pssyntax = 0; /* constant */
  11141. #endif
  11142. synstack->syntax = syntax;
  11143. if (syntax == DQSYNTAX)
  11144. synstack->dblquote = 1;
  11145. quotef = 0;
  11146. bqlist = NULL;
  11147. STARTSTACKSTR(out);
  11148. loop:
  11149. /* For each line, until end of word */
  11150. CHECKEND(); /* set c to PEOF if at end of here document */
  11151. for (;;) { /* until end of line or end of word */
  11152. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11153. switch (SIT(c, synstack->syntax)) {
  11154. case CNL: /* '\n' */
  11155. if (synstack->syntax == BASESYNTAX
  11156. && !synstack->varnest
  11157. ) {
  11158. goto endword; /* exit outer loop */
  11159. }
  11160. USTPUTC(c, out);
  11161. nlprompt();
  11162. c = pgetc_top(synstack);
  11163. goto loop; /* continue outer loop */
  11164. case CWORD:
  11165. USTPUTC(c, out);
  11166. break;
  11167. case CCTL:
  11168. #if BASH_DOLLAR_SQUOTE
  11169. if (c == '\\' && bash_dollar_squote) {
  11170. c = decode_dollar_squote();
  11171. if (c == '\0') {
  11172. /* skip $'\000', $'\x00' (like bash) */
  11173. break;
  11174. }
  11175. if (c & 0x100) {
  11176. /* Unknown escape. Encode as '\z' */
  11177. c = (unsigned char)c;
  11178. if (eofmark == NULL || synstack->dblquote)
  11179. USTPUTC(CTLESC, out);
  11180. USTPUTC('\\', out);
  11181. }
  11182. }
  11183. #endif
  11184. if (!eofmark || synstack->dblquote || synstack->varnest)
  11185. USTPUTC(CTLESC, out);
  11186. USTPUTC(c, out);
  11187. break;
  11188. case CBACK: /* backslash */
  11189. c = pgetc_without_PEOA();
  11190. if (c == PEOF) {
  11191. USTPUTC(CTLESC, out);
  11192. USTPUTC('\\', out);
  11193. pungetc();
  11194. } else {
  11195. if (pssyntax && c == '$') {
  11196. USTPUTC(CTLESC, out);
  11197. USTPUTC('\\', out);
  11198. }
  11199. /* Backslash is retained if we are in "str"
  11200. * and next char isn't dquote-special.
  11201. */
  11202. if (synstack->dblquote
  11203. && c != '\\'
  11204. && c != '`'
  11205. && c != '$'
  11206. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11207. && (c != '}' || !synstack->varnest)
  11208. ) {
  11209. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11210. USTPUTC('\\', out);
  11211. }
  11212. USTPUTC(CTLESC, out);
  11213. USTPUTC(c, out);
  11214. quotef = 1;
  11215. }
  11216. break;
  11217. case CSQUOTE:
  11218. synstack->syntax = SQSYNTAX;
  11219. quotemark:
  11220. if (eofmark == NULL) {
  11221. USTPUTC(CTLQUOTEMARK, out);
  11222. }
  11223. break;
  11224. case CDQUOTE:
  11225. synstack->syntax = DQSYNTAX;
  11226. synstack->dblquote = 1;
  11227. toggledq:
  11228. if (synstack->varnest)
  11229. synstack->innerdq ^= 1;
  11230. goto quotemark;
  11231. case CENDQUOTE:
  11232. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11233. if (eofmark != NULL && synstack->varnest == 0) {
  11234. USTPUTC(c, out);
  11235. break;
  11236. }
  11237. if (synstack->dqvarnest == 0) {
  11238. synstack->syntax = BASESYNTAX;
  11239. synstack->dblquote = 0;
  11240. }
  11241. quotef = 1;
  11242. if (c == '"')
  11243. goto toggledq;
  11244. goto quotemark;
  11245. case CVAR: /* '$' */
  11246. PARSESUB(); /* parse substitution */
  11247. break;
  11248. case CENDVAR: /* '}' */
  11249. if (!synstack->innerdq && synstack->varnest > 0) {
  11250. if (!--synstack->varnest && synstack->varpushed)
  11251. synstack_pop(&synstack);
  11252. else if (synstack->dqvarnest > 0)
  11253. synstack->dqvarnest--;
  11254. c = CTLENDVAR;
  11255. }
  11256. USTPUTC(c, out);
  11257. break;
  11258. #if ENABLE_FEATURE_SH_MATH
  11259. case CLP: /* '(' in arithmetic */
  11260. synstack->parenlevel++;
  11261. USTPUTC(c, out);
  11262. break;
  11263. case CRP: /* ')' in arithmetic */
  11264. if (synstack->parenlevel > 0) {
  11265. synstack->parenlevel--;
  11266. } else {
  11267. if (pgetc_eatbnl() == ')') {
  11268. c = CTLENDARI;
  11269. synstack_pop(&synstack);
  11270. } else {
  11271. /*
  11272. * unbalanced parens
  11273. * (don't 2nd guess - no error)
  11274. */
  11275. pungetc();
  11276. }
  11277. }
  11278. USTPUTC(c, out);
  11279. break;
  11280. #endif
  11281. case CBQUOTE: /* '`' */
  11282. if (checkkwd & CHKEOFMARK) {
  11283. quotef = 1;
  11284. USTPUTC('`', out);
  11285. break;
  11286. }
  11287. PARSEBACKQOLD();
  11288. break;
  11289. case CENDFILE:
  11290. goto endword; /* exit outer loop */
  11291. case CIGN:
  11292. break;
  11293. default:
  11294. if (synstack->varnest == 0) {
  11295. #if BASH_REDIR_OUTPUT
  11296. if (c == '&') {
  11297. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11298. if (pgetc() == '>')
  11299. c = 0x100 + '>'; /* flag &> */
  11300. pungetc();
  11301. }
  11302. #endif
  11303. goto endword; /* exit outer loop */
  11304. }
  11305. IF_ASH_ALIAS(if (c != PEOA))
  11306. USTPUTC(c, out);
  11307. }
  11308. c = pgetc_top(synstack);
  11309. } /* for (;;) */
  11310. endword:
  11311. #if ENABLE_FEATURE_SH_MATH
  11312. if (synstack->syntax == ARISYNTAX)
  11313. raise_error_syntax("missing '))'");
  11314. #endif
  11315. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11316. raise_error_syntax("unterminated quoted string");
  11317. if (synstack->varnest != 0) {
  11318. /* { */
  11319. raise_error_syntax("missing '}'");
  11320. }
  11321. USTPUTC('\0', out);
  11322. len = out - (char *)stackblock();
  11323. out = stackblock();
  11324. if (eofmark == NULL) {
  11325. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11326. && quotef == 0
  11327. ) {
  11328. if (isdigit_str9(out)) {
  11329. PARSEREDIR(); /* passed as params: out, c */
  11330. lasttoken = TREDIR;
  11331. return lasttoken;
  11332. }
  11333. /* else: non-number X seen, interpret it
  11334. * as "NNNX>file" = "NNNX >file" */
  11335. }
  11336. pungetc();
  11337. }
  11338. quoteflag = quotef;
  11339. backquotelist = bqlist;
  11340. grabstackblock(len);
  11341. wordtext = out;
  11342. lasttoken = TWORD;
  11343. return lasttoken;
  11344. /* end of readtoken routine */
  11345. /*
  11346. * Check to see whether we are at the end of the here document. When this
  11347. * is called, c is set to the first character of the next input line. If
  11348. * we are at the end of the here document, this routine sets the c to PEOF.
  11349. */
  11350. checkend: {
  11351. if (realeofmark(eofmark)) {
  11352. int markloc;
  11353. char *p;
  11354. #if ENABLE_ASH_ALIAS
  11355. if (c == PEOA)
  11356. c = pgetc_without_PEOA();
  11357. #endif
  11358. if (striptabs) {
  11359. while (c == '\t') {
  11360. c = pgetc_without_PEOA();
  11361. }
  11362. }
  11363. markloc = out - (char *)stackblock();
  11364. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11365. if (c != *p)
  11366. goto more_heredoc;
  11367. /* FIXME: fails for backslash-newlined terminator:
  11368. * cat <<EOF
  11369. * ...
  11370. * EO\
  11371. * F
  11372. * (see heredoc_bkslash_newline2.tests)
  11373. */
  11374. c = pgetc_without_PEOA();
  11375. }
  11376. if (c == '\n' || c == PEOF) {
  11377. c = PEOF;
  11378. g_parsefile->linno++;
  11379. needprompt = doprompt;
  11380. } else {
  11381. int len_here;
  11382. more_heredoc:
  11383. p = (char *)stackblock() + markloc + 1;
  11384. len_here = out - p;
  11385. if (len_here) {
  11386. len_here -= (c >= PEOF);
  11387. c = p[-1];
  11388. if (len_here) {
  11389. char *str;
  11390. str = alloca(len_here + 1);
  11391. *(char *)mempcpy(str, p, len_here) = '\0';
  11392. pushstring(str, NULL);
  11393. }
  11394. }
  11395. }
  11396. STADJUST((char *)stackblock() + markloc - out, out);
  11397. }
  11398. goto checkend_return;
  11399. }
  11400. /*
  11401. * Parse a redirection operator. The variable "out" points to a string
  11402. * specifying the fd to be redirected. The variable "c" contains the
  11403. * first character of the redirection operator.
  11404. */
  11405. parseredir: {
  11406. /* out is already checked to be a valid number or "" */
  11407. int fd = (*out == '\0' ? -1 : atoi(out));
  11408. union node *np;
  11409. np = stzalloc(sizeof(struct nfile));
  11410. if (c == '>') {
  11411. np->nfile.fd = 1;
  11412. c = pgetc_eatbnl();
  11413. if (c == '>')
  11414. np->type = NAPPEND;
  11415. else if (c == '|')
  11416. np->type = NCLOBBER;
  11417. else if (c == '&')
  11418. np->type = NTOFD;
  11419. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11420. else {
  11421. np->type = NTO;
  11422. pungetc();
  11423. }
  11424. }
  11425. #if BASH_REDIR_OUTPUT
  11426. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11427. np->nfile.fd = 1;
  11428. pgetc(); /* this is '>', no need to check */
  11429. np->type = NTO2;
  11430. }
  11431. #endif
  11432. else { /* c == '<' */
  11433. /*np->nfile.fd = 0; - stzalloc did it */
  11434. c = pgetc_eatbnl();
  11435. switch (c) {
  11436. case '<':
  11437. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11438. np = stzalloc(sizeof(struct nhere));
  11439. /*np->nfile.fd = 0; - stzalloc did it */
  11440. }
  11441. np->type = NHERE;
  11442. heredoc = stzalloc(sizeof(struct heredoc));
  11443. heredoc->here = np;
  11444. c = pgetc_eatbnl();
  11445. if (c == '-') {
  11446. heredoc->striptabs = 1;
  11447. } else {
  11448. /*heredoc->striptabs = 0; - stzalloc did it */
  11449. pungetc();
  11450. }
  11451. break;
  11452. case '&':
  11453. np->type = NFROMFD;
  11454. break;
  11455. case '>':
  11456. np->type = NFROMTO;
  11457. break;
  11458. default:
  11459. np->type = NFROM;
  11460. pungetc();
  11461. break;
  11462. }
  11463. }
  11464. if (fd >= 0)
  11465. np->nfile.fd = fd;
  11466. redirnode = np;
  11467. goto parseredir_return;
  11468. }
  11469. /*
  11470. * Parse a substitution. At this point, we have read the dollar sign
  11471. * and nothing else.
  11472. */
  11473. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11474. * (assuming ascii char codes, as the original implementation did) */
  11475. #define is_special(c) \
  11476. (((unsigned)(c) - 33 < 32) \
  11477. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11478. parsesub: {
  11479. unsigned char subtype;
  11480. int typeloc;
  11481. c = pgetc_eatbnl();
  11482. if ((checkkwd & CHKEOFMARK)
  11483. || c > 255 /* PEOA or PEOF */
  11484. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11485. ) {
  11486. #if BASH_DOLLAR_SQUOTE
  11487. if (synstack->syntax != DQSYNTAX && c == '\'')
  11488. bash_dollar_squote = 1;
  11489. else
  11490. #endif
  11491. USTPUTC('$', out);
  11492. pungetc();
  11493. } else if (c == '(') {
  11494. /* $(command) or $((arith)) */
  11495. if (pgetc_eatbnl() == '(') {
  11496. #if ENABLE_FEATURE_SH_MATH
  11497. PARSEARITH();
  11498. #else
  11499. raise_error_syntax("support for $((arith)) is disabled");
  11500. #endif
  11501. } else {
  11502. pungetc();
  11503. PARSEBACKQNEW();
  11504. }
  11505. } else {
  11506. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11507. smalluint newsyn = synstack->syntax;
  11508. USTPUTC(CTLVAR, out);
  11509. typeloc = out - (char *)stackblock();
  11510. STADJUST(1, out);
  11511. subtype = VSNORMAL;
  11512. if (c == '{') {
  11513. c = pgetc_eatbnl();
  11514. subtype = 0;
  11515. }
  11516. varname:
  11517. if (is_name(c)) {
  11518. /* $[{[#]]NAME[}] */
  11519. do {
  11520. STPUTC(c, out);
  11521. c = pgetc_eatbnl();
  11522. } while (is_in_name(c));
  11523. } else if (isdigit(c)) {
  11524. /* $[{[#]]NUM[}] */
  11525. do {
  11526. STPUTC(c, out);
  11527. c = pgetc_eatbnl();
  11528. } while ((subtype == 0 || subtype == VSLENGTH) && isdigit(c));
  11529. } else if (c != '}') {
  11530. /* $[{[#]]<specialchar>[}] */
  11531. int cc = c;
  11532. c = pgetc_eatbnl();
  11533. if (!subtype && cc == '#') {
  11534. subtype = VSLENGTH;
  11535. if (c == '_' || isalnum(c))
  11536. goto varname;
  11537. cc = c;
  11538. c = pgetc_eatbnl();
  11539. if (cc == '}' || c != '}') {
  11540. pungetc();
  11541. subtype = 0;
  11542. c = cc;
  11543. cc = '#';
  11544. }
  11545. }
  11546. if (!is_special(cc)) {
  11547. if (subtype == VSLENGTH)
  11548. subtype = 0;
  11549. goto badsub;
  11550. }
  11551. USTPUTC(cc, out);
  11552. } else
  11553. goto badsub;
  11554. if (subtype == 0) {
  11555. static const char types[] ALIGN1 = "}-+?=";
  11556. /* ${VAR...} but not $VAR or ${#VAR} */
  11557. /* c == first char after VAR */
  11558. int cc = c;
  11559. switch (c) {
  11560. case ':':
  11561. c = pgetc_eatbnl();
  11562. #if BASH_SUBSTR
  11563. /* This check is only needed to not misinterpret
  11564. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11565. * constructs.
  11566. */
  11567. if (!strchr(types, c)) {
  11568. subtype = VSSUBSTR;
  11569. pungetc();
  11570. break; /* "goto badsub" is bigger (!) */
  11571. }
  11572. #endif
  11573. subtype = VSNUL;
  11574. /*FALLTHROUGH*/
  11575. default: {
  11576. const char *p = strchr(types, c);
  11577. if (p == NULL)
  11578. break;
  11579. subtype |= p - types + VSNORMAL;
  11580. break;
  11581. }
  11582. case '%':
  11583. case '#':
  11584. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11585. c = pgetc_eatbnl();
  11586. if (c == cc)
  11587. subtype++;
  11588. else
  11589. pungetc();
  11590. newsyn = BASESYNTAX;
  11591. break;
  11592. #if BASH_PATTERN_SUBST
  11593. case '/':
  11594. /* ${v/[/]pattern/repl} */
  11595. //TODO: encode pattern and repl separately.
  11596. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11597. // are broken (should print "ONE")
  11598. subtype = VSREPLACE;
  11599. newsyn = BASESYNTAX;
  11600. c = pgetc_eatbnl();
  11601. if (c != '/')
  11602. goto badsub;
  11603. subtype++; /* VSREPLACEALL */
  11604. break;
  11605. #endif
  11606. }
  11607. } else {
  11608. if (subtype == VSLENGTH && c != '}')
  11609. subtype = 0;
  11610. badsub:
  11611. pungetc();
  11612. }
  11613. if (newsyn == ARISYNTAX)
  11614. newsyn = DQSYNTAX;
  11615. if ((newsyn != synstack->syntax || synstack->innerdq)
  11616. && subtype != VSNORMAL
  11617. ) {
  11618. synstack_push(&synstack,
  11619. synstack->prev ?: alloca(sizeof(*synstack)),
  11620. newsyn);
  11621. synstack->varpushed = 1;
  11622. synstack->dblquote = newsyn != BASESYNTAX;
  11623. }
  11624. ((unsigned char *)stackblock())[typeloc] = subtype;
  11625. if (subtype != VSNORMAL) {
  11626. synstack->varnest++;
  11627. if (synstack->dblquote)
  11628. synstack->dqvarnest++;
  11629. }
  11630. STPUTC('=', out);
  11631. }
  11632. goto parsesub_return;
  11633. }
  11634. /*
  11635. * Called to parse command substitutions. Newstyle is set if the command
  11636. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11637. * list of commands (passed by reference), and savelen is the number of
  11638. * characters on the top of the stack which must be preserved.
  11639. */
  11640. parsebackq: {
  11641. struct nodelist **nlpp;
  11642. union node *n;
  11643. char *str;
  11644. size_t savelen;
  11645. struct heredoc *saveheredoclist;
  11646. smallint saveprompt = 0;
  11647. str = NULL;
  11648. savelen = out - (char *)stackblock();
  11649. if (savelen > 0) {
  11650. /*
  11651. * FIXME: this can allocate very large block on stack and SEGV.
  11652. * Example:
  11653. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11654. * allocates 100kb for every command subst. With about
  11655. * a hundred command substitutions stack overflows.
  11656. * With larger prepended string, SEGV happens sooner.
  11657. */
  11658. str = alloca(savelen);
  11659. memcpy(str, stackblock(), savelen);
  11660. }
  11661. if (oldstyle) {
  11662. /* We must read until the closing backquote, giving special
  11663. * treatment to some slashes, and then push the string and
  11664. * reread it as input, interpreting it normally.
  11665. */
  11666. char *pout;
  11667. size_t psavelen;
  11668. char *pstr;
  11669. STARTSTACKSTR(pout);
  11670. for (;;) {
  11671. int pc;
  11672. setprompt_if(needprompt, 2);
  11673. pc = pgetc_eatbnl();
  11674. switch (pc) {
  11675. case '`':
  11676. goto done;
  11677. case '\\':
  11678. pc = pgetc(); /* not pgetc_eatbnl! */
  11679. if (pc != '\\' && pc != '`' && pc != '$'
  11680. && (!synstack->dblquote || pc != '"')
  11681. ) {
  11682. STPUTC('\\', pout);
  11683. }
  11684. if (pc <= 255 /* not PEOA or PEOF */) {
  11685. break;
  11686. }
  11687. /* fall through */
  11688. case PEOF:
  11689. IF_ASH_ALIAS(case PEOA:)
  11690. raise_error_syntax("EOF in backquote substitution");
  11691. case '\n':
  11692. nlnoprompt();
  11693. break;
  11694. default:
  11695. break;
  11696. }
  11697. STPUTC(pc, pout);
  11698. }
  11699. done:
  11700. STPUTC('\0', pout);
  11701. psavelen = pout - (char *)stackblock();
  11702. if (psavelen > 0) {
  11703. pstr = grabstackstr(pout);
  11704. setinputstring(pstr);
  11705. }
  11706. }
  11707. nlpp = &bqlist;
  11708. while (*nlpp)
  11709. nlpp = &(*nlpp)->next;
  11710. *nlpp = stzalloc(sizeof(**nlpp));
  11711. /* (*nlpp)->next = NULL; - stzalloc did it */
  11712. saveheredoclist = heredoclist;
  11713. heredoclist = NULL;
  11714. if (oldstyle) {
  11715. saveprompt = doprompt;
  11716. doprompt = 0;
  11717. }
  11718. n = list(2);
  11719. if (oldstyle)
  11720. doprompt = saveprompt;
  11721. else {
  11722. if (readtoken() != TRP)
  11723. raise_error_unexpected_syntax(TRP);
  11724. setinputstring(nullstr);
  11725. }
  11726. parseheredoc();
  11727. heredoclist = saveheredoclist;
  11728. (*nlpp)->n = n;
  11729. /* Start reading from old file again. */
  11730. popfile();
  11731. /* Ignore any pushed back tokens left from the backquote parsing. */
  11732. if (oldstyle)
  11733. tokpushback = 0;
  11734. out = growstackto(savelen + 1);
  11735. if (str) {
  11736. memcpy(out, str, savelen);
  11737. STADJUST(savelen, out);
  11738. }
  11739. USTPUTC(CTLBACKQ, out);
  11740. if (oldstyle)
  11741. goto parsebackq_oldreturn;
  11742. goto parsebackq_newreturn;
  11743. }
  11744. #if ENABLE_FEATURE_SH_MATH
  11745. /*
  11746. * Parse an arithmetic expansion (indicate start of one and set state)
  11747. */
  11748. parsearith: {
  11749. synstack_push(&synstack,
  11750. synstack->prev ?: alloca(sizeof(*synstack)),
  11751. ARISYNTAX);
  11752. synstack->dblquote = 1;
  11753. USTPUTC(CTLARI, out);
  11754. goto parsearith_return;
  11755. }
  11756. #endif
  11757. } /* end of readtoken */
  11758. /*
  11759. * Read the next input token.
  11760. * If the token is a word, we set backquotelist to the list of cmds in
  11761. * backquotes. We set quoteflag to true if any part of the word was
  11762. * quoted.
  11763. * If the token is TREDIR, then we set redirnode to a structure containing
  11764. * the redirection.
  11765. *
  11766. * [Change comment: here documents and internal procedures]
  11767. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11768. * word parsing code into a separate routine. In this case, readtoken
  11769. * doesn't need to have any internal procedures, but parseword does.
  11770. * We could also make parseoperator in essence the main routine, and
  11771. * have parseword (readtoken1?) handle both words and redirection.]
  11772. */
  11773. #define NEW_xxreadtoken
  11774. #ifdef NEW_xxreadtoken
  11775. /* singles must be first! */
  11776. static const char xxreadtoken_chars[7] ALIGN1 = {
  11777. '\n', '(', ')', /* singles */
  11778. '&', '|', ';', /* doubles */
  11779. 0
  11780. };
  11781. #define xxreadtoken_singles 3
  11782. #define xxreadtoken_doubles 3
  11783. static const char xxreadtoken_tokens[] ALIGN1 = {
  11784. TNL, TLP, TRP, /* only single occurrence allowed */
  11785. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11786. TEOF, /* corresponds to trailing nul */
  11787. TAND, TOR, TENDCASE /* if double occurrence */
  11788. };
  11789. static int
  11790. xxreadtoken(void)
  11791. {
  11792. int c;
  11793. if (tokpushback) {
  11794. tokpushback = 0;
  11795. return lasttoken;
  11796. }
  11797. setprompt_if(needprompt, 2);
  11798. for (;;) { /* until token or start of word found */
  11799. c = pgetc_eatbnl();
  11800. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11801. continue;
  11802. if (c == '#') {
  11803. while ((c = pgetc()) != '\n' && c != PEOF)
  11804. continue;
  11805. pungetc();
  11806. } else if (c == '\\') {
  11807. break; /* return readtoken1(...) */
  11808. } else {
  11809. const char *p;
  11810. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11811. if (c != PEOF) {
  11812. if (c == '\n') {
  11813. nlnoprompt();
  11814. }
  11815. p = strchr(xxreadtoken_chars, c);
  11816. if (p == NULL)
  11817. break; /* return readtoken1(...) */
  11818. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11819. int cc = pgetc_eatbnl();
  11820. if (cc == c) { /* double occurrence? */
  11821. p += xxreadtoken_doubles + 1;
  11822. } else {
  11823. pungetc();
  11824. #if BASH_REDIR_OUTPUT
  11825. if (c == '&' && cc == '>') /* &> */
  11826. break; /* return readtoken1(...) */
  11827. #endif
  11828. }
  11829. }
  11830. }
  11831. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11832. return lasttoken;
  11833. }
  11834. } /* for (;;) */
  11835. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11836. }
  11837. #else /* old xxreadtoken */
  11838. #define RETURN(token) return lasttoken = token
  11839. static int
  11840. xxreadtoken(void)
  11841. {
  11842. int c;
  11843. if (tokpushback) {
  11844. tokpushback = 0;
  11845. return lasttoken;
  11846. }
  11847. setprompt_if(needprompt, 2);
  11848. for (;;) { /* until token or start of word found */
  11849. c = pgetc_eatbnl();
  11850. switch (c) {
  11851. case ' ': case '\t':
  11852. IF_ASH_ALIAS(case PEOA:)
  11853. continue;
  11854. case '#':
  11855. while ((c = pgetc()) != '\n' && c != PEOF)
  11856. continue;
  11857. pungetc();
  11858. continue;
  11859. case '\n':
  11860. nlnoprompt();
  11861. RETURN(TNL);
  11862. case PEOF:
  11863. RETURN(TEOF);
  11864. case '&':
  11865. if (pgetc_eatbnl() == '&')
  11866. RETURN(TAND);
  11867. pungetc();
  11868. RETURN(TBACKGND);
  11869. case '|':
  11870. if (pgetc_eatbnl() == '|')
  11871. RETURN(TOR);
  11872. pungetc();
  11873. RETURN(TPIPE);
  11874. case ';':
  11875. if (pgetc_eatbnl() == ';')
  11876. RETURN(TENDCASE);
  11877. pungetc();
  11878. RETURN(TSEMI);
  11879. case '(':
  11880. RETURN(TLP);
  11881. case ')':
  11882. RETURN(TRP);
  11883. }
  11884. break;
  11885. }
  11886. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11887. #undef RETURN
  11888. }
  11889. #endif /* old xxreadtoken */
  11890. static int
  11891. readtoken(void)
  11892. {
  11893. int t;
  11894. int kwd = checkkwd;
  11895. #if DEBUG
  11896. smallint alreadyseen = tokpushback;
  11897. #endif
  11898. #if ENABLE_ASH_ALIAS
  11899. top:
  11900. #endif
  11901. t = xxreadtoken();
  11902. /*
  11903. * eat newlines
  11904. */
  11905. if (kwd & CHKNL) {
  11906. while (t == TNL) {
  11907. parseheredoc();
  11908. t = xxreadtoken();
  11909. }
  11910. }
  11911. if (t != TWORD || quoteflag) {
  11912. goto out;
  11913. }
  11914. /*
  11915. * check for keywords
  11916. */
  11917. if (kwd & CHKKWD) {
  11918. const char *const *pp;
  11919. pp = findkwd(wordtext);
  11920. if (pp) {
  11921. lasttoken = t = pp - tokname_array;
  11922. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11923. goto out;
  11924. }
  11925. }
  11926. if (checkkwd & CHKALIAS) {
  11927. #if ENABLE_ASH_ALIAS
  11928. struct alias *ap;
  11929. ap = lookupalias(wordtext, 1);
  11930. if (ap != NULL) {
  11931. if (*ap->val) {
  11932. pushstring(ap->val, ap);
  11933. }
  11934. goto top;
  11935. }
  11936. #endif
  11937. }
  11938. out:
  11939. checkkwd = 0;
  11940. #if DEBUG
  11941. if (!alreadyseen)
  11942. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11943. else
  11944. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11945. #endif
  11946. return t;
  11947. }
  11948. static int
  11949. peektoken(void)
  11950. {
  11951. int t;
  11952. t = readtoken();
  11953. tokpushback = 1;
  11954. return t;
  11955. }
  11956. /*
  11957. * Read and parse a command. Returns NODE_EOF on end of file.
  11958. * (NULL is a valid parse tree indicating a blank line.)
  11959. */
  11960. static union node *
  11961. parsecmd(int interact)
  11962. {
  11963. tokpushback = 0;
  11964. checkkwd = 0;
  11965. heredoclist = 0;
  11966. doprompt = interact;
  11967. setprompt_if(doprompt, doprompt);
  11968. needprompt = 0;
  11969. return list(1);
  11970. }
  11971. /*
  11972. * Input any here documents.
  11973. */
  11974. static void
  11975. parseheredoc(void)
  11976. {
  11977. struct heredoc *here;
  11978. union node *n;
  11979. here = heredoclist;
  11980. heredoclist = NULL;
  11981. while (here) {
  11982. tokpushback = 0;
  11983. setprompt_if(needprompt, 2);
  11984. if (here->here->type == NHERE)
  11985. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  11986. else
  11987. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  11988. n = stzalloc(sizeof(struct narg));
  11989. n->narg.type = NARG;
  11990. /*n->narg.next = NULL; - stzalloc did it */
  11991. n->narg.text = wordtext;
  11992. n->narg.backquote = backquotelist;
  11993. here->here->nhere.doc = n;
  11994. here = here->next;
  11995. }
  11996. }
  11997. static const char *
  11998. expandstr(const char *ps, int syntax_type)
  11999. {
  12000. union node n;
  12001. int saveprompt;
  12002. struct parsefile *file_stop = g_parsefile;
  12003. volatile int saveint;
  12004. struct jmploc *volatile savehandler = exception_handler;
  12005. struct jmploc jmploc;
  12006. const char *volatile result;
  12007. int err;
  12008. /* XXX Fix (char *) cast. */
  12009. setinputstring((char *)ps);
  12010. saveprompt = doprompt;
  12011. doprompt = 0;
  12012. result = ps;
  12013. SAVE_INT(saveint);
  12014. err = setjmp(jmploc.loc);
  12015. if (err)
  12016. goto out;
  12017. /* readtoken1() might die horribly.
  12018. * Try a prompt with syntactically wrong command:
  12019. * PS1='$(date "+%H:%M:%S) > '
  12020. */
  12021. exception_handler = &jmploc;
  12022. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  12023. n.narg.type = NARG;
  12024. n.narg.next = NULL;
  12025. n.narg.text = wordtext;
  12026. n.narg.backquote = backquotelist;
  12027. /* expandarg() might fail too:
  12028. * PS1='$((123+))'
  12029. */
  12030. expandarg(&n, NULL, EXP_QUOTED);
  12031. result = stackblock();
  12032. out:
  12033. exception_handler = savehandler;
  12034. if (err && exception_type != EXERROR)
  12035. longjmp(exception_handler->loc, 1);
  12036. RESTORE_INT(saveint);
  12037. doprompt = saveprompt;
  12038. /* Try: PS1='`xxx(`' */
  12039. unwindfiles(file_stop);
  12040. return result;
  12041. }
  12042. static inline int
  12043. parser_eof(void)
  12044. {
  12045. return tokpushback && lasttoken == TEOF;
  12046. }
  12047. /*
  12048. * Execute a command or commands contained in a string.
  12049. */
  12050. static int
  12051. evalstring(char *s, int flags)
  12052. {
  12053. struct jmploc *volatile savehandler;
  12054. struct jmploc jmploc;
  12055. int ex;
  12056. union node *n;
  12057. struct stackmark smark;
  12058. int status;
  12059. s = sstrdup(s);
  12060. setinputstring(s);
  12061. setstackmark(&smark);
  12062. status = 0;
  12063. /* On exception inside execution loop, we must popfile().
  12064. * Try interactively:
  12065. * readonly a=a
  12066. * command eval "a=b" # throws "is read only" error
  12067. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12068. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12069. */
  12070. savehandler = exception_handler;
  12071. ex = setjmp(jmploc.loc);
  12072. if (ex)
  12073. goto out;
  12074. exception_handler = &jmploc;
  12075. while ((n = parsecmd(0)) != NODE_EOF) {
  12076. int i;
  12077. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12078. if (n)
  12079. status = i;
  12080. popstackmark(&smark);
  12081. if (evalskip)
  12082. break;
  12083. }
  12084. out:
  12085. popstackmark(&smark);
  12086. popfile();
  12087. stunalloc(s);
  12088. exception_handler = savehandler;
  12089. if (ex)
  12090. longjmp(exception_handler->loc, ex);
  12091. return status;
  12092. }
  12093. /*
  12094. * The eval command.
  12095. */
  12096. static int FAST_FUNC
  12097. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12098. {
  12099. char *p;
  12100. char *concat;
  12101. if (argv[1]) {
  12102. p = argv[1];
  12103. argv += 2;
  12104. if (argv[0]) {
  12105. STARTSTACKSTR(concat);
  12106. for (;;) {
  12107. concat = stack_putstr(p, concat);
  12108. p = *argv++;
  12109. if (p == NULL)
  12110. break;
  12111. STPUTC(' ', concat);
  12112. }
  12113. STPUTC('\0', concat);
  12114. p = grabstackstr(concat);
  12115. }
  12116. return evalstring(p, flags & EV_TESTED);
  12117. }
  12118. return 0;
  12119. }
  12120. /*
  12121. * Read and execute commands.
  12122. * "Top" is nonzero for the top level command loop;
  12123. * it turns on prompting if the shell is interactive.
  12124. */
  12125. static int
  12126. cmdloop(int top)
  12127. {
  12128. union node *n;
  12129. struct stackmark smark;
  12130. int inter;
  12131. int status = 0;
  12132. int numeof = 0;
  12133. TRACE(("cmdloop(%d) called\n", top));
  12134. for (;;) {
  12135. int skip;
  12136. setstackmark(&smark);
  12137. #if JOBS
  12138. if (doing_jobctl)
  12139. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12140. #endif
  12141. inter = 0;
  12142. if (iflag && top) {
  12143. inter++;
  12144. chkmail();
  12145. }
  12146. n = parsecmd(inter);
  12147. #if DEBUG
  12148. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12149. showtree(n);
  12150. #endif
  12151. if (n == NODE_EOF) {
  12152. if (!top || numeof >= 50)
  12153. break;
  12154. if (!stoppedjobs()) {
  12155. if (!Iflag) {
  12156. if (iflag) {
  12157. newline_and_flush(stderr);
  12158. }
  12159. break;
  12160. }
  12161. out2str("\nUse \"exit\" to leave shell.\n");
  12162. }
  12163. numeof++;
  12164. } else if (nflag == 0) {
  12165. int i;
  12166. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12167. job_warning >>= 1;
  12168. numeof = 0;
  12169. i = evaltree(n, 0);
  12170. if (n)
  12171. status = i;
  12172. }
  12173. popstackmark(&smark);
  12174. skip = evalskip;
  12175. if (skip) {
  12176. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12177. break;
  12178. }
  12179. }
  12180. return status;
  12181. }
  12182. /*
  12183. * Take commands from a file. To be compatible we should do a path
  12184. * search for the file, which is necessary to find sub-commands.
  12185. */
  12186. static char *
  12187. find_dot_file(char *basename)
  12188. {
  12189. char *fullname;
  12190. const char *path = pathval();
  12191. struct stat statb;
  12192. int len;
  12193. /* don't try this for absolute or relative paths */
  12194. if (strchr(basename, '/'))
  12195. return basename;
  12196. while ((len = padvance(&path, basename)) >= 0) {
  12197. fullname = stackblock();
  12198. if ((!pathopt || *pathopt == 'f')
  12199. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12200. ) {
  12201. /* This will be freed by the caller. */
  12202. return stalloc(len);
  12203. }
  12204. }
  12205. /* not found in PATH */
  12206. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12207. return basename;
  12208. #else
  12209. ash_msg_and_raise_error("%s: not found", basename);
  12210. /* NOTREACHED */
  12211. #endif
  12212. }
  12213. static int FAST_FUNC
  12214. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12215. {
  12216. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12217. int status = 0;
  12218. char *fullname;
  12219. char **argv;
  12220. char *args_need_save;
  12221. volatile struct shparam saveparam;
  12222. //???
  12223. // struct strlist *sp;
  12224. // for (sp = cmdenviron; sp; sp = sp->next)
  12225. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12226. nextopt(nullstr); /* handle possible "--" */
  12227. argv = argptr;
  12228. if (!argv[0]) {
  12229. /* bash says: "bash: .: filename argument required" */
  12230. return 2; /* bash compat */
  12231. }
  12232. /* This aborts if file isn't found, which is POSIXly correct.
  12233. * bash returns exitcode 1 instead.
  12234. */
  12235. fullname = find_dot_file(argv[0]);
  12236. argv++;
  12237. args_need_save = argv[0];
  12238. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12239. int argc;
  12240. saveparam = shellparam;
  12241. shellparam.malloced = 0;
  12242. argc = 1;
  12243. while (argv[argc])
  12244. argc++;
  12245. shellparam.nparam = argc;
  12246. shellparam.p = argv;
  12247. };
  12248. /* This aborts if file can't be opened, which is POSIXly correct.
  12249. * bash returns exitcode 1 instead.
  12250. */
  12251. setinputfile(fullname, INPUT_PUSH_FILE);
  12252. commandname = fullname;
  12253. status = cmdloop(0);
  12254. popfile();
  12255. if (args_need_save) {
  12256. freeparam(&shellparam);
  12257. shellparam = saveparam;
  12258. };
  12259. return status;
  12260. }
  12261. static int FAST_FUNC
  12262. exitcmd(int argc UNUSED_PARAM, char **argv)
  12263. {
  12264. if (stoppedjobs())
  12265. return 0;
  12266. if (argv[1])
  12267. savestatus = number(argv[1]);
  12268. raise_exception(EXEXIT);
  12269. /* NOTREACHED */
  12270. }
  12271. /*
  12272. * Read a file containing shell functions.
  12273. */
  12274. static void
  12275. readcmdfile(char *name)
  12276. {
  12277. setinputfile(name, INPUT_PUSH_FILE);
  12278. cmdloop(0);
  12279. popfile();
  12280. }
  12281. /* ============ find_command inplementation */
  12282. /*
  12283. * Resolve a command name. If you change this routine, you may have to
  12284. * change the shellexec routine as well.
  12285. */
  12286. static void
  12287. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12288. {
  12289. struct tblentry *cmdp;
  12290. int idx;
  12291. int prev;
  12292. char *fullname;
  12293. struct stat statb;
  12294. int e;
  12295. int updatetbl;
  12296. struct builtincmd *bcmd;
  12297. int len;
  12298. /* If name contains a slash, don't use PATH or hash table */
  12299. if (strchr(name, '/') != NULL) {
  12300. entry->u.index = -1;
  12301. if (act & DO_ABS) {
  12302. while (stat(name, &statb) < 0) {
  12303. #ifdef SYSV
  12304. if (errno == EINTR)
  12305. continue;
  12306. #endif
  12307. entry->cmdtype = CMDUNKNOWN;
  12308. return;
  12309. }
  12310. }
  12311. entry->cmdtype = CMDNORMAL;
  12312. return;
  12313. }
  12314. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12315. updatetbl = (path == pathval());
  12316. if (!updatetbl)
  12317. act |= DO_ALTPATH;
  12318. /* If name is in the table, check answer will be ok */
  12319. cmdp = cmdlookup(name, 0);
  12320. if (cmdp != NULL) {
  12321. int bit;
  12322. switch (cmdp->cmdtype) {
  12323. default:
  12324. #if DEBUG
  12325. abort();
  12326. #endif
  12327. case CMDNORMAL:
  12328. bit = DO_ALTPATH | DO_REGBLTIN;
  12329. break;
  12330. case CMDFUNCTION:
  12331. bit = DO_NOFUNC;
  12332. break;
  12333. case CMDBUILTIN:
  12334. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12335. break;
  12336. }
  12337. if (act & bit) {
  12338. if (act & bit & DO_REGBLTIN)
  12339. goto fail;
  12340. updatetbl = 0;
  12341. cmdp = NULL;
  12342. } else if (cmdp->rehash == 0)
  12343. /* if not invalidated by cd, we're done */
  12344. goto success;
  12345. }
  12346. /* If %builtin not in path, check for builtin next */
  12347. bcmd = find_builtin(name);
  12348. if (bcmd) {
  12349. if (IS_BUILTIN_REGULAR(bcmd))
  12350. goto builtin_success;
  12351. if (act & DO_ALTPATH)
  12352. goto builtin_success;
  12353. if (builtinloc <= 0)
  12354. goto builtin_success;
  12355. }
  12356. if (act & DO_REGBLTIN)
  12357. goto fail;
  12358. #if ENABLE_FEATURE_SH_STANDALONE
  12359. {
  12360. int applet_no = find_applet_by_name(name);
  12361. if (applet_no >= 0) {
  12362. entry->cmdtype = CMDNORMAL;
  12363. entry->u.index = -2 - applet_no;
  12364. return;
  12365. }
  12366. }
  12367. #endif
  12368. /* We have to search path. */
  12369. prev = -1; /* where to start */
  12370. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12371. if (cmdp->cmdtype == CMDBUILTIN)
  12372. prev = builtinloc;
  12373. else
  12374. prev = cmdp->param.index;
  12375. }
  12376. e = ENOENT;
  12377. idx = -1;
  12378. loop:
  12379. while ((len = padvance(&path, name)) >= 0) {
  12380. const char *lpathopt = pathopt;
  12381. fullname = stackblock();
  12382. idx++;
  12383. if (lpathopt) {
  12384. if (*lpathopt == 'b') {
  12385. if (bcmd)
  12386. goto builtin_success;
  12387. continue;
  12388. } else if (!(act & DO_NOFUNC)) {
  12389. /* handled below */
  12390. } else {
  12391. /* ignore unimplemented options */
  12392. continue;
  12393. }
  12394. }
  12395. /* if rehash, don't redo absolute path names */
  12396. if (fullname[0] == '/' && idx <= prev) {
  12397. if (idx < prev)
  12398. continue;
  12399. TRACE(("searchexec \"%s\": no change\n", name));
  12400. goto success;
  12401. }
  12402. while (stat(fullname, &statb) < 0) {
  12403. #ifdef SYSV
  12404. if (errno == EINTR)
  12405. continue;
  12406. #endif
  12407. if (errno != ENOENT && errno != ENOTDIR)
  12408. e = errno;
  12409. goto loop;
  12410. }
  12411. e = EACCES; /* if we fail, this will be the error */
  12412. if (!S_ISREG(statb.st_mode))
  12413. continue;
  12414. if (lpathopt) { /* this is a %func directory */
  12415. stalloc(len);
  12416. /* NB: stalloc will return space pointed by fullname
  12417. * (because we don't have any intervening allocations
  12418. * between stunalloc above and this stalloc) */
  12419. readcmdfile(fullname);
  12420. cmdp = cmdlookup(name, 0);
  12421. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12422. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12423. stunalloc(fullname);
  12424. goto success;
  12425. }
  12426. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12427. if (!updatetbl) {
  12428. entry->cmdtype = CMDNORMAL;
  12429. entry->u.index = idx;
  12430. return;
  12431. }
  12432. INT_OFF;
  12433. cmdp = cmdlookup(name, 1);
  12434. cmdp->cmdtype = CMDNORMAL;
  12435. cmdp->param.index = idx;
  12436. INT_ON;
  12437. goto success;
  12438. }
  12439. /* We failed. If there was an entry for this command, delete it */
  12440. if (cmdp && updatetbl)
  12441. delete_cmd_entry();
  12442. if (act & DO_ERR) {
  12443. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12444. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12445. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12446. char *argv[3];
  12447. argv[0] = (char*) "command_not_found_handle";
  12448. argv[1] = name;
  12449. argv[2] = NULL;
  12450. evalfun(hookp->param.func, 2, argv, 0);
  12451. entry->cmdtype = CMDUNKNOWN;
  12452. return;
  12453. }
  12454. #endif
  12455. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12456. }
  12457. fail:
  12458. entry->cmdtype = CMDUNKNOWN;
  12459. return;
  12460. builtin_success:
  12461. if (!updatetbl) {
  12462. entry->cmdtype = CMDBUILTIN;
  12463. entry->u.cmd = bcmd;
  12464. return;
  12465. }
  12466. INT_OFF;
  12467. cmdp = cmdlookup(name, 1);
  12468. cmdp->cmdtype = CMDBUILTIN;
  12469. cmdp->param.cmd = bcmd;
  12470. INT_ON;
  12471. success:
  12472. cmdp->rehash = 0;
  12473. entry->cmdtype = cmdp->cmdtype;
  12474. entry->u = cmdp->param;
  12475. }
  12476. /*
  12477. * The trap builtin.
  12478. */
  12479. static int FAST_FUNC
  12480. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12481. {
  12482. char *action;
  12483. char **ap;
  12484. int signo, exitcode;
  12485. nextopt(nullstr);
  12486. ap = argptr;
  12487. if (!*ap) {
  12488. for (signo = 0; signo < NSIG; signo++) {
  12489. char *tr = trap_ptr[signo];
  12490. if (tr) {
  12491. /* note: bash adds "SIG", but only if invoked
  12492. * as "bash". If called as "sh", or if set -o posix,
  12493. * then it prints short signal names.
  12494. * We are printing short names: */
  12495. out1fmt("trap -- %s %s\n",
  12496. single_quote(tr),
  12497. get_signame(signo));
  12498. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12499. * In this case, we will exit very soon, no need to free(). */
  12500. /* if (trap_ptr != trap && tp[0]) */
  12501. /* free(tr); */
  12502. }
  12503. }
  12504. /*
  12505. if (trap_ptr != trap) {
  12506. free(trap_ptr);
  12507. trap_ptr = trap;
  12508. }
  12509. */
  12510. return 0;
  12511. }
  12512. /* Why the second check?
  12513. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12514. * In this case, NUM is signal no, not an action.
  12515. */
  12516. action = NULL;
  12517. if (ap[1] && !is_number(ap[0]))
  12518. action = *ap++;
  12519. exitcode = 0;
  12520. while (*ap) {
  12521. signo = get_signum(*ap);
  12522. if (signo < 0) {
  12523. /* Mimic bash message exactly */
  12524. ash_msg("%s: invalid signal specification", *ap);
  12525. exitcode = 1;
  12526. goto next;
  12527. }
  12528. INT_OFF;
  12529. if (action) {
  12530. if (LONE_DASH(action))
  12531. action = NULL;
  12532. else {
  12533. if (action[0]) /* not NULL and not "" and not "-" */
  12534. may_have_traps = 1;
  12535. action = ckstrdup(action);
  12536. }
  12537. }
  12538. free(trap[signo]);
  12539. trap[signo] = action;
  12540. if (signo != 0)
  12541. setsignal(signo);
  12542. INT_ON;
  12543. next:
  12544. ap++;
  12545. }
  12546. return exitcode;
  12547. }
  12548. /* ============ Builtins */
  12549. #if ENABLE_ASH_HELP
  12550. static int FAST_FUNC
  12551. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12552. {
  12553. unsigned col;
  12554. unsigned i;
  12555. out1fmt(
  12556. "Built-in commands:\n"
  12557. "------------------\n");
  12558. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12559. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12560. builtintab[i].name + 1);
  12561. if (col > 60) {
  12562. out1fmt("\n");
  12563. col = 0;
  12564. }
  12565. }
  12566. # if ENABLE_FEATURE_SH_STANDALONE
  12567. {
  12568. const char *a = applet_names;
  12569. while (*a) {
  12570. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12571. if (col > 60) {
  12572. out1fmt("\n");
  12573. col = 0;
  12574. }
  12575. while (*a++ != '\0')
  12576. continue;
  12577. }
  12578. }
  12579. # endif
  12580. newline_and_flush(stdout);
  12581. return EXIT_SUCCESS;
  12582. }
  12583. #endif
  12584. #if MAX_HISTORY
  12585. static int FAST_FUNC
  12586. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12587. {
  12588. show_history(line_input_state);
  12589. return EXIT_SUCCESS;
  12590. }
  12591. #endif
  12592. /*
  12593. * The export and readonly commands.
  12594. */
  12595. static int FAST_FUNC
  12596. exportcmd(int argc UNUSED_PARAM, char **argv)
  12597. {
  12598. struct var *vp;
  12599. char *name;
  12600. const char *p;
  12601. char **aptr;
  12602. char opt;
  12603. int flag;
  12604. int flag_off;
  12605. /* "readonly" in bash accepts, but ignores -n.
  12606. * We do the same: it saves a conditional in nextopt's param.
  12607. */
  12608. flag_off = 0;
  12609. while ((opt = nextopt("np")) != '\0') {
  12610. if (opt == 'n')
  12611. flag_off = VEXPORT;
  12612. }
  12613. flag = VEXPORT;
  12614. if (argv[0][0] == 'r') {
  12615. flag = VREADONLY;
  12616. flag_off = 0; /* readonly ignores -n */
  12617. }
  12618. flag_off = ~flag_off;
  12619. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12620. {
  12621. aptr = argptr;
  12622. name = *aptr;
  12623. if (name) {
  12624. do {
  12625. p = strchr(name, '=');
  12626. if (p != NULL) {
  12627. p++;
  12628. } else {
  12629. vp = *findvar(hashvar(name), name);
  12630. if (vp) {
  12631. vp->flags = ((vp->flags | flag) & flag_off);
  12632. continue;
  12633. }
  12634. }
  12635. setvar(name, p, (flag & flag_off));
  12636. } while ((name = *++aptr) != NULL);
  12637. return 0;
  12638. }
  12639. }
  12640. /* No arguments. Show the list of exported or readonly vars.
  12641. * -n is ignored.
  12642. */
  12643. showvars(argv[0], flag, 0);
  12644. return 0;
  12645. }
  12646. /*
  12647. * Delete a function if it exists.
  12648. */
  12649. static void
  12650. unsetfunc(const char *name)
  12651. {
  12652. struct tblentry *cmdp;
  12653. cmdp = cmdlookup(name, 0);
  12654. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12655. delete_cmd_entry();
  12656. }
  12657. /*
  12658. * The unset builtin command. We unset the function before we unset the
  12659. * variable to allow a function to be unset when there is a readonly variable
  12660. * with the same name.
  12661. */
  12662. static int FAST_FUNC
  12663. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12664. {
  12665. char **ap;
  12666. int i;
  12667. int flag = 0;
  12668. while ((i = nextopt("vf")) != 0) {
  12669. flag = i;
  12670. }
  12671. for (ap = argptr; *ap; ap++) {
  12672. if (flag != 'f') {
  12673. unsetvar(*ap);
  12674. continue;
  12675. }
  12676. if (flag != 'v')
  12677. unsetfunc(*ap);
  12678. }
  12679. return 0;
  12680. }
  12681. static const unsigned char timescmd_str[] ALIGN1 = {
  12682. ' ', offsetof(struct tms, tms_utime),
  12683. '\n', offsetof(struct tms, tms_stime),
  12684. ' ', offsetof(struct tms, tms_cutime),
  12685. '\n', offsetof(struct tms, tms_cstime),
  12686. 0
  12687. };
  12688. static int FAST_FUNC
  12689. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12690. {
  12691. unsigned clk_tck;
  12692. const unsigned char *p;
  12693. struct tms buf;
  12694. clk_tck = bb_clk_tck();
  12695. times(&buf);
  12696. p = timescmd_str;
  12697. do {
  12698. unsigned sec, frac;
  12699. unsigned long t;
  12700. t = *(clock_t *)(((char *) &buf) + p[1]);
  12701. sec = t / clk_tck;
  12702. frac = t % clk_tck;
  12703. out1fmt("%um%u.%03us%c",
  12704. sec / 60, sec % 60,
  12705. (frac * 1000) / clk_tck,
  12706. p[0]);
  12707. p += 2;
  12708. } while (*p);
  12709. return 0;
  12710. }
  12711. #if ENABLE_FEATURE_SH_MATH
  12712. /*
  12713. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12714. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12715. *
  12716. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12717. */
  12718. static int FAST_FUNC
  12719. letcmd(int argc UNUSED_PARAM, char **argv)
  12720. {
  12721. arith_t i;
  12722. argv++;
  12723. if (!*argv)
  12724. ash_msg_and_raise_error("expression expected");
  12725. do {
  12726. i = ash_arith(*argv);
  12727. } while (*++argv);
  12728. return !i;
  12729. }
  12730. #endif
  12731. /*
  12732. * The read builtin. Options:
  12733. * -r Do not interpret '\' specially
  12734. * -s Turn off echo (tty only)
  12735. * -n NCHARS Read NCHARS max
  12736. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12737. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12738. * -u FD Read from given FD instead of fd 0
  12739. * -d DELIM End on DELIM char, not newline
  12740. * This uses unbuffered input, which may be avoidable in some cases.
  12741. * TODO: bash also has:
  12742. * -a ARRAY Read into array[0],[1],etc
  12743. * -e Use line editing (tty only)
  12744. */
  12745. static int FAST_FUNC
  12746. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12747. {
  12748. struct builtin_read_params params;
  12749. const char *r;
  12750. int i;
  12751. memset(&params, 0, sizeof(params));
  12752. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12753. switch (i) {
  12754. case 'p':
  12755. params.opt_p = optionarg;
  12756. break;
  12757. case 'n':
  12758. params.opt_n = optionarg;
  12759. break;
  12760. case 's':
  12761. params.read_flags |= BUILTIN_READ_SILENT;
  12762. break;
  12763. case 't':
  12764. params.opt_t = optionarg;
  12765. break;
  12766. case 'r':
  12767. params.read_flags |= BUILTIN_READ_RAW;
  12768. break;
  12769. case 'u':
  12770. params.opt_u = optionarg;
  12771. break;
  12772. #if BASH_READ_D
  12773. case 'd':
  12774. params.opt_d = optionarg;
  12775. break;
  12776. #endif
  12777. default:
  12778. break;
  12779. }
  12780. }
  12781. params.argv = argptr;
  12782. params.setvar = setvar0;
  12783. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12784. /* "read -s" needs to save/restore termios, can't allow ^C
  12785. * to jump out of it.
  12786. */
  12787. again:
  12788. INT_OFF;
  12789. r = shell_builtin_read(&params);
  12790. INT_ON;
  12791. if ((uintptr_t)r == 1 && errno == EINTR) {
  12792. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12793. * Correct behavior is to not exit "read"
  12794. */
  12795. if (pending_sig == 0)
  12796. goto again;
  12797. }
  12798. if ((uintptr_t)r > 1)
  12799. ash_msg_and_raise_error(r);
  12800. return (uintptr_t)r;
  12801. }
  12802. static int FAST_FUNC
  12803. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12804. {
  12805. static const char permuser[3] ALIGN1 = "ogu";
  12806. mode_t mask;
  12807. int symbolic_mode = 0;
  12808. while (nextopt("S") != '\0') {
  12809. symbolic_mode = 1;
  12810. }
  12811. INT_OFF;
  12812. mask = umask(0);
  12813. umask(mask);
  12814. INT_ON;
  12815. if (*argptr == NULL) {
  12816. if (symbolic_mode) {
  12817. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12818. char *p = buf;
  12819. int i;
  12820. i = 2;
  12821. for (;;) {
  12822. *p++ = ',';
  12823. *p++ = permuser[i];
  12824. *p++ = '=';
  12825. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12826. if (!(mask & 0400)) *p++ = 'r';
  12827. if (!(mask & 0200)) *p++ = 'w';
  12828. if (!(mask & 0100)) *p++ = 'x';
  12829. mask <<= 3;
  12830. if (--i < 0)
  12831. break;
  12832. }
  12833. *p = '\0';
  12834. puts(buf + 1);
  12835. } else {
  12836. out1fmt("%04o\n", mask);
  12837. }
  12838. } else {
  12839. char *modestr = *argptr;
  12840. /* numeric umasks are taken as-is */
  12841. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12842. if (!isdigit(modestr[0]))
  12843. mask ^= 0777;
  12844. mask = bb_parse_mode(modestr, mask);
  12845. if ((unsigned)mask > 0777) {
  12846. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12847. }
  12848. if (!isdigit(modestr[0]))
  12849. mask ^= 0777;
  12850. umask(mask);
  12851. }
  12852. return 0;
  12853. }
  12854. static int FAST_FUNC
  12855. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12856. {
  12857. return shell_builtin_ulimit(argv);
  12858. }
  12859. /* ============ main() and helpers */
  12860. /*
  12861. * This routine is called when an error or an interrupt occurs in an
  12862. * interactive shell and control is returned to the main command loop
  12863. * but prior to exitshell.
  12864. */
  12865. static void
  12866. exitreset(void)
  12867. {
  12868. /* from eval.c: */
  12869. if (savestatus >= 0) {
  12870. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  12871. exitstatus = savestatus;
  12872. savestatus = -1;
  12873. }
  12874. evalskip = 0;
  12875. loopnest = 0;
  12876. /* from expand.c: */
  12877. ifsfree();
  12878. /* from redir.c: */
  12879. unwindredir(NULL);
  12880. }
  12881. /*
  12882. * This routine is called when an error or an interrupt occurs in an
  12883. * interactive shell and control is returned to the main command loop.
  12884. * (In dash, this function is auto-generated by build machinery).
  12885. */
  12886. static void
  12887. reset(void)
  12888. {
  12889. /* from input.c: */
  12890. g_parsefile->left_in_buffer = 0;
  12891. g_parsefile->left_in_line = 0; /* clear input buffer */
  12892. g_parsefile->unget = 0;
  12893. popallfiles();
  12894. /* from var.c: */
  12895. unwindlocalvars(NULL);
  12896. }
  12897. /*
  12898. * Called to exit the shell.
  12899. */
  12900. static void
  12901. exitshell(void)
  12902. {
  12903. struct jmploc loc;
  12904. char *p;
  12905. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12906. save_history(line_input_state); /* may be NULL */
  12907. #endif
  12908. savestatus = exitstatus;
  12909. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  12910. if (setjmp(loc.loc))
  12911. goto out;
  12912. exception_handler = &loc;
  12913. p = trap[0];
  12914. if (p) {
  12915. trap[0] = NULL;
  12916. evalskip = 0;
  12917. evalstring(p, 0);
  12918. evalskip = SKIPFUNCDEF;
  12919. /*free(p); - we'll exit soon */
  12920. }
  12921. out:
  12922. exitreset();
  12923. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12924. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12925. */
  12926. setjobctl(0);
  12927. flush_stdout_stderr();
  12928. _exit(exitstatus);
  12929. /* NOTREACHED */
  12930. }
  12931. /* Don't inline: conserve stack of caller from having our locals too */
  12932. static NOINLINE void
  12933. init(void)
  12934. {
  12935. /* we will never free this */
  12936. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12937. basepf.linno = 1;
  12938. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12939. setsignal(SIGCHLD);
  12940. {
  12941. char **envp;
  12942. const char *p;
  12943. initvar();
  12944. for (envp = environ; envp && *envp; envp++) {
  12945. /* Used to have
  12946. * p = endofname(*envp);
  12947. * if (p != *envp && *p == '=') {
  12948. * here to weed out badly-named variables, but this breaks
  12949. * scenarios where people do want them passed to children:
  12950. * import os
  12951. * os.environ["test-test"]="test"
  12952. * if os.fork() == 0:
  12953. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12954. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12955. */
  12956. if (strchr(*envp, '=')) {
  12957. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12958. }
  12959. }
  12960. setvareq((char*)defifsvar, VTEXTFIXED);
  12961. setvareq((char*)defoptindvar, VTEXTFIXED);
  12962. setvar0("PPID", utoa(getppid()));
  12963. #if BASH_SHLVL_VAR
  12964. p = lookupvar("SHLVL");
  12965. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12966. #endif
  12967. #if BASH_HOSTNAME_VAR
  12968. if (!lookupvar("HOSTNAME")) {
  12969. struct utsname uts;
  12970. uname(&uts);
  12971. setvar0("HOSTNAME", uts.nodename);
  12972. }
  12973. #endif
  12974. p = lookupvar("PWD");
  12975. if (p) {
  12976. struct stat st1, st2;
  12977. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12978. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12979. ) {
  12980. p = NULL;
  12981. }
  12982. }
  12983. setpwd(p, 0);
  12984. }
  12985. }
  12986. //usage:#define ash_trivial_usage
  12987. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12988. //usage:#define ash_full_usage "\n\n"
  12989. //usage: "Unix shell interpreter"
  12990. /*
  12991. * Process the shell command line arguments.
  12992. */
  12993. static int
  12994. procargs(char **argv)
  12995. {
  12996. int i;
  12997. const char *xminusc;
  12998. char **xargv;
  12999. int login_sh;
  13000. xargv = argv;
  13001. login_sh = xargv[0] && xargv[0][0] == '-';
  13002. #if NUM_SCRIPTS > 0
  13003. if (minusc)
  13004. goto setarg0;
  13005. #endif
  13006. arg0 = xargv[0];
  13007. /* if (xargv[0]) - mmm, this is always true! */
  13008. xargv++;
  13009. argptr = xargv;
  13010. for (i = 0; i < NOPTS; i++)
  13011. optlist[i] = 2;
  13012. if (options(&login_sh)) {
  13013. /* it already printed err message */
  13014. raise_exception(EXERROR);
  13015. }
  13016. xargv = argptr;
  13017. xminusc = minusc;
  13018. if (*xargv == NULL) {
  13019. if (xminusc)
  13020. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13021. sflag = 1;
  13022. }
  13023. if (iflag == 2 /* no explicit -i given */
  13024. && sflag == 1 /* -s given (or implied) */
  13025. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13026. && isatty(0) && isatty(1) /* we are on tty */
  13027. ) {
  13028. iflag = 1;
  13029. }
  13030. if (mflag == 2)
  13031. mflag = iflag;
  13032. for (i = 0; i < NOPTS; i++)
  13033. if (optlist[i] == 2)
  13034. optlist[i] = 0;
  13035. #if DEBUG == 2
  13036. debug = 1;
  13037. #endif
  13038. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13039. if (xminusc) {
  13040. minusc = *xargv++;
  13041. if (*xargv)
  13042. goto setarg0;
  13043. } else if (!sflag) {
  13044. setinputfile(*xargv, 0);
  13045. setarg0:
  13046. arg0 = *xargv++;
  13047. commandname = arg0;
  13048. }
  13049. shellparam.p = xargv;
  13050. #if ENABLE_ASH_GETOPTS
  13051. shellparam.optind = 1;
  13052. shellparam.optoff = -1;
  13053. #endif
  13054. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13055. while (*xargv) {
  13056. shellparam.nparam++;
  13057. xargv++;
  13058. }
  13059. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13060. * Try:
  13061. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13062. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13063. * NB: must do it before setting up signals (in optschanged())
  13064. * and reading .profile etc (after we return from here):
  13065. */
  13066. if (iflag)
  13067. signal(SIGHUP, SIG_DFL);
  13068. optschanged();
  13069. return login_sh;
  13070. }
  13071. /*
  13072. * Read /etc/profile, ~/.profile, $ENV.
  13073. */
  13074. static void
  13075. read_profile(const char *name)
  13076. {
  13077. name = expandstr(name, DQSYNTAX);
  13078. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13079. return;
  13080. cmdloop(0);
  13081. popfile();
  13082. }
  13083. #if PROFILE
  13084. static short profile_buf[16384];
  13085. extern int etext();
  13086. #endif
  13087. /*
  13088. * Main routine. We initialize things, parse the arguments, execute
  13089. * profiles if we're a login shell, and then call cmdloop to execute
  13090. * commands. The setjmp call sets up the location to jump to when an
  13091. * exception occurs. When an exception occurs the variable "state"
  13092. * is used to figure out how far we had gotten.
  13093. */
  13094. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13095. #if NUM_SCRIPTS > 0
  13096. int ash_main(int argc, char **argv)
  13097. #else
  13098. int ash_main(int argc UNUSED_PARAM, char **argv)
  13099. #endif
  13100. /* note: 'argc' is used only if embedded scripts are enabled */
  13101. {
  13102. volatile smallint state;
  13103. struct jmploc jmploc;
  13104. struct stackmark smark;
  13105. int login_sh;
  13106. /* Initialize global data */
  13107. INIT_G_misc();
  13108. INIT_G_memstack();
  13109. INIT_G_var();
  13110. #if ENABLE_ASH_ALIAS
  13111. INIT_G_alias();
  13112. #endif
  13113. INIT_G_cmdtable();
  13114. #if PROFILE
  13115. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13116. #endif
  13117. state = 0;
  13118. if (setjmp(jmploc.loc)) {
  13119. smallint e;
  13120. smallint s;
  13121. exitreset();
  13122. e = exception_type;
  13123. s = state;
  13124. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13125. exitshell();
  13126. }
  13127. reset();
  13128. if (e == EXINT) {
  13129. newline_and_flush(stderr);
  13130. }
  13131. popstackmark(&smark);
  13132. FORCE_INT_ON; /* enable interrupts */
  13133. if (s == 1)
  13134. goto state1;
  13135. if (s == 2)
  13136. goto state2;
  13137. if (s == 3)
  13138. goto state3;
  13139. goto state4;
  13140. }
  13141. exception_handler = &jmploc;
  13142. rootpid = getpid();
  13143. init();
  13144. setstackmark(&smark);
  13145. #if NUM_SCRIPTS > 0
  13146. if (argc < 0)
  13147. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13148. minusc = get_script_content(-argc - 1);
  13149. #endif
  13150. login_sh = procargs(argv);
  13151. #if DEBUG
  13152. TRACE(("Shell args: "));
  13153. trace_puts_args(argv);
  13154. #endif
  13155. if (login_sh) {
  13156. const char *hp;
  13157. state = 1;
  13158. read_profile("/etc/profile");
  13159. state1:
  13160. state = 2;
  13161. hp = lookupvar("HOME");
  13162. if (hp)
  13163. read_profile("$HOME/.profile");
  13164. }
  13165. state2:
  13166. state = 3;
  13167. if (
  13168. #ifndef linux
  13169. getuid() == geteuid() && getgid() == getegid() &&
  13170. #endif
  13171. iflag
  13172. ) {
  13173. const char *shinit = lookupvar("ENV");
  13174. if (shinit != NULL && *shinit != '\0')
  13175. read_profile(shinit);
  13176. }
  13177. popstackmark(&smark);
  13178. state3:
  13179. state = 4;
  13180. if (minusc) {
  13181. /* evalstring pushes parsefile stack.
  13182. * Ensure we don't falsely claim that 0 (stdin)
  13183. * is one of stacked source fds.
  13184. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13185. // if (!sflag) g_parsefile->pf_fd = -1;
  13186. // ^^ not necessary since now we special-case fd 0
  13187. // in save_fd_on_redirect()
  13188. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13189. // The above makes
  13190. // ash -sc 'echo $-'
  13191. // continue reading input from stdin after running 'echo'.
  13192. // bash does not do this: it prints "hBcs" and exits.
  13193. evalstring(minusc, EV_EXIT);
  13194. }
  13195. if (sflag || minusc == NULL) {
  13196. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13197. if (line_input_state) {
  13198. const char *hp = lookupvar("HISTFILE");
  13199. if (!hp) {
  13200. hp = lookupvar("HOME");
  13201. if (hp) {
  13202. INT_OFF;
  13203. hp = concat_path_file(hp, ".ash_history");
  13204. setvar0("HISTFILE", hp);
  13205. free((char*)hp);
  13206. INT_ON;
  13207. hp = lookupvar("HISTFILE");
  13208. }
  13209. }
  13210. if (hp)
  13211. line_input_state->hist_file = xstrdup(hp);
  13212. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13213. hp = lookupvar("HISTFILESIZE");
  13214. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13215. # endif
  13216. }
  13217. #endif
  13218. state4: /* XXX ??? - why isn't this before the "if" statement */
  13219. cmdloop(1);
  13220. }
  13221. #if PROFILE
  13222. monitor(0);
  13223. #endif
  13224. #ifdef GPROF
  13225. {
  13226. extern void _mcleanup(void);
  13227. _mcleanup();
  13228. }
  13229. #endif
  13230. TRACE(("End of main reached\n"));
  13231. exitshell();
  13232. /* NOTREACHED */
  13233. }
  13234. /*-
  13235. * Copyright (c) 1989, 1991, 1993, 1994
  13236. * The Regents of the University of California. All rights reserved.
  13237. *
  13238. * This code is derived from software contributed to Berkeley by
  13239. * Kenneth Almquist.
  13240. *
  13241. * Redistribution and use in source and binary forms, with or without
  13242. * modification, are permitted provided that the following conditions
  13243. * are met:
  13244. * 1. Redistributions of source code must retain the above copyright
  13245. * notice, this list of conditions and the following disclaimer.
  13246. * 2. Redistributions in binary form must reproduce the above copyright
  13247. * notice, this list of conditions and the following disclaimer in the
  13248. * documentation and/or other materials provided with the distribution.
  13249. * 3. Neither the name of the University nor the names of its contributors
  13250. * may be used to endorse or promote products derived from this software
  13251. * without specific prior written permission.
  13252. *
  13253. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13254. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13255. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13256. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13257. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13258. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13259. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13260. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13261. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13262. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13263. * SUCH DAMAGE.
  13264. */