ash.c 284 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189
  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 the GPL v2 or later, see the file LICENSE in this tarball.
  17. */
  18. /*
  19. * The following should be set to reflect the type of system you have:
  20. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  21. * define SYSV if you are running under System V.
  22. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  23. * define DEBUG=2 to compile in and turn on debugging.
  24. *
  25. * When debugging is on, debugging info will be written to ./trace and
  26. * a quit signal will generate a core dump.
  27. */
  28. #define DEBUG 0
  29. /* Tweak debug output verbosity here */
  30. #define DEBUG_TIME 0
  31. #define DEBUG_PID 1
  32. #define DEBUG_SIG 1
  33. #define PROFILE 0
  34. #define JOBS ENABLE_ASH_JOB_CONTROL
  35. #if DEBUG
  36. # ifndef _GNU_SOURCE
  37. # define _GNU_SOURCE
  38. # endif
  39. #endif
  40. #include "busybox.h" /* for applet_names */
  41. #include <paths.h>
  42. #include <setjmp.h>
  43. #include <fnmatch.h>
  44. #include "shell_common.h"
  45. #include "builtin_read.h"
  46. #include "math.h"
  47. #if ENABLE_ASH_RANDOM_SUPPORT
  48. # include "random.h"
  49. #else
  50. # define CLEAR_RANDOM_T(rnd) ((void)0)
  51. #endif
  52. #define SKIP_definitions 1
  53. #include "applet_tables.h"
  54. #undef SKIP_definitions
  55. #if NUM_APPLETS == 1
  56. /* STANDALONE does not make sense, and won't compile */
  57. # undef CONFIG_FEATURE_SH_STANDALONE
  58. # undef ENABLE_FEATURE_SH_STANDALONE
  59. # undef IF_FEATURE_SH_STANDALONE
  60. # undef IF_NOT_FEATURE_SH_STANDALONE
  61. # define ENABLE_FEATURE_SH_STANDALONE 0
  62. # define IF_FEATURE_SH_STANDALONE(...)
  63. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  64. #endif
  65. #ifndef PIPE_BUF
  66. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  67. #endif
  68. #if defined(__uClinux__)
  69. # error "Do not even bother, ash will not run on NOMMU machine"
  70. #endif
  71. /* ============ Hash table sizes. Configurable. */
  72. #define VTABSIZE 39
  73. #define ATABSIZE 39
  74. #define CMDTABLESIZE 31 /* should be prime */
  75. /* ============ Shell options */
  76. static const char *const optletters_optnames[] = {
  77. "e" "errexit",
  78. "f" "noglob",
  79. "I" "ignoreeof",
  80. "i" "interactive",
  81. "m" "monitor",
  82. "n" "noexec",
  83. "s" "stdin",
  84. "x" "xtrace",
  85. "v" "verbose",
  86. "C" "noclobber",
  87. "a" "allexport",
  88. "b" "notify",
  89. "u" "nounset",
  90. "\0" "vi"
  91. #if ENABLE_ASH_BASH_COMPAT
  92. ,"\0" "pipefail"
  93. #endif
  94. #if DEBUG
  95. ,"\0" "nolog"
  96. ,"\0" "debug"
  97. #endif
  98. };
  99. #define optletters(n) optletters_optnames[n][0]
  100. #define optnames(n) (optletters_optnames[n] + 1)
  101. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  102. /* ============ Misc data */
  103. static const char homestr[] ALIGN1 = "HOME";
  104. static const char snlfmt[] ALIGN1 = "%s\n";
  105. static const char msg_illnum[] ALIGN1 = "Illegal number: %s";
  106. /*
  107. * We enclose jmp_buf in a structure so that we can declare pointers to
  108. * jump locations. The global variable handler contains the location to
  109. * jump to when an exception occurs, and the global variable exception_type
  110. * contains a code identifying the exception. To implement nested
  111. * exception handlers, the user should save the value of handler on entry
  112. * to an inner scope, set handler to point to a jmploc structure for the
  113. * inner scope, and restore handler on exit from the scope.
  114. */
  115. struct jmploc {
  116. jmp_buf loc;
  117. };
  118. struct globals_misc {
  119. /* pid of main shell */
  120. int rootpid;
  121. /* shell level: 0 for the main shell, 1 for its children, and so on */
  122. int shlvl;
  123. #define rootshell (!shlvl)
  124. char *minusc; /* argument to -c option */
  125. char *curdir; // = nullstr; /* current working directory */
  126. char *physdir; // = nullstr; /* physical working directory */
  127. char *arg0; /* value of $0 */
  128. struct jmploc *exception_handler;
  129. volatile int suppress_int; /* counter */
  130. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  131. /* last pending signal */
  132. volatile /*sig_atomic_t*/ smallint pending_sig;
  133. smallint exception_type; /* kind of exception (0..5) */
  134. /* exceptions */
  135. #define EXINT 0 /* SIGINT received */
  136. #define EXERROR 1 /* a generic error */
  137. #define EXSHELLPROC 2 /* execute a shell procedure */
  138. #define EXEXEC 3 /* command execution failed */
  139. #define EXEXIT 4 /* exit the shell */
  140. #define EXSIG 5 /* trapped signal in wait(1) */
  141. smallint isloginsh;
  142. char nullstr[1]; /* zero length string */
  143. char optlist[NOPTS];
  144. #define eflag optlist[0]
  145. #define fflag optlist[1]
  146. #define Iflag optlist[2]
  147. #define iflag optlist[3]
  148. #define mflag optlist[4]
  149. #define nflag optlist[5]
  150. #define sflag optlist[6]
  151. #define xflag optlist[7]
  152. #define vflag optlist[8]
  153. #define Cflag optlist[9]
  154. #define aflag optlist[10]
  155. #define bflag optlist[11]
  156. #define uflag optlist[12]
  157. #define viflag optlist[13]
  158. #if ENABLE_ASH_BASH_COMPAT
  159. # define pipefail optlist[14]
  160. #else
  161. # define pipefail 0
  162. #endif
  163. #if DEBUG
  164. # define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
  165. # define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
  166. #endif
  167. /* trap handler commands */
  168. /*
  169. * Sigmode records the current value of the signal handlers for the various
  170. * modes. A value of zero means that the current handler is not known.
  171. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  172. */
  173. char sigmode[NSIG - 1];
  174. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  175. #define S_CATCH 2 /* signal is caught */
  176. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  177. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  178. /* indicates specified signal received */
  179. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  180. char *trap[NSIG];
  181. char **trap_ptr; /* used only by "trap hack" */
  182. /* Rarely referenced stuff */
  183. #if ENABLE_ASH_RANDOM_SUPPORT
  184. random_t random_gen;
  185. #endif
  186. pid_t backgndpid; /* pid of last background process */
  187. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  188. };
  189. extern struct globals_misc *const ash_ptr_to_globals_misc;
  190. #define G_misc (*ash_ptr_to_globals_misc)
  191. #define rootpid (G_misc.rootpid )
  192. #define shlvl (G_misc.shlvl )
  193. #define minusc (G_misc.minusc )
  194. #define curdir (G_misc.curdir )
  195. #define physdir (G_misc.physdir )
  196. #define arg0 (G_misc.arg0 )
  197. #define exception_handler (G_misc.exception_handler)
  198. #define exception_type (G_misc.exception_type )
  199. #define suppress_int (G_misc.suppress_int )
  200. #define pending_int (G_misc.pending_int )
  201. #define pending_sig (G_misc.pending_sig )
  202. #define isloginsh (G_misc.isloginsh )
  203. #define nullstr (G_misc.nullstr )
  204. #define optlist (G_misc.optlist )
  205. #define sigmode (G_misc.sigmode )
  206. #define gotsig (G_misc.gotsig )
  207. #define trap (G_misc.trap )
  208. #define trap_ptr (G_misc.trap_ptr )
  209. #define random_gen (G_misc.random_gen )
  210. #define backgndpid (G_misc.backgndpid )
  211. #define job_warning (G_misc.job_warning)
  212. #define INIT_G_misc() do { \
  213. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  214. barrier(); \
  215. curdir = nullstr; \
  216. physdir = nullstr; \
  217. trap_ptr = trap; \
  218. } while (0)
  219. /* ============ DEBUG */
  220. #if DEBUG
  221. static void trace_printf(const char *fmt, ...);
  222. static void trace_vprintf(const char *fmt, va_list va);
  223. # define TRACE(param) trace_printf param
  224. # define TRACEV(param) trace_vprintf param
  225. # define close(fd) do { \
  226. int dfd = (fd); \
  227. if (close(dfd) < 0) \
  228. bb_error_msg("bug on %d: closing %d(0x%x)", \
  229. __LINE__, dfd, dfd); \
  230. } while (0)
  231. #else
  232. # define TRACE(param)
  233. # define TRACEV(param)
  234. #endif
  235. /* ============ Utility functions */
  236. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  237. static int isdigit_str9(const char *str)
  238. {
  239. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  240. while (--maxlen && isdigit(*str))
  241. str++;
  242. return (*str == '\0');
  243. }
  244. /* ============ Interrupts / exceptions */
  245. /*
  246. * These macros allow the user to suspend the handling of interrupt signals
  247. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  248. * much more efficient and portable. (But hacking the kernel is so much
  249. * more fun than worrying about efficiency and portability. :-))
  250. */
  251. #define INT_OFF do { \
  252. suppress_int++; \
  253. xbarrier(); \
  254. } while (0)
  255. /*
  256. * Called to raise an exception. Since C doesn't include exceptions, we
  257. * just do a longjmp to the exception handler. The type of exception is
  258. * stored in the global variable "exception_type".
  259. */
  260. static void raise_exception(int) NORETURN;
  261. static void
  262. raise_exception(int e)
  263. {
  264. #if DEBUG
  265. if (exception_handler == NULL)
  266. abort();
  267. #endif
  268. INT_OFF;
  269. exception_type = e;
  270. longjmp(exception_handler->loc, 1);
  271. }
  272. #if DEBUG
  273. #define raise_exception(e) do { \
  274. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  275. raise_exception(e); \
  276. } while (0)
  277. #endif
  278. /*
  279. * Called from trap.c when a SIGINT is received. (If the user specifies
  280. * that SIGINT is to be trapped or ignored using the trap builtin, then
  281. * this routine is not called.) Suppressint is nonzero when interrupts
  282. * are held using the INT_OFF macro. (The test for iflag is just
  283. * defensive programming.)
  284. */
  285. static void raise_interrupt(void) NORETURN;
  286. static void
  287. raise_interrupt(void)
  288. {
  289. int ex_type;
  290. pending_int = 0;
  291. /* Signal is not automatically unmasked after it is raised,
  292. * do it ourself - unmask all signals */
  293. sigprocmask_allsigs(SIG_UNBLOCK);
  294. /* pending_sig = 0; - now done in onsig() */
  295. ex_type = EXSIG;
  296. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  297. if (!(rootshell && iflag)) {
  298. /* Kill ourself with SIGINT */
  299. signal(SIGINT, SIG_DFL);
  300. raise(SIGINT);
  301. }
  302. ex_type = EXINT;
  303. }
  304. raise_exception(ex_type);
  305. /* NOTREACHED */
  306. }
  307. #if DEBUG
  308. #define raise_interrupt() do { \
  309. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  310. raise_interrupt(); \
  311. } while (0)
  312. #endif
  313. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  314. int_on(void)
  315. {
  316. xbarrier();
  317. if (--suppress_int == 0 && pending_int) {
  318. raise_interrupt();
  319. }
  320. }
  321. #define INT_ON int_on()
  322. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  323. force_int_on(void)
  324. {
  325. xbarrier();
  326. suppress_int = 0;
  327. if (pending_int)
  328. raise_interrupt();
  329. }
  330. #define FORCE_INT_ON force_int_on()
  331. #define SAVE_INT(v) ((v) = suppress_int)
  332. #define RESTORE_INT(v) do { \
  333. xbarrier(); \
  334. suppress_int = (v); \
  335. if (suppress_int == 0 && pending_int) \
  336. raise_interrupt(); \
  337. } while (0)
  338. /* ============ Stdout/stderr output */
  339. static void
  340. outstr(const char *p, FILE *file)
  341. {
  342. INT_OFF;
  343. fputs(p, file);
  344. INT_ON;
  345. }
  346. static void
  347. flush_stdout_stderr(void)
  348. {
  349. INT_OFF;
  350. fflush_all();
  351. INT_ON;
  352. }
  353. static void
  354. outcslow(int c, FILE *dest)
  355. {
  356. INT_OFF;
  357. putc(c, dest);
  358. fflush(dest);
  359. INT_ON;
  360. }
  361. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  362. static int
  363. out1fmt(const char *fmt, ...)
  364. {
  365. va_list ap;
  366. int r;
  367. INT_OFF;
  368. va_start(ap, fmt);
  369. r = vprintf(fmt, ap);
  370. va_end(ap);
  371. INT_ON;
  372. return r;
  373. }
  374. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  375. static int
  376. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  377. {
  378. va_list ap;
  379. int ret;
  380. va_start(ap, fmt);
  381. INT_OFF;
  382. ret = vsnprintf(outbuf, length, fmt, ap);
  383. va_end(ap);
  384. INT_ON;
  385. return ret;
  386. }
  387. static void
  388. out1str(const char *p)
  389. {
  390. outstr(p, stdout);
  391. }
  392. static void
  393. out2str(const char *p)
  394. {
  395. outstr(p, stderr);
  396. flush_stdout_stderr();
  397. }
  398. /* ============ Parser structures */
  399. /* control characters in argument strings */
  400. #define CTL_FIRST CTLESC
  401. #define CTLESC ((unsigned char)'\201') /* escape next character */
  402. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  403. #define CTLENDVAR ((unsigned char)'\203')
  404. #define CTLBACKQ ((unsigned char)'\204')
  405. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  406. /* CTLBACKQ | CTLQUOTE == '\205' */
  407. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  408. #define CTLENDARI ((unsigned char)'\207')
  409. #define CTLQUOTEMARK ((unsigned char)'\210')
  410. #define CTL_LAST CTLQUOTEMARK
  411. /* variable substitution byte (follows CTLVAR) */
  412. #define VSTYPE 0x0f /* type of variable substitution */
  413. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  414. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  415. /* values of VSTYPE field */
  416. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  417. #define VSMINUS 0x2 /* ${var-text} */
  418. #define VSPLUS 0x3 /* ${var+text} */
  419. #define VSQUESTION 0x4 /* ${var?message} */
  420. #define VSASSIGN 0x5 /* ${var=text} */
  421. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  422. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  423. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  424. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  425. #define VSLENGTH 0xa /* ${#var} */
  426. #if ENABLE_ASH_BASH_COMPAT
  427. #define VSSUBSTR 0xc /* ${var:position:length} */
  428. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  429. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  430. #endif
  431. static const char dolatstr[] ALIGN1 = {
  432. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  433. };
  434. #define NCMD 0
  435. #define NPIPE 1
  436. #define NREDIR 2
  437. #define NBACKGND 3
  438. #define NSUBSHELL 4
  439. #define NAND 5
  440. #define NOR 6
  441. #define NSEMI 7
  442. #define NIF 8
  443. #define NWHILE 9
  444. #define NUNTIL 10
  445. #define NFOR 11
  446. #define NCASE 12
  447. #define NCLIST 13
  448. #define NDEFUN 14
  449. #define NARG 15
  450. #define NTO 16
  451. #if ENABLE_ASH_BASH_COMPAT
  452. #define NTO2 17
  453. #endif
  454. #define NCLOBBER 18
  455. #define NFROM 19
  456. #define NFROMTO 20
  457. #define NAPPEND 21
  458. #define NTOFD 22
  459. #define NFROMFD 23
  460. #define NHERE 24
  461. #define NXHERE 25
  462. #define NNOT 26
  463. #define N_NUMBER 27
  464. union node;
  465. struct ncmd {
  466. smallint type; /* Nxxxx */
  467. union node *assign;
  468. union node *args;
  469. union node *redirect;
  470. };
  471. struct npipe {
  472. smallint type;
  473. smallint pipe_backgnd;
  474. struct nodelist *cmdlist;
  475. };
  476. struct nredir {
  477. smallint type;
  478. union node *n;
  479. union node *redirect;
  480. };
  481. struct nbinary {
  482. smallint type;
  483. union node *ch1;
  484. union node *ch2;
  485. };
  486. struct nif {
  487. smallint type;
  488. union node *test;
  489. union node *ifpart;
  490. union node *elsepart;
  491. };
  492. struct nfor {
  493. smallint type;
  494. union node *args;
  495. union node *body;
  496. char *var;
  497. };
  498. struct ncase {
  499. smallint type;
  500. union node *expr;
  501. union node *cases;
  502. };
  503. struct nclist {
  504. smallint type;
  505. union node *next;
  506. union node *pattern;
  507. union node *body;
  508. };
  509. struct narg {
  510. smallint type;
  511. union node *next;
  512. char *text;
  513. struct nodelist *backquote;
  514. };
  515. /* nfile and ndup layout must match!
  516. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  517. * that it is actually NTO2 (>&file), and change its type.
  518. */
  519. struct nfile {
  520. smallint type;
  521. union node *next;
  522. int fd;
  523. int _unused_dupfd;
  524. union node *fname;
  525. char *expfname;
  526. };
  527. struct ndup {
  528. smallint type;
  529. union node *next;
  530. int fd;
  531. int dupfd;
  532. union node *vname;
  533. char *_unused_expfname;
  534. };
  535. struct nhere {
  536. smallint type;
  537. union node *next;
  538. int fd;
  539. union node *doc;
  540. };
  541. struct nnot {
  542. smallint type;
  543. union node *com;
  544. };
  545. union node {
  546. smallint type;
  547. struct ncmd ncmd;
  548. struct npipe npipe;
  549. struct nredir nredir;
  550. struct nbinary nbinary;
  551. struct nif nif;
  552. struct nfor nfor;
  553. struct ncase ncase;
  554. struct nclist nclist;
  555. struct narg narg;
  556. struct nfile nfile;
  557. struct ndup ndup;
  558. struct nhere nhere;
  559. struct nnot nnot;
  560. };
  561. /*
  562. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  563. * It must be distinct from NULL.
  564. */
  565. #define NODE_EOF ((union node *) -1L)
  566. struct nodelist {
  567. struct nodelist *next;
  568. union node *n;
  569. };
  570. struct funcnode {
  571. int count;
  572. union node n;
  573. };
  574. /*
  575. * Free a parse tree.
  576. */
  577. static void
  578. freefunc(struct funcnode *f)
  579. {
  580. if (f && --f->count < 0)
  581. free(f);
  582. }
  583. /* ============ Debugging output */
  584. #if DEBUG
  585. static FILE *tracefile;
  586. static void
  587. trace_printf(const char *fmt, ...)
  588. {
  589. va_list va;
  590. if (debug != 1)
  591. return;
  592. if (DEBUG_TIME)
  593. fprintf(tracefile, "%u ", (int) time(NULL));
  594. if (DEBUG_PID)
  595. fprintf(tracefile, "[%u] ", (int) getpid());
  596. if (DEBUG_SIG)
  597. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  598. va_start(va, fmt);
  599. vfprintf(tracefile, fmt, va);
  600. va_end(va);
  601. }
  602. static void
  603. trace_vprintf(const char *fmt, va_list va)
  604. {
  605. if (debug != 1)
  606. return;
  607. if (DEBUG_TIME)
  608. fprintf(tracefile, "%u ", (int) time(NULL));
  609. if (DEBUG_PID)
  610. fprintf(tracefile, "[%u] ", (int) getpid());
  611. if (DEBUG_SIG)
  612. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  613. vfprintf(tracefile, fmt, va);
  614. }
  615. static void
  616. trace_puts(const char *s)
  617. {
  618. if (debug != 1)
  619. return;
  620. fputs(s, tracefile);
  621. }
  622. static void
  623. trace_puts_quoted(char *s)
  624. {
  625. char *p;
  626. char c;
  627. if (debug != 1)
  628. return;
  629. putc('"', tracefile);
  630. for (p = s; *p; p++) {
  631. switch ((unsigned char)*p) {
  632. case '\n': c = 'n'; goto backslash;
  633. case '\t': c = 't'; goto backslash;
  634. case '\r': c = 'r'; goto backslash;
  635. case '\"': c = '\"'; goto backslash;
  636. case '\\': c = '\\'; goto backslash;
  637. case CTLESC: c = 'e'; goto backslash;
  638. case CTLVAR: c = 'v'; goto backslash;
  639. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  640. case CTLBACKQ: c = 'q'; goto backslash;
  641. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  642. backslash:
  643. putc('\\', tracefile);
  644. putc(c, tracefile);
  645. break;
  646. default:
  647. if (*p >= ' ' && *p <= '~')
  648. putc(*p, tracefile);
  649. else {
  650. putc('\\', tracefile);
  651. putc((*p >> 6) & 03, tracefile);
  652. putc((*p >> 3) & 07, tracefile);
  653. putc(*p & 07, tracefile);
  654. }
  655. break;
  656. }
  657. }
  658. putc('"', tracefile);
  659. }
  660. static void
  661. trace_puts_args(char **ap)
  662. {
  663. if (debug != 1)
  664. return;
  665. if (!*ap)
  666. return;
  667. while (1) {
  668. trace_puts_quoted(*ap);
  669. if (!*++ap) {
  670. putc('\n', tracefile);
  671. break;
  672. }
  673. putc(' ', tracefile);
  674. }
  675. }
  676. static void
  677. opentrace(void)
  678. {
  679. char s[100];
  680. #ifdef O_APPEND
  681. int flags;
  682. #endif
  683. if (debug != 1) {
  684. if (tracefile)
  685. fflush(tracefile);
  686. /* leave open because libedit might be using it */
  687. return;
  688. }
  689. strcpy(s, "./trace");
  690. if (tracefile) {
  691. if (!freopen(s, "a", tracefile)) {
  692. fprintf(stderr, "Can't re-open %s\n", s);
  693. debug = 0;
  694. return;
  695. }
  696. } else {
  697. tracefile = fopen(s, "a");
  698. if (tracefile == NULL) {
  699. fprintf(stderr, "Can't open %s\n", s);
  700. debug = 0;
  701. return;
  702. }
  703. }
  704. #ifdef O_APPEND
  705. flags = fcntl(fileno(tracefile), F_GETFL);
  706. if (flags >= 0)
  707. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  708. #endif
  709. setlinebuf(tracefile);
  710. fputs("\nTracing started.\n", tracefile);
  711. }
  712. static void
  713. indent(int amount, char *pfx, FILE *fp)
  714. {
  715. int i;
  716. for (i = 0; i < amount; i++) {
  717. if (pfx && i == amount - 1)
  718. fputs(pfx, fp);
  719. putc('\t', fp);
  720. }
  721. }
  722. /* little circular references here... */
  723. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  724. static void
  725. sharg(union node *arg, FILE *fp)
  726. {
  727. char *p;
  728. struct nodelist *bqlist;
  729. unsigned char subtype;
  730. if (arg->type != NARG) {
  731. out1fmt("<node type %d>\n", arg->type);
  732. abort();
  733. }
  734. bqlist = arg->narg.backquote;
  735. for (p = arg->narg.text; *p; p++) {
  736. switch ((unsigned char)*p) {
  737. case CTLESC:
  738. putc(*++p, fp);
  739. break;
  740. case CTLVAR:
  741. putc('$', fp);
  742. putc('{', fp);
  743. subtype = *++p;
  744. if (subtype == VSLENGTH)
  745. putc('#', fp);
  746. while (*p != '=')
  747. putc(*p++, fp);
  748. if (subtype & VSNUL)
  749. putc(':', fp);
  750. switch (subtype & VSTYPE) {
  751. case VSNORMAL:
  752. putc('}', fp);
  753. break;
  754. case VSMINUS:
  755. putc('-', fp);
  756. break;
  757. case VSPLUS:
  758. putc('+', fp);
  759. break;
  760. case VSQUESTION:
  761. putc('?', fp);
  762. break;
  763. case VSASSIGN:
  764. putc('=', fp);
  765. break;
  766. case VSTRIMLEFT:
  767. putc('#', fp);
  768. break;
  769. case VSTRIMLEFTMAX:
  770. putc('#', fp);
  771. putc('#', fp);
  772. break;
  773. case VSTRIMRIGHT:
  774. putc('%', fp);
  775. break;
  776. case VSTRIMRIGHTMAX:
  777. putc('%', fp);
  778. putc('%', fp);
  779. break;
  780. case VSLENGTH:
  781. break;
  782. default:
  783. out1fmt("<subtype %d>", subtype);
  784. }
  785. break;
  786. case CTLENDVAR:
  787. putc('}', fp);
  788. break;
  789. case CTLBACKQ:
  790. case CTLBACKQ|CTLQUOTE:
  791. putc('$', fp);
  792. putc('(', fp);
  793. shtree(bqlist->n, -1, NULL, fp);
  794. putc(')', fp);
  795. break;
  796. default:
  797. putc(*p, fp);
  798. break;
  799. }
  800. }
  801. }
  802. static void
  803. shcmd(union node *cmd, FILE *fp)
  804. {
  805. union node *np;
  806. int first;
  807. const char *s;
  808. int dftfd;
  809. first = 1;
  810. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  811. if (!first)
  812. putc(' ', fp);
  813. sharg(np, fp);
  814. first = 0;
  815. }
  816. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  817. if (!first)
  818. putc(' ', fp);
  819. dftfd = 0;
  820. switch (np->nfile.type) {
  821. case NTO: s = ">>"+1; dftfd = 1; break;
  822. case NCLOBBER: s = ">|"; dftfd = 1; break;
  823. case NAPPEND: s = ">>"; dftfd = 1; break;
  824. #if ENABLE_ASH_BASH_COMPAT
  825. case NTO2:
  826. #endif
  827. case NTOFD: s = ">&"; dftfd = 1; break;
  828. case NFROM: s = "<"; break;
  829. case NFROMFD: s = "<&"; break;
  830. case NFROMTO: s = "<>"; break;
  831. default: s = "*error*"; break;
  832. }
  833. if (np->nfile.fd != dftfd)
  834. fprintf(fp, "%d", np->nfile.fd);
  835. fputs(s, fp);
  836. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  837. fprintf(fp, "%d", np->ndup.dupfd);
  838. } else {
  839. sharg(np->nfile.fname, fp);
  840. }
  841. first = 0;
  842. }
  843. }
  844. static void
  845. shtree(union node *n, int ind, char *pfx, FILE *fp)
  846. {
  847. struct nodelist *lp;
  848. const char *s;
  849. if (n == NULL)
  850. return;
  851. indent(ind, pfx, fp);
  852. if (n == NODE_EOF) {
  853. fputs("<EOF>", fp);
  854. return;
  855. }
  856. switch (n->type) {
  857. case NSEMI:
  858. s = "; ";
  859. goto binop;
  860. case NAND:
  861. s = " && ";
  862. goto binop;
  863. case NOR:
  864. s = " || ";
  865. binop:
  866. shtree(n->nbinary.ch1, ind, NULL, fp);
  867. /* if (ind < 0) */
  868. fputs(s, fp);
  869. shtree(n->nbinary.ch2, ind, NULL, fp);
  870. break;
  871. case NCMD:
  872. shcmd(n, fp);
  873. if (ind >= 0)
  874. putc('\n', fp);
  875. break;
  876. case NPIPE:
  877. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  878. shtree(lp->n, 0, NULL, fp);
  879. if (lp->next)
  880. fputs(" | ", fp);
  881. }
  882. if (n->npipe.pipe_backgnd)
  883. fputs(" &", fp);
  884. if (ind >= 0)
  885. putc('\n', fp);
  886. break;
  887. default:
  888. fprintf(fp, "<node type %d>", n->type);
  889. if (ind >= 0)
  890. putc('\n', fp);
  891. break;
  892. }
  893. }
  894. static void
  895. showtree(union node *n)
  896. {
  897. trace_puts("showtree called\n");
  898. shtree(n, 1, NULL, stderr);
  899. }
  900. #endif /* DEBUG */
  901. /* ============ Parser data */
  902. /*
  903. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  904. */
  905. struct strlist {
  906. struct strlist *next;
  907. char *text;
  908. };
  909. struct alias;
  910. struct strpush {
  911. struct strpush *prev; /* preceding string on stack */
  912. char *prev_string;
  913. int prev_left_in_line;
  914. #if ENABLE_ASH_ALIAS
  915. struct alias *ap; /* if push was associated with an alias */
  916. #endif
  917. char *string; /* remember the string since it may change */
  918. };
  919. struct parsefile {
  920. struct parsefile *prev; /* preceding file on stack */
  921. int linno; /* current line */
  922. int fd; /* file descriptor (or -1 if string) */
  923. int left_in_line; /* number of chars left in this line */
  924. int left_in_buffer; /* number of chars left in this buffer past the line */
  925. char *next_to_pgetc; /* next char in buffer */
  926. char *buf; /* input buffer */
  927. struct strpush *strpush; /* for pushing strings at this level */
  928. struct strpush basestrpush; /* so pushing one is fast */
  929. };
  930. static struct parsefile basepf; /* top level input file */
  931. static struct parsefile *g_parsefile = &basepf; /* current input file */
  932. static int startlinno; /* line # where last token started */
  933. static char *commandname; /* currently executing command */
  934. static struct strlist *cmdenviron; /* environment for builtin command */
  935. static uint8_t exitstatus; /* exit status of last command */
  936. /* ============ Message printing */
  937. static void
  938. ash_vmsg(const char *msg, va_list ap)
  939. {
  940. fprintf(stderr, "%s: ", arg0);
  941. if (commandname) {
  942. if (strcmp(arg0, commandname))
  943. fprintf(stderr, "%s: ", commandname);
  944. if (!iflag || g_parsefile->fd)
  945. fprintf(stderr, "line %d: ", startlinno);
  946. }
  947. vfprintf(stderr, msg, ap);
  948. outcslow('\n', stderr);
  949. }
  950. /*
  951. * Exverror is called to raise the error exception. If the second argument
  952. * is not NULL then error prints an error message using printf style
  953. * formatting. It then raises the error exception.
  954. */
  955. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  956. static void
  957. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  958. {
  959. #if DEBUG
  960. if (msg) {
  961. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  962. TRACEV((msg, ap));
  963. TRACE(("\") pid=%d\n", getpid()));
  964. } else
  965. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  966. if (msg)
  967. #endif
  968. ash_vmsg(msg, ap);
  969. flush_stdout_stderr();
  970. raise_exception(cond);
  971. /* NOTREACHED */
  972. }
  973. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  974. static void
  975. ash_msg_and_raise_error(const char *msg, ...)
  976. {
  977. va_list ap;
  978. va_start(ap, msg);
  979. ash_vmsg_and_raise(EXERROR, msg, ap);
  980. /* NOTREACHED */
  981. va_end(ap);
  982. }
  983. static void raise_error_syntax(const char *) NORETURN;
  984. static void
  985. raise_error_syntax(const char *msg)
  986. {
  987. ash_msg_and_raise_error("syntax error: %s", msg);
  988. /* NOTREACHED */
  989. }
  990. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  991. static void
  992. ash_msg_and_raise(int cond, const char *msg, ...)
  993. {
  994. va_list ap;
  995. va_start(ap, msg);
  996. ash_vmsg_and_raise(cond, msg, ap);
  997. /* NOTREACHED */
  998. va_end(ap);
  999. }
  1000. /*
  1001. * error/warning routines for external builtins
  1002. */
  1003. static void
  1004. ash_msg(const char *fmt, ...)
  1005. {
  1006. va_list ap;
  1007. va_start(ap, fmt);
  1008. ash_vmsg(fmt, ap);
  1009. va_end(ap);
  1010. }
  1011. /*
  1012. * Return a string describing an error. The returned string may be a
  1013. * pointer to a static buffer that will be overwritten on the next call.
  1014. * Action describes the operation that got the error.
  1015. */
  1016. static const char *
  1017. errmsg(int e, const char *em)
  1018. {
  1019. if (e == ENOENT || e == ENOTDIR) {
  1020. return em;
  1021. }
  1022. return strerror(e);
  1023. }
  1024. /* ============ Memory allocation */
  1025. #if 0
  1026. /* I consider these wrappers nearly useless:
  1027. * ok, they return you to nearest exception handler, but
  1028. * how much memory do you leak in the process, making
  1029. * memory starvation worse?
  1030. */
  1031. static void *
  1032. ckrealloc(void * p, size_t nbytes)
  1033. {
  1034. p = realloc(p, nbytes);
  1035. if (!p)
  1036. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1037. return p;
  1038. }
  1039. static void *
  1040. ckmalloc(size_t nbytes)
  1041. {
  1042. return ckrealloc(NULL, nbytes);
  1043. }
  1044. static void *
  1045. ckzalloc(size_t nbytes)
  1046. {
  1047. return memset(ckmalloc(nbytes), 0, nbytes);
  1048. }
  1049. static char *
  1050. ckstrdup(const char *s)
  1051. {
  1052. char *p = strdup(s);
  1053. if (!p)
  1054. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1055. return p;
  1056. }
  1057. #else
  1058. /* Using bbox equivalents. They exit if out of memory */
  1059. # define ckrealloc xrealloc
  1060. # define ckmalloc xmalloc
  1061. # define ckzalloc xzalloc
  1062. # define ckstrdup xstrdup
  1063. #endif
  1064. /*
  1065. * It appears that grabstackstr() will barf with such alignments
  1066. * because stalloc() will return a string allocated in a new stackblock.
  1067. */
  1068. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1069. enum {
  1070. /* Most machines require the value returned from malloc to be aligned
  1071. * in some way. The following macro will get this right
  1072. * on many machines. */
  1073. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1074. /* Minimum size of a block */
  1075. MINSIZE = SHELL_ALIGN(504),
  1076. };
  1077. struct stack_block {
  1078. struct stack_block *prev;
  1079. char space[MINSIZE];
  1080. };
  1081. struct stackmark {
  1082. struct stack_block *stackp;
  1083. char *stacknxt;
  1084. size_t stacknleft;
  1085. struct stackmark *marknext;
  1086. };
  1087. struct globals_memstack {
  1088. struct stack_block *g_stackp; // = &stackbase;
  1089. struct stackmark *markp;
  1090. char *g_stacknxt; // = stackbase.space;
  1091. char *sstrend; // = stackbase.space + MINSIZE;
  1092. size_t g_stacknleft; // = MINSIZE;
  1093. int herefd; // = -1;
  1094. struct stack_block stackbase;
  1095. };
  1096. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1097. #define G_memstack (*ash_ptr_to_globals_memstack)
  1098. #define g_stackp (G_memstack.g_stackp )
  1099. #define markp (G_memstack.markp )
  1100. #define g_stacknxt (G_memstack.g_stacknxt )
  1101. #define sstrend (G_memstack.sstrend )
  1102. #define g_stacknleft (G_memstack.g_stacknleft)
  1103. #define herefd (G_memstack.herefd )
  1104. #define stackbase (G_memstack.stackbase )
  1105. #define INIT_G_memstack() do { \
  1106. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1107. barrier(); \
  1108. g_stackp = &stackbase; \
  1109. g_stacknxt = stackbase.space; \
  1110. g_stacknleft = MINSIZE; \
  1111. sstrend = stackbase.space + MINSIZE; \
  1112. herefd = -1; \
  1113. } while (0)
  1114. #define stackblock() ((void *)g_stacknxt)
  1115. #define stackblocksize() g_stacknleft
  1116. /*
  1117. * Parse trees for commands are allocated in lifo order, so we use a stack
  1118. * to make this more efficient, and also to avoid all sorts of exception
  1119. * handling code to handle interrupts in the middle of a parse.
  1120. *
  1121. * The size 504 was chosen because the Ultrix malloc handles that size
  1122. * well.
  1123. */
  1124. static void *
  1125. stalloc(size_t nbytes)
  1126. {
  1127. char *p;
  1128. size_t aligned;
  1129. aligned = SHELL_ALIGN(nbytes);
  1130. if (aligned > g_stacknleft) {
  1131. size_t len;
  1132. size_t blocksize;
  1133. struct stack_block *sp;
  1134. blocksize = aligned;
  1135. if (blocksize < MINSIZE)
  1136. blocksize = MINSIZE;
  1137. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1138. if (len < blocksize)
  1139. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1140. INT_OFF;
  1141. sp = ckmalloc(len);
  1142. sp->prev = g_stackp;
  1143. g_stacknxt = sp->space;
  1144. g_stacknleft = blocksize;
  1145. sstrend = g_stacknxt + blocksize;
  1146. g_stackp = sp;
  1147. INT_ON;
  1148. }
  1149. p = g_stacknxt;
  1150. g_stacknxt += aligned;
  1151. g_stacknleft -= aligned;
  1152. return p;
  1153. }
  1154. static void *
  1155. stzalloc(size_t nbytes)
  1156. {
  1157. return memset(stalloc(nbytes), 0, nbytes);
  1158. }
  1159. static void
  1160. stunalloc(void *p)
  1161. {
  1162. #if DEBUG
  1163. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1164. write(STDERR_FILENO, "stunalloc\n", 10);
  1165. abort();
  1166. }
  1167. #endif
  1168. g_stacknleft += g_stacknxt - (char *)p;
  1169. g_stacknxt = p;
  1170. }
  1171. /*
  1172. * Like strdup but works with the ash stack.
  1173. */
  1174. static char *
  1175. ststrdup(const char *p)
  1176. {
  1177. size_t len = strlen(p) + 1;
  1178. return memcpy(stalloc(len), p, len);
  1179. }
  1180. static void
  1181. setstackmark(struct stackmark *mark)
  1182. {
  1183. mark->stackp = g_stackp;
  1184. mark->stacknxt = g_stacknxt;
  1185. mark->stacknleft = g_stacknleft;
  1186. mark->marknext = markp;
  1187. markp = mark;
  1188. }
  1189. static void
  1190. popstackmark(struct stackmark *mark)
  1191. {
  1192. struct stack_block *sp;
  1193. if (!mark->stackp)
  1194. return;
  1195. INT_OFF;
  1196. markp = mark->marknext;
  1197. while (g_stackp != mark->stackp) {
  1198. sp = g_stackp;
  1199. g_stackp = sp->prev;
  1200. free(sp);
  1201. }
  1202. g_stacknxt = mark->stacknxt;
  1203. g_stacknleft = mark->stacknleft;
  1204. sstrend = mark->stacknxt + mark->stacknleft;
  1205. INT_ON;
  1206. }
  1207. /*
  1208. * When the parser reads in a string, it wants to stick the string on the
  1209. * stack and only adjust the stack pointer when it knows how big the
  1210. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1211. * of space on top of the stack and stackblocklen returns the length of
  1212. * this block. Growstackblock will grow this space by at least one byte,
  1213. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1214. * part of the block that has been used.
  1215. */
  1216. static void
  1217. growstackblock(void)
  1218. {
  1219. size_t newlen;
  1220. newlen = g_stacknleft * 2;
  1221. if (newlen < g_stacknleft)
  1222. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1223. if (newlen < 128)
  1224. newlen += 128;
  1225. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1226. struct stack_block *oldstackp;
  1227. struct stackmark *xmark;
  1228. struct stack_block *sp;
  1229. struct stack_block *prevstackp;
  1230. size_t grosslen;
  1231. INT_OFF;
  1232. oldstackp = g_stackp;
  1233. sp = g_stackp;
  1234. prevstackp = sp->prev;
  1235. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1236. sp = ckrealloc(sp, grosslen);
  1237. sp->prev = prevstackp;
  1238. g_stackp = sp;
  1239. g_stacknxt = sp->space;
  1240. g_stacknleft = newlen;
  1241. sstrend = sp->space + newlen;
  1242. /*
  1243. * Stack marks pointing to the start of the old block
  1244. * must be relocated to point to the new block
  1245. */
  1246. xmark = markp;
  1247. while (xmark != NULL && xmark->stackp == oldstackp) {
  1248. xmark->stackp = g_stackp;
  1249. xmark->stacknxt = g_stacknxt;
  1250. xmark->stacknleft = g_stacknleft;
  1251. xmark = xmark->marknext;
  1252. }
  1253. INT_ON;
  1254. } else {
  1255. char *oldspace = g_stacknxt;
  1256. size_t oldlen = g_stacknleft;
  1257. char *p = stalloc(newlen);
  1258. /* free the space we just allocated */
  1259. g_stacknxt = memcpy(p, oldspace, oldlen);
  1260. g_stacknleft += newlen;
  1261. }
  1262. }
  1263. static void
  1264. grabstackblock(size_t len)
  1265. {
  1266. len = SHELL_ALIGN(len);
  1267. g_stacknxt += len;
  1268. g_stacknleft -= len;
  1269. }
  1270. /*
  1271. * The following routines are somewhat easier to use than the above.
  1272. * The user declares a variable of type STACKSTR, which may be declared
  1273. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1274. * the user uses the macro STPUTC to add characters to the string. In
  1275. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1276. * grown as necessary. When the user is done, she can just leave the
  1277. * string there and refer to it using stackblock(). Or she can allocate
  1278. * the space for it using grabstackstr(). If it is necessary to allow
  1279. * someone else to use the stack temporarily and then continue to grow
  1280. * the string, the user should use grabstack to allocate the space, and
  1281. * then call ungrabstr(p) to return to the previous mode of operation.
  1282. *
  1283. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1284. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1285. * is space for at least one character.
  1286. */
  1287. static void *
  1288. growstackstr(void)
  1289. {
  1290. size_t len = stackblocksize();
  1291. if (herefd >= 0 && len >= 1024) {
  1292. full_write(herefd, stackblock(), len);
  1293. return stackblock();
  1294. }
  1295. growstackblock();
  1296. return (char *)stackblock() + len;
  1297. }
  1298. /*
  1299. * Called from CHECKSTRSPACE.
  1300. */
  1301. static char *
  1302. makestrspace(size_t newlen, char *p)
  1303. {
  1304. size_t len = p - g_stacknxt;
  1305. size_t size = stackblocksize();
  1306. for (;;) {
  1307. size_t nleft;
  1308. size = stackblocksize();
  1309. nleft = size - len;
  1310. if (nleft >= newlen)
  1311. break;
  1312. growstackblock();
  1313. }
  1314. return (char *)stackblock() + len;
  1315. }
  1316. static char *
  1317. stack_nputstr(const char *s, size_t n, char *p)
  1318. {
  1319. p = makestrspace(n, p);
  1320. p = (char *)memcpy(p, s, n) + n;
  1321. return p;
  1322. }
  1323. static char *
  1324. stack_putstr(const char *s, char *p)
  1325. {
  1326. return stack_nputstr(s, strlen(s), p);
  1327. }
  1328. static char *
  1329. _STPUTC(int c, char *p)
  1330. {
  1331. if (p == sstrend)
  1332. p = growstackstr();
  1333. *p++ = c;
  1334. return p;
  1335. }
  1336. #define STARTSTACKSTR(p) ((p) = stackblock())
  1337. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1338. #define CHECKSTRSPACE(n, p) do { \
  1339. char *q = (p); \
  1340. size_t l = (n); \
  1341. size_t m = sstrend - q; \
  1342. if (l > m) \
  1343. (p) = makestrspace(l, q); \
  1344. } while (0)
  1345. #define USTPUTC(c, p) (*(p)++ = (c))
  1346. #define STACKSTRNUL(p) do { \
  1347. if ((p) == sstrend) \
  1348. (p) = growstackstr(); \
  1349. *(p) = '\0'; \
  1350. } while (0)
  1351. #define STUNPUTC(p) (--(p))
  1352. #define STTOPC(p) ((p)[-1])
  1353. #define STADJUST(amount, p) ((p) += (amount))
  1354. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1355. #define ungrabstackstr(s, p) stunalloc(s)
  1356. #define stackstrend() ((void *)sstrend)
  1357. /* ============ String helpers */
  1358. /*
  1359. * prefix -- see if pfx is a prefix of string.
  1360. */
  1361. static char *
  1362. prefix(const char *string, const char *pfx)
  1363. {
  1364. while (*pfx) {
  1365. if (*pfx++ != *string++)
  1366. return NULL;
  1367. }
  1368. return (char *) string;
  1369. }
  1370. /*
  1371. * Check for a valid number. This should be elsewhere.
  1372. */
  1373. static int
  1374. is_number(const char *p)
  1375. {
  1376. do {
  1377. if (!isdigit(*p))
  1378. return 0;
  1379. } while (*++p != '\0');
  1380. return 1;
  1381. }
  1382. /*
  1383. * Convert a string of digits to an integer, printing an error message on
  1384. * failure.
  1385. */
  1386. static int
  1387. number(const char *s)
  1388. {
  1389. if (!is_number(s))
  1390. ash_msg_and_raise_error(msg_illnum, s);
  1391. return atoi(s);
  1392. }
  1393. /*
  1394. * Produce a possibly single quoted string suitable as input to the shell.
  1395. * The return string is allocated on the stack.
  1396. */
  1397. static char *
  1398. single_quote(const char *s)
  1399. {
  1400. char *p;
  1401. STARTSTACKSTR(p);
  1402. do {
  1403. char *q;
  1404. size_t len;
  1405. len = strchrnul(s, '\'') - s;
  1406. q = p = makestrspace(len + 3, p);
  1407. *q++ = '\'';
  1408. q = (char *)memcpy(q, s, len) + len;
  1409. *q++ = '\'';
  1410. s += len;
  1411. STADJUST(q - p, p);
  1412. if (*s != '\'')
  1413. break;
  1414. len = 0;
  1415. do len++; while (*++s == '\'');
  1416. q = p = makestrspace(len + 3, p);
  1417. *q++ = '"';
  1418. q = (char *)memcpy(q, s - len, len) + len;
  1419. *q++ = '"';
  1420. STADJUST(q - p, p);
  1421. } while (*s);
  1422. USTPUTC('\0', p);
  1423. return stackblock();
  1424. }
  1425. /* ============ nextopt */
  1426. static char **argptr; /* argument list for builtin commands */
  1427. static char *optionarg; /* set by nextopt (like getopt) */
  1428. static char *optptr; /* used by nextopt */
  1429. /*
  1430. * XXX - should get rid of. Have all builtins use getopt(3).
  1431. * The library getopt must have the BSD extension static variable
  1432. * "optreset", otherwise it can't be used within the shell safely.
  1433. *
  1434. * Standard option processing (a la getopt) for builtin routines.
  1435. * The only argument that is passed to nextopt is the option string;
  1436. * the other arguments are unnecessary. It returns the character,
  1437. * or '\0' on end of input.
  1438. */
  1439. static int
  1440. nextopt(const char *optstring)
  1441. {
  1442. char *p;
  1443. const char *q;
  1444. char c;
  1445. p = optptr;
  1446. if (p == NULL || *p == '\0') {
  1447. /* We ate entire "-param", take next one */
  1448. p = *argptr;
  1449. if (p == NULL)
  1450. return '\0';
  1451. if (*p != '-')
  1452. return '\0';
  1453. if (*++p == '\0') /* just "-" ? */
  1454. return '\0';
  1455. argptr++;
  1456. if (LONE_DASH(p)) /* "--" ? */
  1457. return '\0';
  1458. /* p => next "-param" */
  1459. }
  1460. /* p => some option char in the middle of a "-param" */
  1461. c = *p++;
  1462. for (q = optstring; *q != c;) {
  1463. if (*q == '\0')
  1464. ash_msg_and_raise_error("illegal option -%c", c);
  1465. if (*++q == ':')
  1466. q++;
  1467. }
  1468. if (*++q == ':') {
  1469. if (*p == '\0') {
  1470. p = *argptr++;
  1471. if (p == NULL)
  1472. ash_msg_and_raise_error("no arg for -%c option", c);
  1473. }
  1474. optionarg = p;
  1475. p = NULL;
  1476. }
  1477. optptr = p;
  1478. return c;
  1479. }
  1480. /* ============ Shell variables */
  1481. /*
  1482. * The parsefile structure pointed to by the global variable parsefile
  1483. * contains information about the current file being read.
  1484. */
  1485. struct shparam {
  1486. int nparam; /* # of positional parameters (without $0) */
  1487. #if ENABLE_ASH_GETOPTS
  1488. int optind; /* next parameter to be processed by getopts */
  1489. int optoff; /* used by getopts */
  1490. #endif
  1491. unsigned char malloced; /* if parameter list dynamically allocated */
  1492. char **p; /* parameter list */
  1493. };
  1494. /*
  1495. * Free the list of positional parameters.
  1496. */
  1497. static void
  1498. freeparam(volatile struct shparam *param)
  1499. {
  1500. if (param->malloced) {
  1501. char **ap, **ap1;
  1502. ap = ap1 = param->p;
  1503. while (*ap)
  1504. free(*ap++);
  1505. free(ap1);
  1506. }
  1507. }
  1508. #if ENABLE_ASH_GETOPTS
  1509. static void FAST_FUNC getoptsreset(const char *value);
  1510. #endif
  1511. struct var {
  1512. struct var *next; /* next entry in hash list */
  1513. int flags; /* flags are defined above */
  1514. const char *text; /* name=value */
  1515. void (*func)(const char *) FAST_FUNC; /* function to be called when */
  1516. /* the variable gets set/unset */
  1517. };
  1518. struct localvar {
  1519. struct localvar *next; /* next local variable in list */
  1520. struct var *vp; /* the variable that was made local */
  1521. int flags; /* saved flags */
  1522. const char *text; /* saved text */
  1523. };
  1524. /* flags */
  1525. #define VEXPORT 0x01 /* variable is exported */
  1526. #define VREADONLY 0x02 /* variable cannot be modified */
  1527. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1528. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1529. #define VSTACK 0x10 /* text is allocated on the stack */
  1530. #define VUNSET 0x20 /* the variable is not set */
  1531. #define VNOFUNC 0x40 /* don't call the callback function */
  1532. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1533. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1534. #if ENABLE_ASH_RANDOM_SUPPORT
  1535. # define VDYNAMIC 0x200 /* dynamic variable */
  1536. #else
  1537. # define VDYNAMIC 0
  1538. #endif
  1539. /* Need to be before varinit_data[] */
  1540. #if ENABLE_LOCALE_SUPPORT
  1541. static void FAST_FUNC
  1542. change_lc_all(const char *value)
  1543. {
  1544. if (value && *value != '\0')
  1545. setlocale(LC_ALL, value);
  1546. }
  1547. static void FAST_FUNC
  1548. change_lc_ctype(const char *value)
  1549. {
  1550. if (value && *value != '\0')
  1551. setlocale(LC_CTYPE, value);
  1552. }
  1553. #endif
  1554. #if ENABLE_ASH_MAIL
  1555. static void chkmail(void);
  1556. static void changemail(const char *) FAST_FUNC;
  1557. #endif
  1558. static void changepath(const char *) FAST_FUNC;
  1559. #if ENABLE_ASH_RANDOM_SUPPORT
  1560. static void change_random(const char *) FAST_FUNC;
  1561. #endif
  1562. static const struct {
  1563. int flags;
  1564. const char *text;
  1565. void (*func)(const char *) FAST_FUNC;
  1566. } varinit_data[] = {
  1567. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1568. #if ENABLE_ASH_MAIL
  1569. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
  1570. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1571. #endif
  1572. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1573. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1574. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1575. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1576. #if ENABLE_ASH_GETOPTS
  1577. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1578. #endif
  1579. #if ENABLE_ASH_RANDOM_SUPPORT
  1580. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1581. #endif
  1582. #if ENABLE_LOCALE_SUPPORT
  1583. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
  1584. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1585. #endif
  1586. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1587. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
  1588. #endif
  1589. };
  1590. struct redirtab;
  1591. struct globals_var {
  1592. struct shparam shellparam; /* $@ current positional parameters */
  1593. struct redirtab *redirlist;
  1594. int g_nullredirs;
  1595. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1596. struct var *vartab[VTABSIZE];
  1597. struct var varinit[ARRAY_SIZE(varinit_data)];
  1598. };
  1599. extern struct globals_var *const ash_ptr_to_globals_var;
  1600. #define G_var (*ash_ptr_to_globals_var)
  1601. #define shellparam (G_var.shellparam )
  1602. //#define redirlist (G_var.redirlist )
  1603. #define g_nullredirs (G_var.g_nullredirs )
  1604. #define preverrout_fd (G_var.preverrout_fd)
  1605. #define vartab (G_var.vartab )
  1606. #define varinit (G_var.varinit )
  1607. #define INIT_G_var() do { \
  1608. unsigned i; \
  1609. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1610. barrier(); \
  1611. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1612. varinit[i].flags = varinit_data[i].flags; \
  1613. varinit[i].text = varinit_data[i].text; \
  1614. varinit[i].func = varinit_data[i].func; \
  1615. } \
  1616. } while (0)
  1617. #define vifs varinit[0]
  1618. #if ENABLE_ASH_MAIL
  1619. # define vmail (&vifs)[1]
  1620. # define vmpath (&vmail)[1]
  1621. # define vpath (&vmpath)[1]
  1622. #else
  1623. # define vpath (&vifs)[1]
  1624. #endif
  1625. #define vps1 (&vpath)[1]
  1626. #define vps2 (&vps1)[1]
  1627. #define vps4 (&vps2)[1]
  1628. #if ENABLE_ASH_GETOPTS
  1629. # define voptind (&vps4)[1]
  1630. # if ENABLE_ASH_RANDOM_SUPPORT
  1631. # define vrandom (&voptind)[1]
  1632. # endif
  1633. #else
  1634. # if ENABLE_ASH_RANDOM_SUPPORT
  1635. # define vrandom (&vps4)[1]
  1636. # endif
  1637. #endif
  1638. /*
  1639. * The following macros access the values of the above variables.
  1640. * They have to skip over the name. They return the null string
  1641. * for unset variables.
  1642. */
  1643. #define ifsval() (vifs.text + 4)
  1644. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1645. #if ENABLE_ASH_MAIL
  1646. # define mailval() (vmail.text + 5)
  1647. # define mpathval() (vmpath.text + 9)
  1648. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1649. #endif
  1650. #define pathval() (vpath.text + 5)
  1651. #define ps1val() (vps1.text + 4)
  1652. #define ps2val() (vps2.text + 4)
  1653. #define ps4val() (vps4.text + 4)
  1654. #if ENABLE_ASH_GETOPTS
  1655. # define optindval() (voptind.text + 7)
  1656. #endif
  1657. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1658. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1659. #if ENABLE_ASH_GETOPTS
  1660. static void FAST_FUNC
  1661. getoptsreset(const char *value)
  1662. {
  1663. shellparam.optind = number(value);
  1664. shellparam.optoff = -1;
  1665. }
  1666. #endif
  1667. /*
  1668. * Return of a legal variable name (a letter or underscore followed by zero or
  1669. * more letters, underscores, and digits).
  1670. */
  1671. static char* FAST_FUNC
  1672. endofname(const char *name)
  1673. {
  1674. char *p;
  1675. p = (char *) name;
  1676. if (!is_name(*p))
  1677. return p;
  1678. while (*++p) {
  1679. if (!is_in_name(*p))
  1680. break;
  1681. }
  1682. return p;
  1683. }
  1684. /*
  1685. * Compares two strings up to the first = or '\0'. The first
  1686. * string must be terminated by '='; the second may be terminated by
  1687. * either '=' or '\0'.
  1688. */
  1689. static int
  1690. varcmp(const char *p, const char *q)
  1691. {
  1692. int c, d;
  1693. while ((c = *p) == (d = *q)) {
  1694. if (!c || c == '=')
  1695. goto out;
  1696. p++;
  1697. q++;
  1698. }
  1699. if (c == '=')
  1700. c = '\0';
  1701. if (d == '=')
  1702. d = '\0';
  1703. out:
  1704. return c - d;
  1705. }
  1706. static int
  1707. varequal(const char *a, const char *b)
  1708. {
  1709. return !varcmp(a, b);
  1710. }
  1711. /*
  1712. * Find the appropriate entry in the hash table from the name.
  1713. */
  1714. static struct var **
  1715. hashvar(const char *p)
  1716. {
  1717. unsigned hashval;
  1718. hashval = ((unsigned char) *p) << 4;
  1719. while (*p && *p != '=')
  1720. hashval += (unsigned char) *p++;
  1721. return &vartab[hashval % VTABSIZE];
  1722. }
  1723. static int
  1724. vpcmp(const void *a, const void *b)
  1725. {
  1726. return varcmp(*(const char **)a, *(const char **)b);
  1727. }
  1728. /*
  1729. * This routine initializes the builtin variables.
  1730. */
  1731. static void
  1732. initvar(void)
  1733. {
  1734. struct var *vp;
  1735. struct var *end;
  1736. struct var **vpp;
  1737. /*
  1738. * PS1 depends on uid
  1739. */
  1740. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1741. vps1.text = "PS1=\\w \\$ ";
  1742. #else
  1743. if (!geteuid())
  1744. vps1.text = "PS1=# ";
  1745. #endif
  1746. vp = varinit;
  1747. end = vp + ARRAY_SIZE(varinit);
  1748. do {
  1749. vpp = hashvar(vp->text);
  1750. vp->next = *vpp;
  1751. *vpp = vp;
  1752. } while (++vp < end);
  1753. }
  1754. static struct var **
  1755. findvar(struct var **vpp, const char *name)
  1756. {
  1757. for (; *vpp; vpp = &(*vpp)->next) {
  1758. if (varequal((*vpp)->text, name)) {
  1759. break;
  1760. }
  1761. }
  1762. return vpp;
  1763. }
  1764. /*
  1765. * Find the value of a variable. Returns NULL if not set.
  1766. */
  1767. static const char* FAST_FUNC
  1768. lookupvar(const char *name)
  1769. {
  1770. struct var *v;
  1771. v = *findvar(hashvar(name), name);
  1772. if (v) {
  1773. #if ENABLE_ASH_RANDOM_SUPPORT
  1774. /*
  1775. * Dynamic variables are implemented roughly the same way they are
  1776. * in bash. Namely, they're "special" so long as they aren't unset.
  1777. * As soon as they're unset, they're no longer dynamic, and dynamic
  1778. * lookup will no longer happen at that point. -- PFM.
  1779. */
  1780. if ((v->flags & VDYNAMIC))
  1781. (*v->func)(NULL);
  1782. #endif
  1783. if (!(v->flags & VUNSET))
  1784. return strchrnul(v->text, '=') + 1;
  1785. }
  1786. return NULL;
  1787. }
  1788. /*
  1789. * Search the environment of a builtin command.
  1790. */
  1791. static const char *
  1792. bltinlookup(const char *name)
  1793. {
  1794. struct strlist *sp;
  1795. for (sp = cmdenviron; sp; sp = sp->next) {
  1796. if (varequal(sp->text, name))
  1797. return strchrnul(sp->text, '=') + 1;
  1798. }
  1799. return lookupvar(name);
  1800. }
  1801. /*
  1802. * Same as setvar except that the variable and value are passed in
  1803. * the first argument as name=value. Since the first argument will
  1804. * be actually stored in the table, it should not be a string that
  1805. * will go away.
  1806. * Called with interrupts off.
  1807. */
  1808. static void
  1809. setvareq(char *s, int flags)
  1810. {
  1811. struct var *vp, **vpp;
  1812. vpp = hashvar(s);
  1813. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1814. vp = *findvar(vpp, s);
  1815. if (vp) {
  1816. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1817. const char *n;
  1818. if (flags & VNOSAVE)
  1819. free(s);
  1820. n = vp->text;
  1821. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1822. }
  1823. if (flags & VNOSET)
  1824. return;
  1825. if (vp->func && (flags & VNOFUNC) == 0)
  1826. (*vp->func)(strchrnul(s, '=') + 1);
  1827. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1828. free((char*)vp->text);
  1829. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1830. } else {
  1831. if (flags & VNOSET)
  1832. return;
  1833. /* not found */
  1834. vp = ckzalloc(sizeof(*vp));
  1835. vp->next = *vpp;
  1836. /*vp->func = NULL; - ckzalloc did it */
  1837. *vpp = vp;
  1838. }
  1839. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1840. s = ckstrdup(s);
  1841. vp->text = s;
  1842. vp->flags = flags;
  1843. }
  1844. /*
  1845. * Set the value of a variable. The flags argument is ored with the
  1846. * flags of the variable. If val is NULL, the variable is unset.
  1847. */
  1848. static void
  1849. setvar(const char *name, const char *val, int flags)
  1850. {
  1851. char *p, *q;
  1852. size_t namelen;
  1853. char *nameeq;
  1854. size_t vallen;
  1855. q = endofname(name);
  1856. p = strchrnul(q, '=');
  1857. namelen = p - name;
  1858. if (!namelen || p != q)
  1859. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1860. vallen = 0;
  1861. if (val == NULL) {
  1862. flags |= VUNSET;
  1863. } else {
  1864. vallen = strlen(val);
  1865. }
  1866. INT_OFF;
  1867. nameeq = ckmalloc(namelen + vallen + 2);
  1868. p = (char *)memcpy(nameeq, name, namelen) + namelen;
  1869. if (val) {
  1870. *p++ = '=';
  1871. p = (char *)memcpy(p, val, vallen) + vallen;
  1872. }
  1873. *p = '\0';
  1874. setvareq(nameeq, flags | VNOSAVE);
  1875. INT_ON;
  1876. }
  1877. static void FAST_FUNC
  1878. setvar2(const char *name, const char *val)
  1879. {
  1880. setvar(name, val, 0);
  1881. }
  1882. #if ENABLE_ASH_GETOPTS
  1883. /*
  1884. * Safe version of setvar, returns 1 on success 0 on failure.
  1885. */
  1886. static int
  1887. setvarsafe(const char *name, const char *val, int flags)
  1888. {
  1889. int err;
  1890. volatile int saveint;
  1891. struct jmploc *volatile savehandler = exception_handler;
  1892. struct jmploc jmploc;
  1893. SAVE_INT(saveint);
  1894. if (setjmp(jmploc.loc))
  1895. err = 1;
  1896. else {
  1897. exception_handler = &jmploc;
  1898. setvar(name, val, flags);
  1899. err = 0;
  1900. }
  1901. exception_handler = savehandler;
  1902. RESTORE_INT(saveint);
  1903. return err;
  1904. }
  1905. #endif
  1906. /*
  1907. * Unset the specified variable.
  1908. */
  1909. static int
  1910. unsetvar(const char *s)
  1911. {
  1912. struct var **vpp;
  1913. struct var *vp;
  1914. int retval;
  1915. vpp = findvar(hashvar(s), s);
  1916. vp = *vpp;
  1917. retval = 2;
  1918. if (vp) {
  1919. int flags = vp->flags;
  1920. retval = 1;
  1921. if (flags & VREADONLY)
  1922. goto out;
  1923. #if ENABLE_ASH_RANDOM_SUPPORT
  1924. vp->flags &= ~VDYNAMIC;
  1925. #endif
  1926. if (flags & VUNSET)
  1927. goto ok;
  1928. if ((flags & VSTRFIXED) == 0) {
  1929. INT_OFF;
  1930. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1931. free((char*)vp->text);
  1932. *vpp = vp->next;
  1933. free(vp);
  1934. INT_ON;
  1935. } else {
  1936. setvar(s, 0, 0);
  1937. vp->flags &= ~VEXPORT;
  1938. }
  1939. ok:
  1940. retval = 0;
  1941. }
  1942. out:
  1943. return retval;
  1944. }
  1945. /*
  1946. * Process a linked list of variable assignments.
  1947. */
  1948. static void
  1949. listsetvar(struct strlist *list_set_var, int flags)
  1950. {
  1951. struct strlist *lp = list_set_var;
  1952. if (!lp)
  1953. return;
  1954. INT_OFF;
  1955. do {
  1956. setvareq(lp->text, flags);
  1957. lp = lp->next;
  1958. } while (lp);
  1959. INT_ON;
  1960. }
  1961. /*
  1962. * Generate a list of variables satisfying the given conditions.
  1963. */
  1964. static char **
  1965. listvars(int on, int off, char ***end)
  1966. {
  1967. struct var **vpp;
  1968. struct var *vp;
  1969. char **ep;
  1970. int mask;
  1971. STARTSTACKSTR(ep);
  1972. vpp = vartab;
  1973. mask = on | off;
  1974. do {
  1975. for (vp = *vpp; vp; vp = vp->next) {
  1976. if ((vp->flags & mask) == on) {
  1977. if (ep == stackstrend())
  1978. ep = growstackstr();
  1979. *ep++ = (char *) vp->text;
  1980. }
  1981. }
  1982. } while (++vpp < vartab + VTABSIZE);
  1983. if (ep == stackstrend())
  1984. ep = growstackstr();
  1985. if (end)
  1986. *end = ep;
  1987. *ep++ = NULL;
  1988. return grabstackstr(ep);
  1989. }
  1990. /* ============ Path search helper
  1991. *
  1992. * The variable path (passed by reference) should be set to the start
  1993. * of the path before the first call; path_advance will update
  1994. * this value as it proceeds. Successive calls to path_advance will return
  1995. * the possible path expansions in sequence. If an option (indicated by
  1996. * a percent sign) appears in the path entry then the global variable
  1997. * pathopt will be set to point to it; otherwise pathopt will be set to
  1998. * NULL.
  1999. */
  2000. static const char *pathopt; /* set by path_advance */
  2001. static char *
  2002. path_advance(const char **path, const char *name)
  2003. {
  2004. const char *p;
  2005. char *q;
  2006. const char *start;
  2007. size_t len;
  2008. if (*path == NULL)
  2009. return NULL;
  2010. start = *path;
  2011. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2012. continue;
  2013. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2014. while (stackblocksize() < len)
  2015. growstackblock();
  2016. q = stackblock();
  2017. if (p != start) {
  2018. memcpy(q, start, p - start);
  2019. q += p - start;
  2020. *q++ = '/';
  2021. }
  2022. strcpy(q, name);
  2023. pathopt = NULL;
  2024. if (*p == '%') {
  2025. pathopt = ++p;
  2026. while (*p && *p != ':')
  2027. p++;
  2028. }
  2029. if (*p == ':')
  2030. *path = p + 1;
  2031. else
  2032. *path = NULL;
  2033. return stalloc(len);
  2034. }
  2035. /* ============ Prompt */
  2036. static smallint doprompt; /* if set, prompt the user */
  2037. static smallint needprompt; /* true if interactive and at start of line */
  2038. #if ENABLE_FEATURE_EDITING
  2039. static line_input_t *line_input_state;
  2040. static const char *cmdedit_prompt;
  2041. static void
  2042. putprompt(const char *s)
  2043. {
  2044. if (ENABLE_ASH_EXPAND_PRMT) {
  2045. free((char*)cmdedit_prompt);
  2046. cmdedit_prompt = ckstrdup(s);
  2047. return;
  2048. }
  2049. cmdedit_prompt = s;
  2050. }
  2051. #else
  2052. static void
  2053. putprompt(const char *s)
  2054. {
  2055. out2str(s);
  2056. }
  2057. #endif
  2058. #if ENABLE_ASH_EXPAND_PRMT
  2059. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2060. static const char *expandstr(const char *ps);
  2061. #else
  2062. #define expandstr(s) s
  2063. #endif
  2064. static void
  2065. setprompt(int whichprompt)
  2066. {
  2067. const char *prompt;
  2068. #if ENABLE_ASH_EXPAND_PRMT
  2069. struct stackmark smark;
  2070. #endif
  2071. needprompt = 0;
  2072. switch (whichprompt) {
  2073. case 1:
  2074. prompt = ps1val();
  2075. break;
  2076. case 2:
  2077. prompt = ps2val();
  2078. break;
  2079. default: /* 0 */
  2080. prompt = nullstr;
  2081. }
  2082. #if ENABLE_ASH_EXPAND_PRMT
  2083. setstackmark(&smark);
  2084. stalloc(stackblocksize());
  2085. #endif
  2086. putprompt(expandstr(prompt));
  2087. #if ENABLE_ASH_EXPAND_PRMT
  2088. popstackmark(&smark);
  2089. #endif
  2090. }
  2091. /* ============ The cd and pwd commands */
  2092. #define CD_PHYSICAL 1
  2093. #define CD_PRINT 2
  2094. static int
  2095. cdopt(void)
  2096. {
  2097. int flags = 0;
  2098. int i, j;
  2099. j = 'L';
  2100. while ((i = nextopt("LP")) != '\0') {
  2101. if (i != j) {
  2102. flags ^= CD_PHYSICAL;
  2103. j = i;
  2104. }
  2105. }
  2106. return flags;
  2107. }
  2108. /*
  2109. * Update curdir (the name of the current directory) in response to a
  2110. * cd command.
  2111. */
  2112. static const char *
  2113. updatepwd(const char *dir)
  2114. {
  2115. char *new;
  2116. char *p;
  2117. char *cdcomppath;
  2118. const char *lim;
  2119. cdcomppath = ststrdup(dir);
  2120. STARTSTACKSTR(new);
  2121. if (*dir != '/') {
  2122. if (curdir == nullstr)
  2123. return 0;
  2124. new = stack_putstr(curdir, new);
  2125. }
  2126. new = makestrspace(strlen(dir) + 2, new);
  2127. lim = (char *)stackblock() + 1;
  2128. if (*dir != '/') {
  2129. if (new[-1] != '/')
  2130. USTPUTC('/', new);
  2131. if (new > lim && *lim == '/')
  2132. lim++;
  2133. } else {
  2134. USTPUTC('/', new);
  2135. cdcomppath++;
  2136. if (dir[1] == '/' && dir[2] != '/') {
  2137. USTPUTC('/', new);
  2138. cdcomppath++;
  2139. lim++;
  2140. }
  2141. }
  2142. p = strtok(cdcomppath, "/");
  2143. while (p) {
  2144. switch (*p) {
  2145. case '.':
  2146. if (p[1] == '.' && p[2] == '\0') {
  2147. while (new > lim) {
  2148. STUNPUTC(new);
  2149. if (new[-1] == '/')
  2150. break;
  2151. }
  2152. break;
  2153. }
  2154. if (p[1] == '\0')
  2155. break;
  2156. /* fall through */
  2157. default:
  2158. new = stack_putstr(p, new);
  2159. USTPUTC('/', new);
  2160. }
  2161. p = strtok(0, "/");
  2162. }
  2163. if (new > lim)
  2164. STUNPUTC(new);
  2165. *new = 0;
  2166. return stackblock();
  2167. }
  2168. /*
  2169. * Find out what the current directory is. If we already know the current
  2170. * directory, this routine returns immediately.
  2171. */
  2172. static char *
  2173. getpwd(void)
  2174. {
  2175. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2176. return dir ? dir : nullstr;
  2177. }
  2178. static void
  2179. setpwd(const char *val, int setold)
  2180. {
  2181. char *oldcur, *dir;
  2182. oldcur = dir = curdir;
  2183. if (setold) {
  2184. setvar("OLDPWD", oldcur, VEXPORT);
  2185. }
  2186. INT_OFF;
  2187. if (physdir != nullstr) {
  2188. if (physdir != oldcur)
  2189. free(physdir);
  2190. physdir = nullstr;
  2191. }
  2192. if (oldcur == val || !val) {
  2193. char *s = getpwd();
  2194. physdir = s;
  2195. if (!val)
  2196. dir = s;
  2197. } else
  2198. dir = ckstrdup(val);
  2199. if (oldcur != dir && oldcur != nullstr) {
  2200. free(oldcur);
  2201. }
  2202. curdir = dir;
  2203. INT_ON;
  2204. setvar("PWD", dir, VEXPORT);
  2205. }
  2206. static void hashcd(void);
  2207. /*
  2208. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2209. * know that the current directory has changed.
  2210. */
  2211. static int
  2212. docd(const char *dest, int flags)
  2213. {
  2214. const char *dir = 0;
  2215. int err;
  2216. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2217. INT_OFF;
  2218. if (!(flags & CD_PHYSICAL)) {
  2219. dir = updatepwd(dest);
  2220. if (dir)
  2221. dest = dir;
  2222. }
  2223. err = chdir(dest);
  2224. if (err)
  2225. goto out;
  2226. setpwd(dir, 1);
  2227. hashcd();
  2228. out:
  2229. INT_ON;
  2230. return err;
  2231. }
  2232. static int FAST_FUNC
  2233. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2234. {
  2235. const char *dest;
  2236. const char *path;
  2237. const char *p;
  2238. char c;
  2239. struct stat statb;
  2240. int flags;
  2241. flags = cdopt();
  2242. dest = *argptr;
  2243. if (!dest)
  2244. dest = bltinlookup(homestr);
  2245. else if (LONE_DASH(dest)) {
  2246. dest = bltinlookup("OLDPWD");
  2247. flags |= CD_PRINT;
  2248. }
  2249. if (!dest)
  2250. dest = nullstr;
  2251. if (*dest == '/')
  2252. goto step7;
  2253. if (*dest == '.') {
  2254. c = dest[1];
  2255. dotdot:
  2256. switch (c) {
  2257. case '\0':
  2258. case '/':
  2259. goto step6;
  2260. case '.':
  2261. c = dest[2];
  2262. if (c != '.')
  2263. goto dotdot;
  2264. }
  2265. }
  2266. if (!*dest)
  2267. dest = ".";
  2268. path = bltinlookup("CDPATH");
  2269. if (!path) {
  2270. step6:
  2271. step7:
  2272. p = dest;
  2273. goto docd;
  2274. }
  2275. do {
  2276. c = *path;
  2277. p = path_advance(&path, dest);
  2278. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2279. if (c && c != ':')
  2280. flags |= CD_PRINT;
  2281. docd:
  2282. if (!docd(p, flags))
  2283. goto out;
  2284. break;
  2285. }
  2286. } while (path);
  2287. ash_msg_and_raise_error("can't cd to %s", dest);
  2288. /* NOTREACHED */
  2289. out:
  2290. if (flags & CD_PRINT)
  2291. out1fmt(snlfmt, curdir);
  2292. return 0;
  2293. }
  2294. static int FAST_FUNC
  2295. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2296. {
  2297. int flags;
  2298. const char *dir = curdir;
  2299. flags = cdopt();
  2300. if (flags) {
  2301. if (physdir == nullstr)
  2302. setpwd(dir, 0);
  2303. dir = physdir;
  2304. }
  2305. out1fmt(snlfmt, dir);
  2306. return 0;
  2307. }
  2308. /* ============ ... */
  2309. #define IBUFSIZ COMMON_BUFSIZE
  2310. /* buffer for top level input file */
  2311. #define basebuf bb_common_bufsiz1
  2312. /* Syntax classes */
  2313. #define CWORD 0 /* character is nothing special */
  2314. #define CNL 1 /* newline character */
  2315. #define CBACK 2 /* a backslash character */
  2316. #define CSQUOTE 3 /* single quote */
  2317. #define CDQUOTE 4 /* double quote */
  2318. #define CENDQUOTE 5 /* a terminating quote */
  2319. #define CBQUOTE 6 /* backwards single quote */
  2320. #define CVAR 7 /* a dollar sign */
  2321. #define CENDVAR 8 /* a '}' character */
  2322. #define CLP 9 /* a left paren in arithmetic */
  2323. #define CRP 10 /* a right paren in arithmetic */
  2324. #define CENDFILE 11 /* end of file */
  2325. #define CCTL 12 /* like CWORD, except it must be escaped */
  2326. #define CSPCL 13 /* these terminate a word */
  2327. #define CIGN 14 /* character should be ignored */
  2328. #define PEOF 256
  2329. #if ENABLE_ASH_ALIAS
  2330. # define PEOA 257
  2331. #endif
  2332. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2333. #if ENABLE_SH_MATH_SUPPORT
  2334. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2335. #else
  2336. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2337. #endif
  2338. static const uint16_t S_I_T[] = {
  2339. #if ENABLE_ASH_ALIAS
  2340. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2341. #endif
  2342. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2343. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2344. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2345. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2346. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2347. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2348. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2349. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2350. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2351. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2352. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2353. #if !USE_SIT_FUNCTION
  2354. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2355. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2356. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2357. #endif
  2358. #undef SIT_ITEM
  2359. };
  2360. /* Constants below must match table above */
  2361. enum {
  2362. #if ENABLE_ASH_ALIAS
  2363. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2364. #endif
  2365. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2366. CNL_CNL_CNL_CNL , /* 2 */
  2367. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2368. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2369. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2370. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2371. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2372. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2373. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2374. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2375. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2376. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2377. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2378. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2379. };
  2380. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2381. * caller must ensure proper cast on it if c is *char_ptr!
  2382. */
  2383. /* Values for syntax param */
  2384. #define BASESYNTAX 0 /* not in quotes */
  2385. #define DQSYNTAX 1 /* in double quotes */
  2386. #define SQSYNTAX 2 /* in single quotes */
  2387. #define ARISYNTAX 3 /* in arithmetic */
  2388. #define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2389. #if USE_SIT_FUNCTION
  2390. static int
  2391. SIT(int c, int syntax)
  2392. {
  2393. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2394. # if ENABLE_ASH_ALIAS
  2395. static const uint8_t syntax_index_table[] ALIGN1 = {
  2396. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2397. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2398. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2399. 11, 3 /* "}~" */
  2400. };
  2401. # else
  2402. static const uint8_t syntax_index_table[] ALIGN1 = {
  2403. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2404. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2405. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2406. 10, 2 /* "}~" */
  2407. };
  2408. # endif
  2409. const char *s;
  2410. int indx;
  2411. if (c == PEOF)
  2412. return CENDFILE;
  2413. # if ENABLE_ASH_ALIAS
  2414. if (c == PEOA)
  2415. indx = 0;
  2416. else
  2417. # endif
  2418. {
  2419. /* Cast is purely for paranoia here,
  2420. * just in case someone passed signed char to us */
  2421. if ((unsigned char)c >= CTL_FIRST
  2422. && (unsigned char)c <= CTL_LAST
  2423. ) {
  2424. return CCTL;
  2425. }
  2426. s = strchrnul(spec_symbls, c);
  2427. if (*s == '\0')
  2428. return CWORD;
  2429. indx = syntax_index_table[s - spec_symbls];
  2430. }
  2431. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2432. }
  2433. #else /* !USE_SIT_FUNCTION */
  2434. static const uint8_t syntax_index_table[] = {
  2435. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2436. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2437. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2438. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2439. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2440. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2441. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2442. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2443. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2444. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2445. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2446. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2447. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2448. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2449. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2450. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2451. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2452. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2453. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2454. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2455. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2456. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2457. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2458. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2459. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2460. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2461. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2462. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2463. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2464. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2465. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2466. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2467. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2468. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2469. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2470. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2471. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2472. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2473. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2474. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2475. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2476. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2477. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2478. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2479. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2480. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2481. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2482. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2483. /* 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2484. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2485. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2486. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2487. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2488. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2489. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2490. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2491. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2492. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2493. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2495. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2496. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2497. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2498. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2499. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2500. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2501. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2502. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2507. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2508. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2509. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2511. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2513. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2514. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2515. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2516. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2517. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2520. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2522. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2528. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2529. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2530. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2531. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2533. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2534. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2535. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2536. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2537. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2538. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2561. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2562. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2563. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2566. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2567. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2568. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2569. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2570. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2571. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2572. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2573. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2601. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2602. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2603. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2623. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2624. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2625. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2626. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2692. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2693. # if ENABLE_ASH_ALIAS
  2694. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2695. # endif
  2696. };
  2697. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2698. #endif /* !USE_SIT_FUNCTION */
  2699. /* ============ Alias handling */
  2700. #if ENABLE_ASH_ALIAS
  2701. #define ALIASINUSE 1
  2702. #define ALIASDEAD 2
  2703. struct alias {
  2704. struct alias *next;
  2705. char *name;
  2706. char *val;
  2707. int flag;
  2708. };
  2709. static struct alias **atab; // [ATABSIZE];
  2710. #define INIT_G_alias() do { \
  2711. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2712. } while (0)
  2713. static struct alias **
  2714. __lookupalias(const char *name) {
  2715. unsigned int hashval;
  2716. struct alias **app;
  2717. const char *p;
  2718. unsigned int ch;
  2719. p = name;
  2720. ch = (unsigned char)*p;
  2721. hashval = ch << 4;
  2722. while (ch) {
  2723. hashval += ch;
  2724. ch = (unsigned char)*++p;
  2725. }
  2726. app = &atab[hashval % ATABSIZE];
  2727. for (; *app; app = &(*app)->next) {
  2728. if (strcmp(name, (*app)->name) == 0) {
  2729. break;
  2730. }
  2731. }
  2732. return app;
  2733. }
  2734. static struct alias *
  2735. lookupalias(const char *name, int check)
  2736. {
  2737. struct alias *ap = *__lookupalias(name);
  2738. if (check && ap && (ap->flag & ALIASINUSE))
  2739. return NULL;
  2740. return ap;
  2741. }
  2742. static struct alias *
  2743. freealias(struct alias *ap)
  2744. {
  2745. struct alias *next;
  2746. if (ap->flag & ALIASINUSE) {
  2747. ap->flag |= ALIASDEAD;
  2748. return ap;
  2749. }
  2750. next = ap->next;
  2751. free(ap->name);
  2752. free(ap->val);
  2753. free(ap);
  2754. return next;
  2755. }
  2756. static void
  2757. setalias(const char *name, const char *val)
  2758. {
  2759. struct alias *ap, **app;
  2760. app = __lookupalias(name);
  2761. ap = *app;
  2762. INT_OFF;
  2763. if (ap) {
  2764. if (!(ap->flag & ALIASINUSE)) {
  2765. free(ap->val);
  2766. }
  2767. ap->val = ckstrdup(val);
  2768. ap->flag &= ~ALIASDEAD;
  2769. } else {
  2770. /* not found */
  2771. ap = ckzalloc(sizeof(struct alias));
  2772. ap->name = ckstrdup(name);
  2773. ap->val = ckstrdup(val);
  2774. /*ap->flag = 0; - ckzalloc did it */
  2775. /*ap->next = NULL;*/
  2776. *app = ap;
  2777. }
  2778. INT_ON;
  2779. }
  2780. static int
  2781. unalias(const char *name)
  2782. {
  2783. struct alias **app;
  2784. app = __lookupalias(name);
  2785. if (*app) {
  2786. INT_OFF;
  2787. *app = freealias(*app);
  2788. INT_ON;
  2789. return 0;
  2790. }
  2791. return 1;
  2792. }
  2793. static void
  2794. rmaliases(void)
  2795. {
  2796. struct alias *ap, **app;
  2797. int i;
  2798. INT_OFF;
  2799. for (i = 0; i < ATABSIZE; i++) {
  2800. app = &atab[i];
  2801. for (ap = *app; ap; ap = *app) {
  2802. *app = freealias(*app);
  2803. if (ap == *app) {
  2804. app = &ap->next;
  2805. }
  2806. }
  2807. }
  2808. INT_ON;
  2809. }
  2810. static void
  2811. printalias(const struct alias *ap)
  2812. {
  2813. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2814. }
  2815. /*
  2816. * TODO - sort output
  2817. */
  2818. static int FAST_FUNC
  2819. aliascmd(int argc UNUSED_PARAM, char **argv)
  2820. {
  2821. char *n, *v;
  2822. int ret = 0;
  2823. struct alias *ap;
  2824. if (!argv[1]) {
  2825. int i;
  2826. for (i = 0; i < ATABSIZE; i++) {
  2827. for (ap = atab[i]; ap; ap = ap->next) {
  2828. printalias(ap);
  2829. }
  2830. }
  2831. return 0;
  2832. }
  2833. while ((n = *++argv) != NULL) {
  2834. v = strchr(n+1, '=');
  2835. if (v == NULL) { /* n+1: funny ksh stuff */
  2836. ap = *__lookupalias(n);
  2837. if (ap == NULL) {
  2838. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2839. ret = 1;
  2840. } else
  2841. printalias(ap);
  2842. } else {
  2843. *v++ = '\0';
  2844. setalias(n, v);
  2845. }
  2846. }
  2847. return ret;
  2848. }
  2849. static int FAST_FUNC
  2850. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2851. {
  2852. int i;
  2853. while ((i = nextopt("a")) != '\0') {
  2854. if (i == 'a') {
  2855. rmaliases();
  2856. return 0;
  2857. }
  2858. }
  2859. for (i = 0; *argptr; argptr++) {
  2860. if (unalias(*argptr)) {
  2861. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2862. i = 1;
  2863. }
  2864. }
  2865. return i;
  2866. }
  2867. #endif /* ASH_ALIAS */
  2868. /* ============ jobs.c */
  2869. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2870. #define FORK_FG 0
  2871. #define FORK_BG 1
  2872. #define FORK_NOJOB 2
  2873. /* mode flags for showjob(s) */
  2874. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  2875. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  2876. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  2877. /*
  2878. * A job structure contains information about a job. A job is either a
  2879. * single process or a set of processes contained in a pipeline. In the
  2880. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2881. * array of pids.
  2882. */
  2883. struct procstat {
  2884. pid_t ps_pid; /* process id */
  2885. int ps_status; /* last process status from wait() */
  2886. char *ps_cmd; /* text of command being run */
  2887. };
  2888. struct job {
  2889. struct procstat ps0; /* status of process */
  2890. struct procstat *ps; /* status or processes when more than one */
  2891. #if JOBS
  2892. int stopstatus; /* status of a stopped job */
  2893. #endif
  2894. uint32_t
  2895. nprocs: 16, /* number of processes */
  2896. state: 8,
  2897. #define JOBRUNNING 0 /* at least one proc running */
  2898. #define JOBSTOPPED 1 /* all procs are stopped */
  2899. #define JOBDONE 2 /* all procs are completed */
  2900. #if JOBS
  2901. sigint: 1, /* job was killed by SIGINT */
  2902. jobctl: 1, /* job running under job control */
  2903. #endif
  2904. waited: 1, /* true if this entry has been waited for */
  2905. used: 1, /* true if this entry is in used */
  2906. changed: 1; /* true if status has changed */
  2907. struct job *prev_job; /* previous job */
  2908. };
  2909. static struct job *makejob(/*union node *,*/ int);
  2910. static int forkshell(struct job *, union node *, int);
  2911. static int waitforjob(struct job *);
  2912. #if !JOBS
  2913. enum { doing_jobctl = 0 };
  2914. #define setjobctl(on) do {} while (0)
  2915. #else
  2916. static smallint doing_jobctl; //references:8
  2917. static void setjobctl(int);
  2918. #endif
  2919. /*
  2920. * Ignore a signal.
  2921. */
  2922. static void
  2923. ignoresig(int signo)
  2924. {
  2925. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  2926. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  2927. /* No, need to do it */
  2928. signal(signo, SIG_IGN);
  2929. }
  2930. sigmode[signo - 1] = S_HARD_IGN;
  2931. }
  2932. /*
  2933. * Signal handler. Only one usage site - in setsignal()
  2934. */
  2935. static void
  2936. onsig(int signo)
  2937. {
  2938. gotsig[signo - 1] = 1;
  2939. if (signo == SIGINT && !trap[SIGINT]) {
  2940. if (!suppress_int) {
  2941. pending_sig = 0;
  2942. raise_interrupt(); /* does not return */
  2943. }
  2944. pending_int = 1;
  2945. } else {
  2946. pending_sig = signo;
  2947. }
  2948. }
  2949. /*
  2950. * Set the signal handler for the specified signal. The routine figures
  2951. * out what it should be set to.
  2952. */
  2953. static void
  2954. setsignal(int signo)
  2955. {
  2956. char *t;
  2957. char cur_act, new_act;
  2958. struct sigaction act;
  2959. t = trap[signo];
  2960. new_act = S_DFL;
  2961. if (t != NULL) { /* trap for this sig is set */
  2962. new_act = S_CATCH;
  2963. if (t[0] == '\0') /* trap is "": ignore this sig */
  2964. new_act = S_IGN;
  2965. }
  2966. if (rootshell && new_act == S_DFL) {
  2967. switch (signo) {
  2968. case SIGINT:
  2969. if (iflag || minusc || sflag == 0)
  2970. new_act = S_CATCH;
  2971. break;
  2972. case SIGQUIT:
  2973. #if DEBUG
  2974. if (debug)
  2975. break;
  2976. #endif
  2977. /* man bash:
  2978. * "In all cases, bash ignores SIGQUIT. Non-builtin
  2979. * commands run by bash have signal handlers
  2980. * set to the values inherited by the shell
  2981. * from its parent". */
  2982. new_act = S_IGN;
  2983. break;
  2984. case SIGTERM:
  2985. if (iflag)
  2986. new_act = S_IGN;
  2987. break;
  2988. #if JOBS
  2989. case SIGTSTP:
  2990. case SIGTTOU:
  2991. if (mflag)
  2992. new_act = S_IGN;
  2993. break;
  2994. #endif
  2995. }
  2996. }
  2997. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  2998. //whereas we have to restore it to what shell got on entry
  2999. //from the parent. See comment above
  3000. t = &sigmode[signo - 1];
  3001. cur_act = *t;
  3002. if (cur_act == 0) {
  3003. /* current setting is not yet known */
  3004. if (sigaction(signo, NULL, &act)) {
  3005. /* pretend it worked; maybe we should give a warning,
  3006. * but other shells don't. We don't alter sigmode,
  3007. * so we retry every time.
  3008. * btw, in Linux it never fails. --vda */
  3009. return;
  3010. }
  3011. if (act.sa_handler == SIG_IGN) {
  3012. cur_act = S_HARD_IGN;
  3013. if (mflag
  3014. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3015. ) {
  3016. cur_act = S_IGN; /* don't hard ignore these */
  3017. }
  3018. }
  3019. }
  3020. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3021. return;
  3022. act.sa_handler = SIG_DFL;
  3023. switch (new_act) {
  3024. case S_CATCH:
  3025. act.sa_handler = onsig;
  3026. act.sa_flags = 0; /* matters only if !DFL and !IGN */
  3027. sigfillset(&act.sa_mask); /* ditto */
  3028. break;
  3029. case S_IGN:
  3030. act.sa_handler = SIG_IGN;
  3031. break;
  3032. }
  3033. sigaction_set(signo, &act);
  3034. *t = new_act;
  3035. }
  3036. /* mode flags for set_curjob */
  3037. #define CUR_DELETE 2
  3038. #define CUR_RUNNING 1
  3039. #define CUR_STOPPED 0
  3040. /* mode flags for dowait */
  3041. #define DOWAIT_NONBLOCK WNOHANG
  3042. #define DOWAIT_BLOCK 0
  3043. #if JOBS
  3044. /* pgrp of shell on invocation */
  3045. static int initialpgrp; //references:2
  3046. static int ttyfd = -1; //5
  3047. #endif
  3048. /* array of jobs */
  3049. static struct job *jobtab; //5
  3050. /* size of array */
  3051. static unsigned njobs; //4
  3052. /* current job */
  3053. static struct job *curjob; //lots
  3054. /* number of presumed living untracked jobs */
  3055. static int jobless; //4
  3056. static void
  3057. set_curjob(struct job *jp, unsigned mode)
  3058. {
  3059. struct job *jp1;
  3060. struct job **jpp, **curp;
  3061. /* first remove from list */
  3062. jpp = curp = &curjob;
  3063. do {
  3064. jp1 = *jpp;
  3065. if (jp1 == jp)
  3066. break;
  3067. jpp = &jp1->prev_job;
  3068. } while (1);
  3069. *jpp = jp1->prev_job;
  3070. /* Then re-insert in correct position */
  3071. jpp = curp;
  3072. switch (mode) {
  3073. default:
  3074. #if DEBUG
  3075. abort();
  3076. #endif
  3077. case CUR_DELETE:
  3078. /* job being deleted */
  3079. break;
  3080. case CUR_RUNNING:
  3081. /* newly created job or backgrounded job,
  3082. put after all stopped jobs. */
  3083. do {
  3084. jp1 = *jpp;
  3085. #if JOBS
  3086. if (!jp1 || jp1->state != JOBSTOPPED)
  3087. #endif
  3088. break;
  3089. jpp = &jp1->prev_job;
  3090. } while (1);
  3091. /* FALLTHROUGH */
  3092. #if JOBS
  3093. case CUR_STOPPED:
  3094. #endif
  3095. /* newly stopped job - becomes curjob */
  3096. jp->prev_job = *jpp;
  3097. *jpp = jp;
  3098. break;
  3099. }
  3100. }
  3101. #if JOBS || DEBUG
  3102. static int
  3103. jobno(const struct job *jp)
  3104. {
  3105. return jp - jobtab + 1;
  3106. }
  3107. #endif
  3108. /*
  3109. * Convert a job name to a job structure.
  3110. */
  3111. #if !JOBS
  3112. #define getjob(name, getctl) getjob(name)
  3113. #endif
  3114. static struct job *
  3115. getjob(const char *name, int getctl)
  3116. {
  3117. struct job *jp;
  3118. struct job *found;
  3119. const char *err_msg = "%s: no such job";
  3120. unsigned num;
  3121. int c;
  3122. const char *p;
  3123. char *(*match)(const char *, const char *);
  3124. jp = curjob;
  3125. p = name;
  3126. if (!p)
  3127. goto currentjob;
  3128. if (*p != '%')
  3129. goto err;
  3130. c = *++p;
  3131. if (!c)
  3132. goto currentjob;
  3133. if (!p[1]) {
  3134. if (c == '+' || c == '%') {
  3135. currentjob:
  3136. err_msg = "No current job";
  3137. goto check;
  3138. }
  3139. if (c == '-') {
  3140. if (jp)
  3141. jp = jp->prev_job;
  3142. err_msg = "No previous job";
  3143. check:
  3144. if (!jp)
  3145. goto err;
  3146. goto gotit;
  3147. }
  3148. }
  3149. if (is_number(p)) {
  3150. num = atoi(p);
  3151. if (num < njobs) {
  3152. jp = jobtab + num - 1;
  3153. if (jp->used)
  3154. goto gotit;
  3155. goto err;
  3156. }
  3157. }
  3158. match = prefix;
  3159. if (*p == '?') {
  3160. match = strstr;
  3161. p++;
  3162. }
  3163. found = NULL;
  3164. while (jp) {
  3165. if (match(jp->ps[0].ps_cmd, p)) {
  3166. if (found)
  3167. goto err;
  3168. found = jp;
  3169. err_msg = "%s: ambiguous";
  3170. }
  3171. jp = jp->prev_job;
  3172. }
  3173. if (!found)
  3174. goto err;
  3175. jp = found;
  3176. gotit:
  3177. #if JOBS
  3178. err_msg = "job %s not created under job control";
  3179. if (getctl && jp->jobctl == 0)
  3180. goto err;
  3181. #endif
  3182. return jp;
  3183. err:
  3184. ash_msg_and_raise_error(err_msg, name);
  3185. }
  3186. /*
  3187. * Mark a job structure as unused.
  3188. */
  3189. static void
  3190. freejob(struct job *jp)
  3191. {
  3192. struct procstat *ps;
  3193. int i;
  3194. INT_OFF;
  3195. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3196. if (ps->ps_cmd != nullstr)
  3197. free(ps->ps_cmd);
  3198. }
  3199. if (jp->ps != &jp->ps0)
  3200. free(jp->ps);
  3201. jp->used = 0;
  3202. set_curjob(jp, CUR_DELETE);
  3203. INT_ON;
  3204. }
  3205. #if JOBS
  3206. static void
  3207. xtcsetpgrp(int fd, pid_t pgrp)
  3208. {
  3209. if (tcsetpgrp(fd, pgrp))
  3210. ash_msg_and_raise_error("can't set tty process group (%m)");
  3211. }
  3212. /*
  3213. * Turn job control on and off.
  3214. *
  3215. * Note: This code assumes that the third arg to ioctl is a character
  3216. * pointer, which is true on Berkeley systems but not System V. Since
  3217. * System V doesn't have job control yet, this isn't a problem now.
  3218. *
  3219. * Called with interrupts off.
  3220. */
  3221. static void
  3222. setjobctl(int on)
  3223. {
  3224. int fd;
  3225. int pgrp;
  3226. if (on == doing_jobctl || rootshell == 0)
  3227. return;
  3228. if (on) {
  3229. int ofd;
  3230. ofd = fd = open(_PATH_TTY, O_RDWR);
  3231. if (fd < 0) {
  3232. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3233. * That sometimes helps to acquire controlling tty.
  3234. * Obviously, a workaround for bugs when someone
  3235. * failed to provide a controlling tty to bash! :) */
  3236. fd = 2;
  3237. while (!isatty(fd))
  3238. if (--fd < 0)
  3239. goto out;
  3240. }
  3241. fd = fcntl(fd, F_DUPFD, 10);
  3242. if (ofd >= 0)
  3243. close(ofd);
  3244. if (fd < 0)
  3245. goto out;
  3246. /* fd is a tty at this point */
  3247. close_on_exec_on(fd);
  3248. do { /* while we are in the background */
  3249. pgrp = tcgetpgrp(fd);
  3250. if (pgrp < 0) {
  3251. out:
  3252. ash_msg("can't access tty; job control turned off");
  3253. mflag = on = 0;
  3254. goto close;
  3255. }
  3256. if (pgrp == getpgrp())
  3257. break;
  3258. killpg(0, SIGTTIN);
  3259. } while (1);
  3260. initialpgrp = pgrp;
  3261. setsignal(SIGTSTP);
  3262. setsignal(SIGTTOU);
  3263. setsignal(SIGTTIN);
  3264. pgrp = rootpid;
  3265. setpgid(0, pgrp);
  3266. xtcsetpgrp(fd, pgrp);
  3267. } else {
  3268. /* turning job control off */
  3269. fd = ttyfd;
  3270. pgrp = initialpgrp;
  3271. /* was xtcsetpgrp, but this can make exiting ash
  3272. * loop forever if pty is already deleted */
  3273. tcsetpgrp(fd, pgrp);
  3274. setpgid(0, pgrp);
  3275. setsignal(SIGTSTP);
  3276. setsignal(SIGTTOU);
  3277. setsignal(SIGTTIN);
  3278. close:
  3279. if (fd >= 0)
  3280. close(fd);
  3281. fd = -1;
  3282. }
  3283. ttyfd = fd;
  3284. doing_jobctl = on;
  3285. }
  3286. static int FAST_FUNC
  3287. killcmd(int argc, char **argv)
  3288. {
  3289. int i = 1;
  3290. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3291. do {
  3292. if (argv[i][0] == '%') {
  3293. struct job *jp = getjob(argv[i], 0);
  3294. unsigned pid = jp->ps[0].ps_pid;
  3295. /* Enough space for ' -NNN<nul>' */
  3296. argv[i] = alloca(sizeof(int)*3 + 3);
  3297. /* kill_main has matching code to expect
  3298. * leading space. Needed to not confuse
  3299. * negative pids with "kill -SIGNAL_NO" syntax */
  3300. sprintf(argv[i], " -%u", pid);
  3301. }
  3302. } while (argv[++i]);
  3303. }
  3304. return kill_main(argc, argv);
  3305. }
  3306. static void
  3307. showpipe(struct job *jp /*, FILE *out*/)
  3308. {
  3309. struct procstat *ps;
  3310. struct procstat *psend;
  3311. psend = jp->ps + jp->nprocs;
  3312. for (ps = jp->ps + 1; ps < psend; ps++)
  3313. printf(" | %s", ps->ps_cmd);
  3314. outcslow('\n', stdout);
  3315. flush_stdout_stderr();
  3316. }
  3317. static int
  3318. restartjob(struct job *jp, int mode)
  3319. {
  3320. struct procstat *ps;
  3321. int i;
  3322. int status;
  3323. pid_t pgid;
  3324. INT_OFF;
  3325. if (jp->state == JOBDONE)
  3326. goto out;
  3327. jp->state = JOBRUNNING;
  3328. pgid = jp->ps[0].ps_pid;
  3329. if (mode == FORK_FG)
  3330. xtcsetpgrp(ttyfd, pgid);
  3331. killpg(pgid, SIGCONT);
  3332. ps = jp->ps;
  3333. i = jp->nprocs;
  3334. do {
  3335. if (WIFSTOPPED(ps->ps_status)) {
  3336. ps->ps_status = -1;
  3337. }
  3338. ps++;
  3339. } while (--i);
  3340. out:
  3341. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3342. INT_ON;
  3343. return status;
  3344. }
  3345. static int FAST_FUNC
  3346. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3347. {
  3348. struct job *jp;
  3349. int mode;
  3350. int retval;
  3351. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3352. nextopt(nullstr);
  3353. argv = argptr;
  3354. do {
  3355. jp = getjob(*argv, 1);
  3356. if (mode == FORK_BG) {
  3357. set_curjob(jp, CUR_RUNNING);
  3358. printf("[%d] ", jobno(jp));
  3359. }
  3360. out1str(jp->ps[0].ps_cmd);
  3361. showpipe(jp /*, stdout*/);
  3362. retval = restartjob(jp, mode);
  3363. } while (*argv && *++argv);
  3364. return retval;
  3365. }
  3366. #endif
  3367. static int
  3368. sprint_status(char *s, int status, int sigonly)
  3369. {
  3370. int col;
  3371. int st;
  3372. col = 0;
  3373. if (!WIFEXITED(status)) {
  3374. #if JOBS
  3375. if (WIFSTOPPED(status))
  3376. st = WSTOPSIG(status);
  3377. else
  3378. #endif
  3379. st = WTERMSIG(status);
  3380. if (sigonly) {
  3381. if (st == SIGINT || st == SIGPIPE)
  3382. goto out;
  3383. #if JOBS
  3384. if (WIFSTOPPED(status))
  3385. goto out;
  3386. #endif
  3387. }
  3388. st &= 0x7f;
  3389. col = fmtstr(s, 32, strsignal(st));
  3390. if (WCOREDUMP(status)) {
  3391. col += fmtstr(s + col, 16, " (core dumped)");
  3392. }
  3393. } else if (!sigonly) {
  3394. st = WEXITSTATUS(status);
  3395. if (st)
  3396. col = fmtstr(s, 16, "Done(%d)", st);
  3397. else
  3398. col = fmtstr(s, 16, "Done");
  3399. }
  3400. out:
  3401. return col;
  3402. }
  3403. static int
  3404. dowait(int wait_flags, struct job *job)
  3405. {
  3406. int pid;
  3407. int status;
  3408. struct job *jp;
  3409. struct job *thisjob;
  3410. int state;
  3411. TRACE(("dowait(0x%x) called\n", wait_flags));
  3412. /* Do a wait system call. If job control is compiled in, we accept
  3413. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3414. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3415. if (doing_jobctl)
  3416. wait_flags |= WUNTRACED;
  3417. pid = waitpid(-1, &status, wait_flags);
  3418. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3419. pid, status, errno, strerror(errno)));
  3420. if (pid <= 0)
  3421. return pid;
  3422. INT_OFF;
  3423. thisjob = NULL;
  3424. for (jp = curjob; jp; jp = jp->prev_job) {
  3425. struct procstat *ps;
  3426. struct procstat *psend;
  3427. if (jp->state == JOBDONE)
  3428. continue;
  3429. state = JOBDONE;
  3430. ps = jp->ps;
  3431. psend = ps + jp->nprocs;
  3432. do {
  3433. if (ps->ps_pid == pid) {
  3434. TRACE(("Job %d: changing status of proc %d "
  3435. "from 0x%x to 0x%x\n",
  3436. jobno(jp), pid, ps->ps_status, status));
  3437. ps->ps_status = status;
  3438. thisjob = jp;
  3439. }
  3440. if (ps->ps_status == -1)
  3441. state = JOBRUNNING;
  3442. #if JOBS
  3443. if (state == JOBRUNNING)
  3444. continue;
  3445. if (WIFSTOPPED(ps->ps_status)) {
  3446. jp->stopstatus = ps->ps_status;
  3447. state = JOBSTOPPED;
  3448. }
  3449. #endif
  3450. } while (++ps < psend);
  3451. if (thisjob)
  3452. goto gotjob;
  3453. }
  3454. #if JOBS
  3455. if (!WIFSTOPPED(status))
  3456. #endif
  3457. jobless--;
  3458. goto out;
  3459. gotjob:
  3460. if (state != JOBRUNNING) {
  3461. thisjob->changed = 1;
  3462. if (thisjob->state != state) {
  3463. TRACE(("Job %d: changing state from %d to %d\n",
  3464. jobno(thisjob), thisjob->state, state));
  3465. thisjob->state = state;
  3466. #if JOBS
  3467. if (state == JOBSTOPPED) {
  3468. set_curjob(thisjob, CUR_STOPPED);
  3469. }
  3470. #endif
  3471. }
  3472. }
  3473. out:
  3474. INT_ON;
  3475. if (thisjob && thisjob == job) {
  3476. char s[48 + 1];
  3477. int len;
  3478. len = sprint_status(s, status, 1);
  3479. if (len) {
  3480. s[len] = '\n';
  3481. s[len + 1] = '\0';
  3482. out2str(s);
  3483. }
  3484. }
  3485. return pid;
  3486. }
  3487. static int
  3488. blocking_wait_with_raise_on_sig(struct job *job)
  3489. {
  3490. pid_t pid = dowait(DOWAIT_BLOCK, job);
  3491. if (pid <= 0 && pending_sig)
  3492. raise_exception(EXSIG);
  3493. return pid;
  3494. }
  3495. #if JOBS
  3496. static void
  3497. showjob(FILE *out, struct job *jp, int mode)
  3498. {
  3499. struct procstat *ps;
  3500. struct procstat *psend;
  3501. int col;
  3502. int indent_col;
  3503. char s[80];
  3504. ps = jp->ps;
  3505. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3506. /* just output process (group) id of pipeline */
  3507. fprintf(out, "%d\n", ps->ps_pid);
  3508. return;
  3509. }
  3510. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3511. indent_col = col;
  3512. if (jp == curjob)
  3513. s[col - 3] = '+';
  3514. else if (curjob && jp == curjob->prev_job)
  3515. s[col - 3] = '-';
  3516. if (mode & SHOW_PIDS)
  3517. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3518. psend = ps + jp->nprocs;
  3519. if (jp->state == JOBRUNNING) {
  3520. strcpy(s + col, "Running");
  3521. col += sizeof("Running") - 1;
  3522. } else {
  3523. int status = psend[-1].ps_status;
  3524. if (jp->state == JOBSTOPPED)
  3525. status = jp->stopstatus;
  3526. col += sprint_status(s + col, status, 0);
  3527. }
  3528. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3529. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3530. * or prints several "PID | <cmdN>" lines,
  3531. * depending on SHOW_PIDS bit.
  3532. * We do not print status of individual processes
  3533. * between PID and <cmdN>. bash does it, but not very well:
  3534. * first line shows overall job status, not process status,
  3535. * making it impossible to know 1st process status.
  3536. */
  3537. goto start;
  3538. do {
  3539. /* for each process */
  3540. s[0] = '\0';
  3541. col = 33;
  3542. if (mode & SHOW_PIDS)
  3543. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3544. start:
  3545. fprintf(out, "%s%*c%s%s",
  3546. s,
  3547. 33 - col >= 0 ? 33 - col : 0, ' ',
  3548. ps == jp->ps ? "" : "| ",
  3549. ps->ps_cmd
  3550. );
  3551. } while (++ps != psend);
  3552. outcslow('\n', out);
  3553. jp->changed = 0;
  3554. if (jp->state == JOBDONE) {
  3555. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3556. freejob(jp);
  3557. }
  3558. }
  3559. /*
  3560. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3561. * statuses have changed since the last call to showjobs.
  3562. */
  3563. static void
  3564. showjobs(FILE *out, int mode)
  3565. {
  3566. struct job *jp;
  3567. TRACE(("showjobs(0x%x) called\n", mode));
  3568. /* Handle all finished jobs */
  3569. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3570. continue;
  3571. for (jp = curjob; jp; jp = jp->prev_job) {
  3572. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3573. showjob(out, jp, mode);
  3574. }
  3575. }
  3576. }
  3577. static int FAST_FUNC
  3578. jobscmd(int argc UNUSED_PARAM, char **argv)
  3579. {
  3580. int mode, m;
  3581. mode = 0;
  3582. while ((m = nextopt("lp")) != '\0') {
  3583. if (m == 'l')
  3584. mode |= SHOW_PIDS;
  3585. else
  3586. mode |= SHOW_ONLY_PGID;
  3587. }
  3588. argv = argptr;
  3589. if (*argv) {
  3590. do
  3591. showjob(stdout, getjob(*argv, 0), mode);
  3592. while (*++argv);
  3593. } else {
  3594. showjobs(stdout, mode);
  3595. }
  3596. return 0;
  3597. }
  3598. #endif /* JOBS */
  3599. /* Called only on finished or stopped jobs (no members are running) */
  3600. static int
  3601. getstatus(struct job *job)
  3602. {
  3603. int status;
  3604. int retval;
  3605. struct procstat *ps;
  3606. /* Fetch last member's status */
  3607. ps = job->ps + job->nprocs - 1;
  3608. status = ps->ps_status;
  3609. if (pipefail) {
  3610. /* "set -o pipefail" mode: use last _nonzero_ status */
  3611. while (status == 0 && --ps >= job->ps)
  3612. status = ps->ps_status;
  3613. }
  3614. retval = WEXITSTATUS(status);
  3615. if (!WIFEXITED(status)) {
  3616. #if JOBS
  3617. retval = WSTOPSIG(status);
  3618. if (!WIFSTOPPED(status))
  3619. #endif
  3620. {
  3621. /* XXX: limits number of signals */
  3622. retval = WTERMSIG(status);
  3623. #if JOBS
  3624. if (retval == SIGINT)
  3625. job->sigint = 1;
  3626. #endif
  3627. }
  3628. retval += 128;
  3629. }
  3630. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3631. jobno(job), job->nprocs, status, retval));
  3632. return retval;
  3633. }
  3634. static int FAST_FUNC
  3635. waitcmd(int argc UNUSED_PARAM, char **argv)
  3636. {
  3637. struct job *job;
  3638. int retval;
  3639. struct job *jp;
  3640. if (pending_sig)
  3641. raise_exception(EXSIG);
  3642. nextopt(nullstr);
  3643. retval = 0;
  3644. argv = argptr;
  3645. if (!*argv) {
  3646. /* wait for all jobs */
  3647. for (;;) {
  3648. jp = curjob;
  3649. while (1) {
  3650. if (!jp) /* no running procs */
  3651. goto ret;
  3652. if (jp->state == JOBRUNNING)
  3653. break;
  3654. jp->waited = 1;
  3655. jp = jp->prev_job;
  3656. }
  3657. /* man bash:
  3658. * "When bash is waiting for an asynchronous command via
  3659. * the wait builtin, the reception of a signal for which a trap
  3660. * has been set will cause the wait builtin to return immediately
  3661. * with an exit status greater than 128, immediately after which
  3662. * the trap is executed."
  3663. * Do we do it that way? */
  3664. blocking_wait_with_raise_on_sig(NULL);
  3665. }
  3666. }
  3667. retval = 127;
  3668. do {
  3669. if (**argv != '%') {
  3670. pid_t pid = number(*argv);
  3671. job = curjob;
  3672. while (1) {
  3673. if (!job)
  3674. goto repeat;
  3675. if (job->ps[job->nprocs - 1].ps_pid == pid)
  3676. break;
  3677. job = job->prev_job;
  3678. }
  3679. } else
  3680. job = getjob(*argv, 0);
  3681. /* loop until process terminated or stopped */
  3682. while (job->state == JOBRUNNING)
  3683. blocking_wait_with_raise_on_sig(NULL);
  3684. job->waited = 1;
  3685. retval = getstatus(job);
  3686. repeat: ;
  3687. } while (*++argv);
  3688. ret:
  3689. return retval;
  3690. }
  3691. static struct job *
  3692. growjobtab(void)
  3693. {
  3694. size_t len;
  3695. ptrdiff_t offset;
  3696. struct job *jp, *jq;
  3697. len = njobs * sizeof(*jp);
  3698. jq = jobtab;
  3699. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3700. offset = (char *)jp - (char *)jq;
  3701. if (offset) {
  3702. /* Relocate pointers */
  3703. size_t l = len;
  3704. jq = (struct job *)((char *)jq + l);
  3705. while (l) {
  3706. l -= sizeof(*jp);
  3707. jq--;
  3708. #define joff(p) ((struct job *)((char *)(p) + l))
  3709. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3710. if (joff(jp)->ps == &jq->ps0)
  3711. jmove(joff(jp)->ps);
  3712. if (joff(jp)->prev_job)
  3713. jmove(joff(jp)->prev_job);
  3714. }
  3715. if (curjob)
  3716. jmove(curjob);
  3717. #undef joff
  3718. #undef jmove
  3719. }
  3720. njobs += 4;
  3721. jobtab = jp;
  3722. jp = (struct job *)((char *)jp + len);
  3723. jq = jp + 3;
  3724. do {
  3725. jq->used = 0;
  3726. } while (--jq >= jp);
  3727. return jp;
  3728. }
  3729. /*
  3730. * Return a new job structure.
  3731. * Called with interrupts off.
  3732. */
  3733. static struct job *
  3734. makejob(/*union node *node,*/ int nprocs)
  3735. {
  3736. int i;
  3737. struct job *jp;
  3738. for (i = njobs, jp = jobtab; ; jp++) {
  3739. if (--i < 0) {
  3740. jp = growjobtab();
  3741. break;
  3742. }
  3743. if (jp->used == 0)
  3744. break;
  3745. if (jp->state != JOBDONE || !jp->waited)
  3746. continue;
  3747. #if JOBS
  3748. if (doing_jobctl)
  3749. continue;
  3750. #endif
  3751. freejob(jp);
  3752. break;
  3753. }
  3754. memset(jp, 0, sizeof(*jp));
  3755. #if JOBS
  3756. /* jp->jobctl is a bitfield.
  3757. * "jp->jobctl |= jobctl" likely to give awful code */
  3758. if (doing_jobctl)
  3759. jp->jobctl = 1;
  3760. #endif
  3761. jp->prev_job = curjob;
  3762. curjob = jp;
  3763. jp->used = 1;
  3764. jp->ps = &jp->ps0;
  3765. if (nprocs > 1) {
  3766. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3767. }
  3768. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3769. jobno(jp)));
  3770. return jp;
  3771. }
  3772. #if JOBS
  3773. /*
  3774. * Return a string identifying a command (to be printed by the
  3775. * jobs command).
  3776. */
  3777. static char *cmdnextc;
  3778. static void
  3779. cmdputs(const char *s)
  3780. {
  3781. static const char vstype[VSTYPE + 1][3] = {
  3782. "", "}", "-", "+", "?", "=",
  3783. "%", "%%", "#", "##"
  3784. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3785. };
  3786. const char *p, *str;
  3787. char cc[2];
  3788. char *nextc;
  3789. unsigned char c;
  3790. unsigned char subtype = 0;
  3791. int quoted = 0;
  3792. cc[1] = '\0';
  3793. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3794. p = s;
  3795. while ((c = *p++) != '\0') {
  3796. str = NULL;
  3797. switch (c) {
  3798. case CTLESC:
  3799. c = *p++;
  3800. break;
  3801. case CTLVAR:
  3802. subtype = *p++;
  3803. if ((subtype & VSTYPE) == VSLENGTH)
  3804. str = "${#";
  3805. else
  3806. str = "${";
  3807. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3808. goto dostr;
  3809. quoted ^= 1;
  3810. c = '"';
  3811. break;
  3812. case CTLENDVAR:
  3813. str = "\"}" + !(quoted & 1);
  3814. quoted >>= 1;
  3815. subtype = 0;
  3816. goto dostr;
  3817. case CTLBACKQ:
  3818. str = "$(...)";
  3819. goto dostr;
  3820. case CTLBACKQ+CTLQUOTE:
  3821. str = "\"$(...)\"";
  3822. goto dostr;
  3823. #if ENABLE_SH_MATH_SUPPORT
  3824. case CTLARI:
  3825. str = "$((";
  3826. goto dostr;
  3827. case CTLENDARI:
  3828. str = "))";
  3829. goto dostr;
  3830. #endif
  3831. case CTLQUOTEMARK:
  3832. quoted ^= 1;
  3833. c = '"';
  3834. break;
  3835. case '=':
  3836. if (subtype == 0)
  3837. break;
  3838. if ((subtype & VSTYPE) != VSNORMAL)
  3839. quoted <<= 1;
  3840. str = vstype[subtype & VSTYPE];
  3841. if (subtype & VSNUL)
  3842. c = ':';
  3843. else
  3844. goto checkstr;
  3845. break;
  3846. case '\'':
  3847. case '\\':
  3848. case '"':
  3849. case '$':
  3850. /* These can only happen inside quotes */
  3851. cc[0] = c;
  3852. str = cc;
  3853. c = '\\';
  3854. break;
  3855. default:
  3856. break;
  3857. }
  3858. USTPUTC(c, nextc);
  3859. checkstr:
  3860. if (!str)
  3861. continue;
  3862. dostr:
  3863. while ((c = *str++) != '\0') {
  3864. USTPUTC(c, nextc);
  3865. }
  3866. } /* while *p++ not NUL */
  3867. if (quoted & 1) {
  3868. USTPUTC('"', nextc);
  3869. }
  3870. *nextc = 0;
  3871. cmdnextc = nextc;
  3872. }
  3873. /* cmdtxt() and cmdlist() call each other */
  3874. static void cmdtxt(union node *n);
  3875. static void
  3876. cmdlist(union node *np, int sep)
  3877. {
  3878. for (; np; np = np->narg.next) {
  3879. if (!sep)
  3880. cmdputs(" ");
  3881. cmdtxt(np);
  3882. if (sep && np->narg.next)
  3883. cmdputs(" ");
  3884. }
  3885. }
  3886. static void
  3887. cmdtxt(union node *n)
  3888. {
  3889. union node *np;
  3890. struct nodelist *lp;
  3891. const char *p;
  3892. if (!n)
  3893. return;
  3894. switch (n->type) {
  3895. default:
  3896. #if DEBUG
  3897. abort();
  3898. #endif
  3899. case NPIPE:
  3900. lp = n->npipe.cmdlist;
  3901. for (;;) {
  3902. cmdtxt(lp->n);
  3903. lp = lp->next;
  3904. if (!lp)
  3905. break;
  3906. cmdputs(" | ");
  3907. }
  3908. break;
  3909. case NSEMI:
  3910. p = "; ";
  3911. goto binop;
  3912. case NAND:
  3913. p = " && ";
  3914. goto binop;
  3915. case NOR:
  3916. p = " || ";
  3917. binop:
  3918. cmdtxt(n->nbinary.ch1);
  3919. cmdputs(p);
  3920. n = n->nbinary.ch2;
  3921. goto donode;
  3922. case NREDIR:
  3923. case NBACKGND:
  3924. n = n->nredir.n;
  3925. goto donode;
  3926. case NNOT:
  3927. cmdputs("!");
  3928. n = n->nnot.com;
  3929. donode:
  3930. cmdtxt(n);
  3931. break;
  3932. case NIF:
  3933. cmdputs("if ");
  3934. cmdtxt(n->nif.test);
  3935. cmdputs("; then ");
  3936. if (n->nif.elsepart) {
  3937. cmdtxt(n->nif.ifpart);
  3938. cmdputs("; else ");
  3939. n = n->nif.elsepart;
  3940. } else {
  3941. n = n->nif.ifpart;
  3942. }
  3943. p = "; fi";
  3944. goto dotail;
  3945. case NSUBSHELL:
  3946. cmdputs("(");
  3947. n = n->nredir.n;
  3948. p = ")";
  3949. goto dotail;
  3950. case NWHILE:
  3951. p = "while ";
  3952. goto until;
  3953. case NUNTIL:
  3954. p = "until ";
  3955. until:
  3956. cmdputs(p);
  3957. cmdtxt(n->nbinary.ch1);
  3958. n = n->nbinary.ch2;
  3959. p = "; done";
  3960. dodo:
  3961. cmdputs("; do ");
  3962. dotail:
  3963. cmdtxt(n);
  3964. goto dotail2;
  3965. case NFOR:
  3966. cmdputs("for ");
  3967. cmdputs(n->nfor.var);
  3968. cmdputs(" in ");
  3969. cmdlist(n->nfor.args, 1);
  3970. n = n->nfor.body;
  3971. p = "; done";
  3972. goto dodo;
  3973. case NDEFUN:
  3974. cmdputs(n->narg.text);
  3975. p = "() { ... }";
  3976. goto dotail2;
  3977. case NCMD:
  3978. cmdlist(n->ncmd.args, 1);
  3979. cmdlist(n->ncmd.redirect, 0);
  3980. break;
  3981. case NARG:
  3982. p = n->narg.text;
  3983. dotail2:
  3984. cmdputs(p);
  3985. break;
  3986. case NHERE:
  3987. case NXHERE:
  3988. p = "<<...";
  3989. goto dotail2;
  3990. case NCASE:
  3991. cmdputs("case ");
  3992. cmdputs(n->ncase.expr->narg.text);
  3993. cmdputs(" in ");
  3994. for (np = n->ncase.cases; np; np = np->nclist.next) {
  3995. cmdtxt(np->nclist.pattern);
  3996. cmdputs(") ");
  3997. cmdtxt(np->nclist.body);
  3998. cmdputs(";; ");
  3999. }
  4000. p = "esac";
  4001. goto dotail2;
  4002. case NTO:
  4003. p = ">";
  4004. goto redir;
  4005. case NCLOBBER:
  4006. p = ">|";
  4007. goto redir;
  4008. case NAPPEND:
  4009. p = ">>";
  4010. goto redir;
  4011. #if ENABLE_ASH_BASH_COMPAT
  4012. case NTO2:
  4013. #endif
  4014. case NTOFD:
  4015. p = ">&";
  4016. goto redir;
  4017. case NFROM:
  4018. p = "<";
  4019. goto redir;
  4020. case NFROMFD:
  4021. p = "<&";
  4022. goto redir;
  4023. case NFROMTO:
  4024. p = "<>";
  4025. redir:
  4026. cmdputs(utoa(n->nfile.fd));
  4027. cmdputs(p);
  4028. if (n->type == NTOFD || n->type == NFROMFD) {
  4029. cmdputs(utoa(n->ndup.dupfd));
  4030. break;
  4031. }
  4032. n = n->nfile.fname;
  4033. goto donode;
  4034. }
  4035. }
  4036. static char *
  4037. commandtext(union node *n)
  4038. {
  4039. char *name;
  4040. STARTSTACKSTR(cmdnextc);
  4041. cmdtxt(n);
  4042. name = stackblock();
  4043. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4044. name, cmdnextc, cmdnextc));
  4045. return ckstrdup(name);
  4046. }
  4047. #endif /* JOBS */
  4048. /*
  4049. * Fork off a subshell. If we are doing job control, give the subshell its
  4050. * own process group. Jp is a job structure that the job is to be added to.
  4051. * N is the command that will be evaluated by the child. Both jp and n may
  4052. * be NULL. The mode parameter can be one of the following:
  4053. * FORK_FG - Fork off a foreground process.
  4054. * FORK_BG - Fork off a background process.
  4055. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4056. * process group even if job control is on.
  4057. *
  4058. * When job control is turned off, background processes have their standard
  4059. * input redirected to /dev/null (except for the second and later processes
  4060. * in a pipeline).
  4061. *
  4062. * Called with interrupts off.
  4063. */
  4064. /*
  4065. * Clear traps on a fork.
  4066. */
  4067. static void
  4068. clear_traps(void)
  4069. {
  4070. char **tp;
  4071. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4072. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4073. INT_OFF;
  4074. if (trap_ptr == trap)
  4075. free(*tp);
  4076. /* else: it "belongs" to trap_ptr vector, don't free */
  4077. *tp = NULL;
  4078. if ((tp - trap) != 0)
  4079. setsignal(tp - trap);
  4080. INT_ON;
  4081. }
  4082. }
  4083. }
  4084. /* Lives far away from here, needed for forkchild */
  4085. static void closescript(void);
  4086. /* Called after fork(), in child */
  4087. static NOINLINE void
  4088. forkchild(struct job *jp, union node *n, int mode)
  4089. {
  4090. int oldlvl;
  4091. TRACE(("Child shell %d\n", getpid()));
  4092. oldlvl = shlvl;
  4093. shlvl++;
  4094. /* man bash: "Non-builtin commands run by bash have signal handlers
  4095. * set to the values inherited by the shell from its parent".
  4096. * Do we do it correctly? */
  4097. closescript();
  4098. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4099. && n && n->type == NCMD /* is it single cmd? */
  4100. /* && n->ncmd.args->type == NARG - always true? */
  4101. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4102. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4103. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4104. ) {
  4105. TRACE(("Trap hack\n"));
  4106. /* Awful hack for `trap` or $(trap).
  4107. *
  4108. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4109. * contains an example where "trap" is executed in a subshell:
  4110. *
  4111. * save_traps=$(trap)
  4112. * ...
  4113. * eval "$save_traps"
  4114. *
  4115. * Standard does not say that "trap" in subshell shall print
  4116. * parent shell's traps. It only says that its output
  4117. * must have suitable form, but then, in the above example
  4118. * (which is not supposed to be normative), it implies that.
  4119. *
  4120. * bash (and probably other shell) does implement it
  4121. * (traps are reset to defaults, but "trap" still shows them),
  4122. * but as a result, "trap" logic is hopelessly messed up:
  4123. *
  4124. * # trap
  4125. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4126. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4127. * # true | trap <--- trap is in subshell - no output (ditto)
  4128. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4129. * trap -- 'echo Ho' SIGWINCH
  4130. * # echo `(trap)` <--- in subshell in subshell - output
  4131. * trap -- 'echo Ho' SIGWINCH
  4132. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4133. * trap -- 'echo Ho' SIGWINCH
  4134. *
  4135. * The rules when to forget and when to not forget traps
  4136. * get really complex and nonsensical.
  4137. *
  4138. * Our solution: ONLY bare $(trap) or `trap` is special.
  4139. */
  4140. /* Save trap handler strings for trap builtin to print */
  4141. trap_ptr = memcpy(xmalloc(sizeof(trap)), trap, sizeof(trap));
  4142. /* Fall through into clearing traps */
  4143. }
  4144. clear_traps();
  4145. #if JOBS
  4146. /* do job control only in root shell */
  4147. doing_jobctl = 0;
  4148. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  4149. pid_t pgrp;
  4150. if (jp->nprocs == 0)
  4151. pgrp = getpid();
  4152. else
  4153. pgrp = jp->ps[0].ps_pid;
  4154. /* this can fail because we are doing it in the parent also */
  4155. setpgid(0, pgrp);
  4156. if (mode == FORK_FG)
  4157. xtcsetpgrp(ttyfd, pgrp);
  4158. setsignal(SIGTSTP);
  4159. setsignal(SIGTTOU);
  4160. } else
  4161. #endif
  4162. if (mode == FORK_BG) {
  4163. /* man bash: "When job control is not in effect,
  4164. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4165. ignoresig(SIGINT);
  4166. ignoresig(SIGQUIT);
  4167. if (jp->nprocs == 0) {
  4168. close(0);
  4169. if (open(bb_dev_null, O_RDONLY) != 0)
  4170. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4171. }
  4172. }
  4173. if (!oldlvl) {
  4174. if (iflag) { /* why if iflag only? */
  4175. setsignal(SIGINT);
  4176. setsignal(SIGTERM);
  4177. }
  4178. /* man bash:
  4179. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4180. * commands run by bash have signal handlers
  4181. * set to the values inherited by the shell
  4182. * from its parent".
  4183. * Take care of the second rule: */
  4184. setsignal(SIGQUIT);
  4185. }
  4186. #if JOBS
  4187. if (n && n->type == NCMD
  4188. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4189. ) {
  4190. TRACE(("Job hack\n"));
  4191. /* "jobs": we do not want to clear job list for it,
  4192. * instead we remove only _its_ own_ job from job list.
  4193. * This makes "jobs .... | cat" more useful.
  4194. */
  4195. freejob(curjob);
  4196. return;
  4197. }
  4198. #endif
  4199. for (jp = curjob; jp; jp = jp->prev_job)
  4200. freejob(jp);
  4201. jobless = 0;
  4202. }
  4203. /* Called after fork(), in parent */
  4204. #if !JOBS
  4205. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4206. #endif
  4207. static void
  4208. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4209. {
  4210. TRACE(("In parent shell: child = %d\n", pid));
  4211. if (!jp) {
  4212. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4213. continue;
  4214. jobless++;
  4215. return;
  4216. }
  4217. #if JOBS
  4218. if (mode != FORK_NOJOB && jp->jobctl) {
  4219. int pgrp;
  4220. if (jp->nprocs == 0)
  4221. pgrp = pid;
  4222. else
  4223. pgrp = jp->ps[0].ps_pid;
  4224. /* This can fail because we are doing it in the child also */
  4225. setpgid(pid, pgrp);
  4226. }
  4227. #endif
  4228. if (mode == FORK_BG) {
  4229. backgndpid = pid; /* set $! */
  4230. set_curjob(jp, CUR_RUNNING);
  4231. }
  4232. if (jp) {
  4233. struct procstat *ps = &jp->ps[jp->nprocs++];
  4234. ps->ps_pid = pid;
  4235. ps->ps_status = -1;
  4236. ps->ps_cmd = nullstr;
  4237. #if JOBS
  4238. if (doing_jobctl && n)
  4239. ps->ps_cmd = commandtext(n);
  4240. #endif
  4241. }
  4242. }
  4243. static int
  4244. forkshell(struct job *jp, union node *n, int mode)
  4245. {
  4246. int pid;
  4247. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4248. pid = fork();
  4249. if (pid < 0) {
  4250. TRACE(("Fork failed, errno=%d", errno));
  4251. if (jp)
  4252. freejob(jp);
  4253. ash_msg_and_raise_error("can't fork");
  4254. }
  4255. if (pid == 0) {
  4256. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4257. forkchild(jp, n, mode);
  4258. } else {
  4259. forkparent(jp, n, mode, pid);
  4260. }
  4261. return pid;
  4262. }
  4263. /*
  4264. * Wait for job to finish.
  4265. *
  4266. * Under job control we have the problem that while a child process
  4267. * is running interrupts generated by the user are sent to the child
  4268. * but not to the shell. This means that an infinite loop started by
  4269. * an interactive user may be hard to kill. With job control turned off,
  4270. * an interactive user may place an interactive program inside a loop.
  4271. * If the interactive program catches interrupts, the user doesn't want
  4272. * these interrupts to also abort the loop. The approach we take here
  4273. * is to have the shell ignore interrupt signals while waiting for a
  4274. * foreground process to terminate, and then send itself an interrupt
  4275. * signal if the child process was terminated by an interrupt signal.
  4276. * Unfortunately, some programs want to do a bit of cleanup and then
  4277. * exit on interrupt; unless these processes terminate themselves by
  4278. * sending a signal to themselves (instead of calling exit) they will
  4279. * confuse this approach.
  4280. *
  4281. * Called with interrupts off.
  4282. */
  4283. static int
  4284. waitforjob(struct job *jp)
  4285. {
  4286. int st;
  4287. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4288. INT_OFF;
  4289. while (jp->state == JOBRUNNING) {
  4290. /* In non-interactive shells, we _can_ get
  4291. * a keyboard signal here and be EINTRed,
  4292. * but we just loop back, waiting for command to complete.
  4293. *
  4294. * man bash:
  4295. * "If bash is waiting for a command to complete and receives
  4296. * a signal for which a trap has been set, the trap
  4297. * will not be executed until the command completes."
  4298. *
  4299. * Reality is that even if trap is not set, bash
  4300. * will not act on the signal until command completes.
  4301. * Try this. sleep5intoff.c:
  4302. * #include <signal.h>
  4303. * #include <unistd.h>
  4304. * int main() {
  4305. * sigset_t set;
  4306. * sigemptyset(&set);
  4307. * sigaddset(&set, SIGINT);
  4308. * sigaddset(&set, SIGQUIT);
  4309. * sigprocmask(SIG_BLOCK, &set, NULL);
  4310. * sleep(5);
  4311. * return 0;
  4312. * }
  4313. * $ bash -c './sleep5intoff; echo hi'
  4314. * ^C^C^C^C <--- pressing ^C once a second
  4315. * $ _
  4316. * $ bash -c './sleep5intoff; echo hi'
  4317. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4318. * $ _
  4319. */
  4320. dowait(DOWAIT_BLOCK, jp);
  4321. }
  4322. INT_ON;
  4323. st = getstatus(jp);
  4324. #if JOBS
  4325. if (jp->jobctl) {
  4326. xtcsetpgrp(ttyfd, rootpid);
  4327. /*
  4328. * This is truly gross.
  4329. * If we're doing job control, then we did a TIOCSPGRP which
  4330. * caused us (the shell) to no longer be in the controlling
  4331. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4332. * intuit from the subprocess exit status whether a SIGINT
  4333. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4334. */
  4335. if (jp->sigint) /* TODO: do the same with all signals */
  4336. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4337. }
  4338. if (jp->state == JOBDONE)
  4339. #endif
  4340. freejob(jp);
  4341. return st;
  4342. }
  4343. /*
  4344. * return 1 if there are stopped jobs, otherwise 0
  4345. */
  4346. static int
  4347. stoppedjobs(void)
  4348. {
  4349. struct job *jp;
  4350. int retval;
  4351. retval = 0;
  4352. if (job_warning)
  4353. goto out;
  4354. jp = curjob;
  4355. if (jp && jp->state == JOBSTOPPED) {
  4356. out2str("You have stopped jobs.\n");
  4357. job_warning = 2;
  4358. retval++;
  4359. }
  4360. out:
  4361. return retval;
  4362. }
  4363. /* ============ redir.c
  4364. *
  4365. * Code for dealing with input/output redirection.
  4366. */
  4367. #define EMPTY -2 /* marks an unused slot in redirtab */
  4368. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4369. /*
  4370. * Open a file in noclobber mode.
  4371. * The code was copied from bash.
  4372. */
  4373. static int
  4374. noclobberopen(const char *fname)
  4375. {
  4376. int r, fd;
  4377. struct stat finfo, finfo2;
  4378. /*
  4379. * If the file exists and is a regular file, return an error
  4380. * immediately.
  4381. */
  4382. r = stat(fname, &finfo);
  4383. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4384. errno = EEXIST;
  4385. return -1;
  4386. }
  4387. /*
  4388. * If the file was not present (r != 0), make sure we open it
  4389. * exclusively so that if it is created before we open it, our open
  4390. * will fail. Make sure that we do not truncate an existing file.
  4391. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4392. * file was not a regular file, we leave O_EXCL off.
  4393. */
  4394. if (r != 0)
  4395. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4396. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4397. /* If the open failed, return the file descriptor right away. */
  4398. if (fd < 0)
  4399. return fd;
  4400. /*
  4401. * OK, the open succeeded, but the file may have been changed from a
  4402. * non-regular file to a regular file between the stat and the open.
  4403. * We are assuming that the O_EXCL open handles the case where FILENAME
  4404. * did not exist and is symlinked to an existing file between the stat
  4405. * and open.
  4406. */
  4407. /*
  4408. * If we can open it and fstat the file descriptor, and neither check
  4409. * revealed that it was a regular file, and the file has not been
  4410. * replaced, return the file descriptor.
  4411. */
  4412. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4413. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4414. return fd;
  4415. /* The file has been replaced. badness. */
  4416. close(fd);
  4417. errno = EEXIST;
  4418. return -1;
  4419. }
  4420. /*
  4421. * Handle here documents. Normally we fork off a process to write the
  4422. * data to a pipe. If the document is short, we can stuff the data in
  4423. * the pipe without forking.
  4424. */
  4425. /* openhere needs this forward reference */
  4426. static void expandhere(union node *arg, int fd);
  4427. static int
  4428. openhere(union node *redir)
  4429. {
  4430. int pip[2];
  4431. size_t len = 0;
  4432. if (pipe(pip) < 0)
  4433. ash_msg_and_raise_error("pipe call failed");
  4434. if (redir->type == NHERE) {
  4435. len = strlen(redir->nhere.doc->narg.text);
  4436. if (len <= PIPE_BUF) {
  4437. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4438. goto out;
  4439. }
  4440. }
  4441. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4442. /* child */
  4443. close(pip[0]);
  4444. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4445. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4446. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4447. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4448. signal(SIGPIPE, SIG_DFL);
  4449. if (redir->type == NHERE)
  4450. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4451. else /* NXHERE */
  4452. expandhere(redir->nhere.doc, pip[1]);
  4453. _exit(EXIT_SUCCESS);
  4454. }
  4455. out:
  4456. close(pip[1]);
  4457. return pip[0];
  4458. }
  4459. static int
  4460. openredirect(union node *redir)
  4461. {
  4462. char *fname;
  4463. int f;
  4464. switch (redir->nfile.type) {
  4465. case NFROM:
  4466. fname = redir->nfile.expfname;
  4467. f = open(fname, O_RDONLY);
  4468. if (f < 0)
  4469. goto eopen;
  4470. break;
  4471. case NFROMTO:
  4472. fname = redir->nfile.expfname;
  4473. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4474. if (f < 0)
  4475. goto ecreate;
  4476. break;
  4477. case NTO:
  4478. #if ENABLE_ASH_BASH_COMPAT
  4479. case NTO2:
  4480. #endif
  4481. /* Take care of noclobber mode. */
  4482. if (Cflag) {
  4483. fname = redir->nfile.expfname;
  4484. f = noclobberopen(fname);
  4485. if (f < 0)
  4486. goto ecreate;
  4487. break;
  4488. }
  4489. /* FALLTHROUGH */
  4490. case NCLOBBER:
  4491. fname = redir->nfile.expfname;
  4492. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4493. if (f < 0)
  4494. goto ecreate;
  4495. break;
  4496. case NAPPEND:
  4497. fname = redir->nfile.expfname;
  4498. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4499. if (f < 0)
  4500. goto ecreate;
  4501. break;
  4502. default:
  4503. #if DEBUG
  4504. abort();
  4505. #endif
  4506. /* Fall through to eliminate warning. */
  4507. /* Our single caller does this itself */
  4508. // case NTOFD:
  4509. // case NFROMFD:
  4510. // f = -1;
  4511. // break;
  4512. case NHERE:
  4513. case NXHERE:
  4514. f = openhere(redir);
  4515. break;
  4516. }
  4517. return f;
  4518. ecreate:
  4519. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4520. eopen:
  4521. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4522. }
  4523. /*
  4524. * Copy a file descriptor to be >= to. Returns -1
  4525. * if the source file descriptor is closed, EMPTY if there are no unused
  4526. * file descriptors left.
  4527. */
  4528. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4529. * old code was doing close(to) prior to copyfd() to achieve the same */
  4530. enum {
  4531. COPYFD_EXACT = (int)~(INT_MAX),
  4532. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4533. };
  4534. static int
  4535. copyfd(int from, int to)
  4536. {
  4537. int newfd;
  4538. if (to & COPYFD_EXACT) {
  4539. to &= ~COPYFD_EXACT;
  4540. /*if (from != to)*/
  4541. newfd = dup2(from, to);
  4542. } else {
  4543. newfd = fcntl(from, F_DUPFD, to);
  4544. }
  4545. if (newfd < 0) {
  4546. if (errno == EMFILE)
  4547. return EMPTY;
  4548. /* Happens when source fd is not open: try "echo >&99" */
  4549. ash_msg_and_raise_error("%d: %m", from);
  4550. }
  4551. return newfd;
  4552. }
  4553. /* Struct def and variable are moved down to the first usage site */
  4554. struct two_fd_t {
  4555. int orig, copy;
  4556. };
  4557. struct redirtab {
  4558. struct redirtab *next;
  4559. int nullredirs;
  4560. int pair_count;
  4561. struct two_fd_t two_fd[];
  4562. };
  4563. #define redirlist (G_var.redirlist)
  4564. static int need_to_remember(struct redirtab *rp, int fd)
  4565. {
  4566. int i;
  4567. if (!rp) /* remembering was not requested */
  4568. return 0;
  4569. for (i = 0; i < rp->pair_count; i++) {
  4570. if (rp->two_fd[i].orig == fd) {
  4571. /* already remembered */
  4572. return 0;
  4573. }
  4574. }
  4575. return 1;
  4576. }
  4577. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4578. static int is_hidden_fd(struct redirtab *rp, int fd)
  4579. {
  4580. int i;
  4581. struct parsefile *pf;
  4582. if (fd == -1)
  4583. return 0;
  4584. pf = g_parsefile;
  4585. while (pf) {
  4586. if (pf->fd > 0 && fd == pf->fd) {
  4587. return 1;
  4588. }
  4589. pf = pf->prev;
  4590. }
  4591. if (!rp)
  4592. return 0;
  4593. fd |= COPYFD_RESTORE;
  4594. for (i = 0; i < rp->pair_count; i++) {
  4595. if (rp->two_fd[i].copy == fd) {
  4596. return 1;
  4597. }
  4598. }
  4599. return 0;
  4600. }
  4601. /*
  4602. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4603. * old file descriptors are stashed away so that the redirection can be
  4604. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4605. * standard output, and the standard error if it becomes a duplicate of
  4606. * stdout, is saved in memory.
  4607. */
  4608. /* flags passed to redirect */
  4609. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4610. #define REDIR_SAVEFD2 03 /* set preverrout */
  4611. static void
  4612. redirect(union node *redir, int flags)
  4613. {
  4614. struct redirtab *sv;
  4615. int sv_pos;
  4616. int i;
  4617. int fd;
  4618. int newfd;
  4619. int copied_fd2 = -1;
  4620. g_nullredirs++;
  4621. if (!redir) {
  4622. return;
  4623. }
  4624. sv = NULL;
  4625. sv_pos = 0;
  4626. INT_OFF;
  4627. if (flags & REDIR_PUSH) {
  4628. union node *tmp = redir;
  4629. do {
  4630. sv_pos++;
  4631. #if ENABLE_ASH_BASH_COMPAT
  4632. if (tmp->nfile.type == NTO2)
  4633. sv_pos++;
  4634. #endif
  4635. tmp = tmp->nfile.next;
  4636. } while (tmp);
  4637. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4638. sv->next = redirlist;
  4639. sv->pair_count = sv_pos;
  4640. redirlist = sv;
  4641. sv->nullredirs = g_nullredirs - 1;
  4642. g_nullredirs = 0;
  4643. while (sv_pos > 0) {
  4644. sv_pos--;
  4645. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4646. }
  4647. }
  4648. do {
  4649. fd = redir->nfile.fd;
  4650. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4651. int right_fd = redir->ndup.dupfd;
  4652. /* redirect from/to same file descriptor? */
  4653. if (right_fd == fd)
  4654. continue;
  4655. /* echo >&10 and 10 is a fd opened to the sh script? */
  4656. if (is_hidden_fd(sv, right_fd)) {
  4657. errno = EBADF; /* as if it is closed */
  4658. ash_msg_and_raise_error("%d: %m", right_fd);
  4659. }
  4660. newfd = -1;
  4661. } else {
  4662. newfd = openredirect(redir); /* always >= 0 */
  4663. if (fd == newfd) {
  4664. /* Descriptor wasn't open before redirect.
  4665. * Mark it for close in the future */
  4666. if (need_to_remember(sv, fd)) {
  4667. goto remember_to_close;
  4668. }
  4669. continue;
  4670. }
  4671. }
  4672. #if ENABLE_ASH_BASH_COMPAT
  4673. redirect_more:
  4674. #endif
  4675. if (need_to_remember(sv, fd)) {
  4676. /* Copy old descriptor */
  4677. i = fcntl(fd, F_DUPFD, 10);
  4678. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4679. * are closed in popredir() in the child, preventing them from leaking
  4680. * into child. (popredir() also cleans up the mess in case of failures)
  4681. */
  4682. if (i == -1) {
  4683. i = errno;
  4684. if (i != EBADF) {
  4685. /* Strange error (e.g. "too many files" EMFILE?) */
  4686. if (newfd >= 0)
  4687. close(newfd);
  4688. errno = i;
  4689. ash_msg_and_raise_error("%d: %m", fd);
  4690. /* NOTREACHED */
  4691. }
  4692. /* EBADF: it is not open - good, remember to close it */
  4693. remember_to_close:
  4694. i = CLOSED;
  4695. } else { /* fd is open, save its copy */
  4696. /* "exec fd>&-" should not close fds
  4697. * which point to script file(s).
  4698. * Force them to be restored afterwards */
  4699. if (is_hidden_fd(sv, fd))
  4700. i |= COPYFD_RESTORE;
  4701. }
  4702. if (fd == 2)
  4703. copied_fd2 = i;
  4704. sv->two_fd[sv_pos].orig = fd;
  4705. sv->two_fd[sv_pos].copy = i;
  4706. sv_pos++;
  4707. }
  4708. if (newfd < 0) {
  4709. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4710. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4711. /* Don't want to trigger debugging */
  4712. if (fd != -1)
  4713. close(fd);
  4714. } else {
  4715. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4716. }
  4717. } else if (fd != newfd) { /* move newfd to fd */
  4718. copyfd(newfd, fd | COPYFD_EXACT);
  4719. #if ENABLE_ASH_BASH_COMPAT
  4720. if (!(redir->nfile.type == NTO2 && fd == 2))
  4721. #endif
  4722. close(newfd);
  4723. }
  4724. #if ENABLE_ASH_BASH_COMPAT
  4725. if (redir->nfile.type == NTO2 && fd == 1) {
  4726. /* We already redirected it to fd 1, now copy it to 2 */
  4727. newfd = 1;
  4728. fd = 2;
  4729. goto redirect_more;
  4730. }
  4731. #endif
  4732. } while ((redir = redir->nfile.next) != NULL);
  4733. INT_ON;
  4734. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4735. preverrout_fd = copied_fd2;
  4736. }
  4737. /*
  4738. * Undo the effects of the last redirection.
  4739. */
  4740. static void
  4741. popredir(int drop, int restore)
  4742. {
  4743. struct redirtab *rp;
  4744. int i;
  4745. if (--g_nullredirs >= 0)
  4746. return;
  4747. INT_OFF;
  4748. rp = redirlist;
  4749. for (i = 0; i < rp->pair_count; i++) {
  4750. int fd = rp->two_fd[i].orig;
  4751. int copy = rp->two_fd[i].copy;
  4752. if (copy == CLOSED) {
  4753. if (!drop)
  4754. close(fd);
  4755. continue;
  4756. }
  4757. if (copy != EMPTY) {
  4758. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4759. copy &= ~COPYFD_RESTORE;
  4760. /*close(fd);*/
  4761. copyfd(copy, fd | COPYFD_EXACT);
  4762. }
  4763. close(copy & ~COPYFD_RESTORE);
  4764. }
  4765. }
  4766. redirlist = rp->next;
  4767. g_nullredirs = rp->nullredirs;
  4768. free(rp);
  4769. INT_ON;
  4770. }
  4771. /*
  4772. * Undo all redirections. Called on error or interrupt.
  4773. */
  4774. /*
  4775. * Discard all saved file descriptors.
  4776. */
  4777. static void
  4778. clearredir(int drop)
  4779. {
  4780. for (;;) {
  4781. g_nullredirs = 0;
  4782. if (!redirlist)
  4783. break;
  4784. popredir(drop, /*restore:*/ 0);
  4785. }
  4786. }
  4787. static int
  4788. redirectsafe(union node *redir, int flags)
  4789. {
  4790. int err;
  4791. volatile int saveint;
  4792. struct jmploc *volatile savehandler = exception_handler;
  4793. struct jmploc jmploc;
  4794. SAVE_INT(saveint);
  4795. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4796. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4797. if (!err) {
  4798. exception_handler = &jmploc;
  4799. redirect(redir, flags);
  4800. }
  4801. exception_handler = savehandler;
  4802. if (err && exception_type != EXERROR)
  4803. longjmp(exception_handler->loc, 1);
  4804. RESTORE_INT(saveint);
  4805. return err;
  4806. }
  4807. /* ============ Routines to expand arguments to commands
  4808. *
  4809. * We have to deal with backquotes, shell variables, and file metacharacters.
  4810. */
  4811. #if ENABLE_SH_MATH_SUPPORT
  4812. static arith_t
  4813. ash_arith(const char *s)
  4814. {
  4815. arith_eval_hooks_t math_hooks;
  4816. arith_t result;
  4817. int errcode = 0;
  4818. math_hooks.lookupvar = lookupvar;
  4819. math_hooks.setvar = setvar2;
  4820. math_hooks.endofname = endofname;
  4821. INT_OFF;
  4822. result = arith(s, &errcode, &math_hooks);
  4823. if (errcode < 0) {
  4824. if (errcode == -3)
  4825. ash_msg_and_raise_error("exponent less than 0");
  4826. if (errcode == -2)
  4827. ash_msg_and_raise_error("divide by zero");
  4828. if (errcode == -5)
  4829. ash_msg_and_raise_error("expression recursion loop detected");
  4830. raise_error_syntax(s);
  4831. }
  4832. INT_ON;
  4833. return result;
  4834. }
  4835. #endif
  4836. /*
  4837. * expandarg flags
  4838. */
  4839. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4840. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4841. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4842. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4843. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4844. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4845. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4846. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4847. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4848. /*
  4849. * rmescape() flags
  4850. */
  4851. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4852. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4853. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4854. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4855. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4856. /*
  4857. * Structure specifying which parts of the string should be searched
  4858. * for IFS characters.
  4859. */
  4860. struct ifsregion {
  4861. struct ifsregion *next; /* next region in list */
  4862. int begoff; /* offset of start of region */
  4863. int endoff; /* offset of end of region */
  4864. int nulonly; /* search for nul bytes only */
  4865. };
  4866. struct arglist {
  4867. struct strlist *list;
  4868. struct strlist **lastp;
  4869. };
  4870. /* output of current string */
  4871. static char *expdest;
  4872. /* list of back quote expressions */
  4873. static struct nodelist *argbackq;
  4874. /* first struct in list of ifs regions */
  4875. static struct ifsregion ifsfirst;
  4876. /* last struct in list */
  4877. static struct ifsregion *ifslastp;
  4878. /* holds expanded arg list */
  4879. static struct arglist exparg;
  4880. /*
  4881. * Our own itoa().
  4882. */
  4883. static int
  4884. cvtnum(arith_t num)
  4885. {
  4886. int len;
  4887. expdest = makestrspace(32, expdest);
  4888. len = fmtstr(expdest, 32, arith_t_fmt, num);
  4889. STADJUST(len, expdest);
  4890. return len;
  4891. }
  4892. static size_t
  4893. esclen(const char *start, const char *p)
  4894. {
  4895. size_t esc = 0;
  4896. while (p > start && (unsigned char)*--p == CTLESC) {
  4897. esc++;
  4898. }
  4899. return esc;
  4900. }
  4901. /*
  4902. * Remove any CTLESC characters from a string.
  4903. */
  4904. static char *
  4905. rmescapes(char *str, int flag)
  4906. {
  4907. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4908. char *p, *q, *r;
  4909. unsigned inquotes;
  4910. unsigned protect_against_glob;
  4911. unsigned globbing;
  4912. p = strpbrk(str, qchars);
  4913. if (!p)
  4914. return str;
  4915. q = p;
  4916. r = str;
  4917. if (flag & RMESCAPE_ALLOC) {
  4918. size_t len = p - str;
  4919. size_t fulllen = len + strlen(p) + 1;
  4920. if (flag & RMESCAPE_GROW) {
  4921. int strloc = str - (char *)stackblock();
  4922. r = makestrspace(fulllen, expdest);
  4923. /* p and str may be invalidated by makestrspace */
  4924. str = (char *)stackblock() + strloc;
  4925. p = str + len;
  4926. } else if (flag & RMESCAPE_HEAP) {
  4927. r = ckmalloc(fulllen);
  4928. } else {
  4929. r = stalloc(fulllen);
  4930. }
  4931. q = r;
  4932. if (len > 0) {
  4933. q = (char *)memcpy(q, str, len) + len;
  4934. }
  4935. }
  4936. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4937. globbing = flag & RMESCAPE_GLOB;
  4938. protect_against_glob = globbing;
  4939. while (*p) {
  4940. if ((unsigned char)*p == CTLQUOTEMARK) {
  4941. // TODO: if no RMESCAPE_QUOTED in flags, inquotes never becomes 0
  4942. // (alternates between RMESCAPE_QUOTED and ~RMESCAPE_QUOTED). Is it ok?
  4943. // Note: both inquotes and protect_against_glob only affect whether
  4944. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  4945. inquotes = ~inquotes;
  4946. p++;
  4947. protect_against_glob = globbing;
  4948. continue;
  4949. }
  4950. if (*p == '\\') {
  4951. /* naked back slash */
  4952. protect_against_glob = 0;
  4953. goto copy;
  4954. }
  4955. if ((unsigned char)*p == CTLESC) {
  4956. p++;
  4957. if (protect_against_glob && inquotes && *p != '/') {
  4958. *q++ = '\\';
  4959. }
  4960. }
  4961. protect_against_glob = globbing;
  4962. copy:
  4963. *q++ = *p++;
  4964. }
  4965. *q = '\0';
  4966. if (flag & RMESCAPE_GROW) {
  4967. expdest = r;
  4968. STADJUST(q - r + 1, expdest);
  4969. }
  4970. return r;
  4971. }
  4972. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4973. /*
  4974. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4975. *
  4976. * Returns an stalloced string.
  4977. */
  4978. static char *
  4979. preglob(const char *pattern, int quoted, int flag)
  4980. {
  4981. flag |= RMESCAPE_GLOB;
  4982. if (quoted) {
  4983. flag |= RMESCAPE_QUOTED;
  4984. }
  4985. return rmescapes((char *)pattern, flag);
  4986. }
  4987. /*
  4988. * Put a string on the stack.
  4989. */
  4990. static void
  4991. memtodest(const char *p, size_t len, int syntax, int quotes)
  4992. {
  4993. char *q = expdest;
  4994. q = makestrspace(quotes ? len * 2 : len, q);
  4995. while (len--) {
  4996. unsigned char c = *p++;
  4997. if (c == '\0')
  4998. continue;
  4999. if (quotes) {
  5000. int n = SIT(c, syntax);
  5001. if (n == CCTL || n == CBACK)
  5002. USTPUTC(CTLESC, q);
  5003. }
  5004. USTPUTC(c, q);
  5005. }
  5006. expdest = q;
  5007. }
  5008. static void
  5009. strtodest(const char *p, int syntax, int quotes)
  5010. {
  5011. memtodest(p, strlen(p), syntax, quotes);
  5012. }
  5013. /*
  5014. * Record the fact that we have to scan this region of the
  5015. * string for IFS characters.
  5016. */
  5017. static void
  5018. recordregion(int start, int end, int nulonly)
  5019. {
  5020. struct ifsregion *ifsp;
  5021. if (ifslastp == NULL) {
  5022. ifsp = &ifsfirst;
  5023. } else {
  5024. INT_OFF;
  5025. ifsp = ckzalloc(sizeof(*ifsp));
  5026. /*ifsp->next = NULL; - ckzalloc did it */
  5027. ifslastp->next = ifsp;
  5028. INT_ON;
  5029. }
  5030. ifslastp = ifsp;
  5031. ifslastp->begoff = start;
  5032. ifslastp->endoff = end;
  5033. ifslastp->nulonly = nulonly;
  5034. }
  5035. static void
  5036. removerecordregions(int endoff)
  5037. {
  5038. if (ifslastp == NULL)
  5039. return;
  5040. if (ifsfirst.endoff > endoff) {
  5041. while (ifsfirst.next != NULL) {
  5042. struct ifsregion *ifsp;
  5043. INT_OFF;
  5044. ifsp = ifsfirst.next->next;
  5045. free(ifsfirst.next);
  5046. ifsfirst.next = ifsp;
  5047. INT_ON;
  5048. }
  5049. if (ifsfirst.begoff > endoff)
  5050. ifslastp = NULL;
  5051. else {
  5052. ifslastp = &ifsfirst;
  5053. ifsfirst.endoff = endoff;
  5054. }
  5055. return;
  5056. }
  5057. ifslastp = &ifsfirst;
  5058. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5059. ifslastp=ifslastp->next;
  5060. while (ifslastp->next != NULL) {
  5061. struct ifsregion *ifsp;
  5062. INT_OFF;
  5063. ifsp = ifslastp->next->next;
  5064. free(ifslastp->next);
  5065. ifslastp->next = ifsp;
  5066. INT_ON;
  5067. }
  5068. if (ifslastp->endoff > endoff)
  5069. ifslastp->endoff = endoff;
  5070. }
  5071. static char *
  5072. exptilde(char *startp, char *p, int flags)
  5073. {
  5074. unsigned char c;
  5075. char *name;
  5076. struct passwd *pw;
  5077. const char *home;
  5078. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5079. int startloc;
  5080. name = p + 1;
  5081. while ((c = *++p) != '\0') {
  5082. switch (c) {
  5083. case CTLESC:
  5084. return startp;
  5085. case CTLQUOTEMARK:
  5086. return startp;
  5087. case ':':
  5088. if (flags & EXP_VARTILDE)
  5089. goto done;
  5090. break;
  5091. case '/':
  5092. case CTLENDVAR:
  5093. goto done;
  5094. }
  5095. }
  5096. done:
  5097. *p = '\0';
  5098. if (*name == '\0') {
  5099. home = lookupvar(homestr);
  5100. } else {
  5101. pw = getpwnam(name);
  5102. if (pw == NULL)
  5103. goto lose;
  5104. home = pw->pw_dir;
  5105. }
  5106. if (!home || !*home)
  5107. goto lose;
  5108. *p = c;
  5109. startloc = expdest - (char *)stackblock();
  5110. strtodest(home, SQSYNTAX, quotes);
  5111. recordregion(startloc, expdest - (char *)stackblock(), 0);
  5112. return p;
  5113. lose:
  5114. *p = c;
  5115. return startp;
  5116. }
  5117. /*
  5118. * Execute a command inside back quotes. If it's a builtin command, we
  5119. * want to save its output in a block obtained from malloc. Otherwise
  5120. * we fork off a subprocess and get the output of the command via a pipe.
  5121. * Should be called with interrupts off.
  5122. */
  5123. struct backcmd { /* result of evalbackcmd */
  5124. int fd; /* file descriptor to read from */
  5125. int nleft; /* number of chars in buffer */
  5126. char *buf; /* buffer */
  5127. struct job *jp; /* job structure for command */
  5128. };
  5129. /* These forward decls are needed to use "eval" code for backticks handling: */
  5130. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5131. #define EV_EXIT 01 /* exit after evaluating tree */
  5132. static void evaltree(union node *, int);
  5133. static void FAST_FUNC
  5134. evalbackcmd(union node *n, struct backcmd *result)
  5135. {
  5136. int saveherefd;
  5137. result->fd = -1;
  5138. result->buf = NULL;
  5139. result->nleft = 0;
  5140. result->jp = NULL;
  5141. if (n == NULL)
  5142. goto out;
  5143. saveherefd = herefd;
  5144. herefd = -1;
  5145. {
  5146. int pip[2];
  5147. struct job *jp;
  5148. if (pipe(pip) < 0)
  5149. ash_msg_and_raise_error("pipe call failed");
  5150. jp = makejob(/*n,*/ 1);
  5151. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5152. FORCE_INT_ON;
  5153. close(pip[0]);
  5154. if (pip[1] != 1) {
  5155. /*close(1);*/
  5156. copyfd(pip[1], 1 | COPYFD_EXACT);
  5157. close(pip[1]);
  5158. }
  5159. eflag = 0;
  5160. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5161. /* NOTREACHED */
  5162. }
  5163. close(pip[1]);
  5164. result->fd = pip[0];
  5165. result->jp = jp;
  5166. }
  5167. herefd = saveherefd;
  5168. out:
  5169. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5170. result->fd, result->buf, result->nleft, result->jp));
  5171. }
  5172. /*
  5173. * Expand stuff in backwards quotes.
  5174. */
  5175. static void
  5176. expbackq(union node *cmd, int quoted, int quotes)
  5177. {
  5178. struct backcmd in;
  5179. int i;
  5180. char buf[128];
  5181. char *p;
  5182. char *dest;
  5183. int startloc;
  5184. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5185. struct stackmark smark;
  5186. INT_OFF;
  5187. setstackmark(&smark);
  5188. dest = expdest;
  5189. startloc = dest - (char *)stackblock();
  5190. grabstackstr(dest);
  5191. evalbackcmd(cmd, &in);
  5192. popstackmark(&smark);
  5193. p = in.buf;
  5194. i = in.nleft;
  5195. if (i == 0)
  5196. goto read;
  5197. for (;;) {
  5198. memtodest(p, i, syntax, quotes);
  5199. read:
  5200. if (in.fd < 0)
  5201. break;
  5202. i = nonblock_safe_read(in.fd, buf, sizeof(buf));
  5203. TRACE(("expbackq: read returns %d\n", i));
  5204. if (i <= 0)
  5205. break;
  5206. p = buf;
  5207. }
  5208. free(in.buf);
  5209. if (in.fd >= 0) {
  5210. close(in.fd);
  5211. back_exitstatus = waitforjob(in.jp);
  5212. }
  5213. INT_ON;
  5214. /* Eat all trailing newlines */
  5215. dest = expdest;
  5216. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5217. STUNPUTC(dest);
  5218. expdest = dest;
  5219. if (quoted == 0)
  5220. recordregion(startloc, dest - (char *)stackblock(), 0);
  5221. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  5222. (dest - (char *)stackblock()) - startloc,
  5223. (dest - (char *)stackblock()) - startloc,
  5224. stackblock() + startloc));
  5225. }
  5226. #if ENABLE_SH_MATH_SUPPORT
  5227. /*
  5228. * Expand arithmetic expression. Backup to start of expression,
  5229. * evaluate, place result in (backed up) result, adjust string position.
  5230. */
  5231. static void
  5232. expari(int quotes)
  5233. {
  5234. char *p, *start;
  5235. int begoff;
  5236. int flag;
  5237. int len;
  5238. /* ifsfree(); */
  5239. /*
  5240. * This routine is slightly over-complicated for
  5241. * efficiency. Next we scan backwards looking for the
  5242. * start of arithmetic.
  5243. */
  5244. start = stackblock();
  5245. p = expdest - 1;
  5246. *p = '\0';
  5247. p--;
  5248. do {
  5249. int esc;
  5250. while ((unsigned char)*p != CTLARI) {
  5251. p--;
  5252. #if DEBUG
  5253. if (p < start) {
  5254. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5255. }
  5256. #endif
  5257. }
  5258. esc = esclen(start, p);
  5259. if (!(esc % 2)) {
  5260. break;
  5261. }
  5262. p -= esc + 1;
  5263. } while (1);
  5264. begoff = p - start;
  5265. removerecordregions(begoff);
  5266. flag = p[1];
  5267. expdest = p;
  5268. if (quotes)
  5269. rmescapes(p + 2, 0);
  5270. len = cvtnum(ash_arith(p + 2));
  5271. if (flag != '"')
  5272. recordregion(begoff, begoff + len, 0);
  5273. }
  5274. #endif
  5275. /* argstr needs it */
  5276. static char *evalvar(char *p, int flags, struct strlist *var_str_list);
  5277. /*
  5278. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5279. * characters to allow for further processing. Otherwise treat
  5280. * $@ like $* since no splitting will be performed.
  5281. *
  5282. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5283. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5284. * for correct expansion of "B=$A" word.
  5285. */
  5286. static void
  5287. argstr(char *p, int flags, struct strlist *var_str_list)
  5288. {
  5289. static const char spclchars[] ALIGN1 = {
  5290. '=',
  5291. ':',
  5292. CTLQUOTEMARK,
  5293. CTLENDVAR,
  5294. CTLESC,
  5295. CTLVAR,
  5296. CTLBACKQ,
  5297. CTLBACKQ | CTLQUOTE,
  5298. #if ENABLE_SH_MATH_SUPPORT
  5299. CTLENDARI,
  5300. #endif
  5301. '\0'
  5302. };
  5303. const char *reject = spclchars;
  5304. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
  5305. int breakall = flags & EXP_WORD;
  5306. int inquotes;
  5307. size_t length;
  5308. int startloc;
  5309. if (!(flags & EXP_VARTILDE)) {
  5310. reject += 2;
  5311. } else if (flags & EXP_VARTILDE2) {
  5312. reject++;
  5313. }
  5314. inquotes = 0;
  5315. length = 0;
  5316. if (flags & EXP_TILDE) {
  5317. char *q;
  5318. flags &= ~EXP_TILDE;
  5319. tilde:
  5320. q = p;
  5321. if (*q == CTLESC && (flags & EXP_QWORD))
  5322. q++;
  5323. if (*q == '~')
  5324. p = exptilde(p, q, flags);
  5325. }
  5326. start:
  5327. startloc = expdest - (char *)stackblock();
  5328. for (;;) {
  5329. unsigned char c;
  5330. length += strcspn(p + length, reject);
  5331. c = p[length];
  5332. if (c) {
  5333. if (!(c & 0x80)
  5334. #if ENABLE_SH_MATH_SUPPORT
  5335. || c == CTLENDARI
  5336. #endif
  5337. ) {
  5338. /* c == '=' || c == ':' || c == CTLENDARI */
  5339. length++;
  5340. }
  5341. }
  5342. if (length > 0) {
  5343. int newloc;
  5344. expdest = stack_nputstr(p, length, expdest);
  5345. newloc = expdest - (char *)stackblock();
  5346. if (breakall && !inquotes && newloc > startloc) {
  5347. recordregion(startloc, newloc, 0);
  5348. }
  5349. startloc = newloc;
  5350. }
  5351. p += length + 1;
  5352. length = 0;
  5353. switch (c) {
  5354. case '\0':
  5355. goto breakloop;
  5356. case '=':
  5357. if (flags & EXP_VARTILDE2) {
  5358. p--;
  5359. continue;
  5360. }
  5361. flags |= EXP_VARTILDE2;
  5362. reject++;
  5363. /* fall through */
  5364. case ':':
  5365. /*
  5366. * sort of a hack - expand tildes in variable
  5367. * assignments (after the first '=' and after ':'s).
  5368. */
  5369. if (*--p == '~') {
  5370. goto tilde;
  5371. }
  5372. continue;
  5373. }
  5374. switch (c) {
  5375. case CTLENDVAR: /* ??? */
  5376. goto breakloop;
  5377. case CTLQUOTEMARK:
  5378. /* "$@" syntax adherence hack */
  5379. if (!inquotes
  5380. && memcmp(p, dolatstr, 4) == 0
  5381. && ( p[4] == CTLQUOTEMARK
  5382. || (p[4] == CTLENDVAR && p[5] == CTLQUOTEMARK)
  5383. )
  5384. ) {
  5385. p = evalvar(p + 1, flags, /* var_str_list: */ NULL) + 1;
  5386. goto start;
  5387. }
  5388. inquotes = !inquotes;
  5389. addquote:
  5390. if (quotes) {
  5391. p--;
  5392. length++;
  5393. startloc++;
  5394. }
  5395. break;
  5396. case CTLESC:
  5397. startloc++;
  5398. length++;
  5399. goto addquote;
  5400. case CTLVAR:
  5401. p = evalvar(p, flags, var_str_list);
  5402. goto start;
  5403. case CTLBACKQ:
  5404. c = '\0';
  5405. case CTLBACKQ|CTLQUOTE:
  5406. expbackq(argbackq->n, c, quotes);
  5407. argbackq = argbackq->next;
  5408. goto start;
  5409. #if ENABLE_SH_MATH_SUPPORT
  5410. case CTLENDARI:
  5411. p--;
  5412. expari(quotes);
  5413. goto start;
  5414. #endif
  5415. }
  5416. }
  5417. breakloop:
  5418. ;
  5419. }
  5420. static char *
  5421. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
  5422. int zero)
  5423. {
  5424. // This commented out code was added by James Simmons <jsimmons@infradead.org>
  5425. // as part of a larger change when he added support for ${var/a/b}.
  5426. // However, it broke # and % operators:
  5427. //
  5428. //var=ababcdcd
  5429. // ok bad
  5430. //echo ${var#ab} abcdcd abcdcd
  5431. //echo ${var##ab} abcdcd abcdcd
  5432. //echo ${var#a*b} abcdcd ababcdcd (!)
  5433. //echo ${var##a*b} cdcd cdcd
  5434. //echo ${var#?} babcdcd ababcdcd (!)
  5435. //echo ${var##?} babcdcd babcdcd
  5436. //echo ${var#*} ababcdcd babcdcd (!)
  5437. //echo ${var##*}
  5438. //echo ${var%cd} ababcd ababcd
  5439. //echo ${var%%cd} ababcd abab (!)
  5440. //echo ${var%c*d} ababcd ababcd
  5441. //echo ${var%%c*d} abab ababcdcd (!)
  5442. //echo ${var%?} ababcdc ababcdc
  5443. //echo ${var%%?} ababcdc ababcdcd (!)
  5444. //echo ${var%*} ababcdcd ababcdcd
  5445. //echo ${var%%*}
  5446. //
  5447. // Commenting it back out helped. Remove it completely if it really
  5448. // is not needed.
  5449. char *loc, *loc2; //, *full;
  5450. char c;
  5451. loc = startp;
  5452. loc2 = rmesc;
  5453. do {
  5454. int match; // = strlen(str);
  5455. const char *s = loc2;
  5456. c = *loc2;
  5457. if (zero) {
  5458. *loc2 = '\0';
  5459. s = rmesc;
  5460. }
  5461. match = pmatch(str, s); // this line was deleted
  5462. // // chop off end if its '*'
  5463. // full = strrchr(str, '*');
  5464. // if (full && full != str)
  5465. // match--;
  5466. //
  5467. // // If str starts with '*' replace with s.
  5468. // if ((*str == '*') && strlen(s) >= match) {
  5469. // full = xstrdup(s);
  5470. // strncpy(full+strlen(s)-match+1, str+1, match-1);
  5471. // } else
  5472. // full = xstrndup(str, match);
  5473. // match = strncmp(s, full, strlen(full));
  5474. // free(full);
  5475. //
  5476. *loc2 = c;
  5477. if (match) // if (!match)
  5478. return loc;
  5479. if (quotes && (unsigned char)*loc == CTLESC)
  5480. loc++;
  5481. loc++;
  5482. loc2++;
  5483. } while (c);
  5484. return 0;
  5485. }
  5486. static char *
  5487. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5488. int zero)
  5489. {
  5490. int esc = 0;
  5491. char *loc;
  5492. char *loc2;
  5493. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5494. int match;
  5495. char c = *loc2;
  5496. const char *s = loc2;
  5497. if (zero) {
  5498. *loc2 = '\0';
  5499. s = rmesc;
  5500. }
  5501. match = pmatch(str, s);
  5502. *loc2 = c;
  5503. if (match)
  5504. return loc;
  5505. loc--;
  5506. if (quotes) {
  5507. if (--esc < 0) {
  5508. esc = esclen(startp, loc);
  5509. }
  5510. if (esc % 2) {
  5511. esc--;
  5512. loc--;
  5513. }
  5514. }
  5515. }
  5516. return 0;
  5517. }
  5518. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5519. static void
  5520. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5521. {
  5522. const char *msg;
  5523. const char *tail;
  5524. tail = nullstr;
  5525. msg = "parameter not set";
  5526. if (umsg) {
  5527. if ((unsigned char)*end == CTLENDVAR) {
  5528. if (varflags & VSNUL)
  5529. tail = " or null";
  5530. } else {
  5531. msg = umsg;
  5532. }
  5533. }
  5534. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5535. }
  5536. #if ENABLE_ASH_BASH_COMPAT
  5537. static char *
  5538. parse_sub_pattern(char *arg, int inquotes)
  5539. {
  5540. char *idx, *repl = NULL;
  5541. unsigned char c;
  5542. idx = arg;
  5543. while (1) {
  5544. c = *arg;
  5545. if (!c)
  5546. break;
  5547. if (c == '/') {
  5548. /* Only the first '/' seen is our separator */
  5549. if (!repl) {
  5550. repl = idx + 1;
  5551. c = '\0';
  5552. }
  5553. }
  5554. *idx++ = c;
  5555. if (!inquotes && c == '\\' && arg[1] == '\\')
  5556. arg++; /* skip both \\, not just first one */
  5557. arg++;
  5558. }
  5559. *idx = c; /* NUL */
  5560. return repl;
  5561. }
  5562. #endif /* ENABLE_ASH_BASH_COMPAT */
  5563. static const char *
  5564. subevalvar(char *p, char *str, int strloc, int subtype,
  5565. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5566. {
  5567. struct nodelist *saveargbackq = argbackq;
  5568. char *startp;
  5569. char *loc;
  5570. char *rmesc, *rmescend;
  5571. IF_ASH_BASH_COMPAT(char *repl = NULL;)
  5572. IF_ASH_BASH_COMPAT(char null = '\0';)
  5573. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5574. int saveherefd = herefd;
  5575. int amount, workloc, resetloc;
  5576. int zero;
  5577. char *(*scan)(char*, char*, char*, char*, int, int);
  5578. herefd = -1;
  5579. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5580. var_str_list);
  5581. STPUTC('\0', expdest);
  5582. herefd = saveherefd;
  5583. argbackq = saveargbackq;
  5584. startp = (char *)stackblock() + startloc;
  5585. switch (subtype) {
  5586. case VSASSIGN:
  5587. setvar(str, startp, 0);
  5588. amount = startp - expdest;
  5589. STADJUST(amount, expdest);
  5590. return startp;
  5591. #if ENABLE_ASH_BASH_COMPAT
  5592. case VSSUBSTR:
  5593. loc = str = stackblock() + strloc;
  5594. /* Read POS in ${var:POS:LEN} */
  5595. pos = atoi(loc); /* number(loc) errors out on "1:4" */
  5596. len = str - startp - 1;
  5597. /* *loc != '\0', guaranteed by parser */
  5598. if (quotes) {
  5599. char *ptr;
  5600. /* Adjust the length by the number of escapes */
  5601. for (ptr = startp; ptr < (str - 1); ptr++) {
  5602. if ((unsigned char)*ptr == CTLESC) {
  5603. len--;
  5604. ptr++;
  5605. }
  5606. }
  5607. }
  5608. orig_len = len;
  5609. if (*loc++ == ':') {
  5610. /* ${var::LEN} */
  5611. len = number(loc);
  5612. } else {
  5613. /* Skip POS in ${var:POS:LEN} */
  5614. len = orig_len;
  5615. while (*loc && *loc != ':') {
  5616. /* TODO?
  5617. * bash complains on: var=qwe; echo ${var:1a:123}
  5618. if (!isdigit(*loc))
  5619. ash_msg_and_raise_error(msg_illnum, str);
  5620. */
  5621. loc++;
  5622. }
  5623. if (*loc++ == ':') {
  5624. len = number(loc);
  5625. }
  5626. }
  5627. if (pos >= orig_len) {
  5628. pos = 0;
  5629. len = 0;
  5630. }
  5631. if (len > (orig_len - pos))
  5632. len = orig_len - pos;
  5633. for (str = startp; pos; str++, pos--) {
  5634. if (quotes && (unsigned char)*str == CTLESC)
  5635. str++;
  5636. }
  5637. for (loc = startp; len; len--) {
  5638. if (quotes && (unsigned char)*str == CTLESC)
  5639. *loc++ = *str++;
  5640. *loc++ = *str++;
  5641. }
  5642. *loc = '\0';
  5643. amount = loc - expdest;
  5644. STADJUST(amount, expdest);
  5645. return loc;
  5646. #endif
  5647. case VSQUESTION:
  5648. varunset(p, str, startp, varflags);
  5649. /* NOTREACHED */
  5650. }
  5651. resetloc = expdest - (char *)stackblock();
  5652. /* We'll comeback here if we grow the stack while handling
  5653. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5654. * stack will need rebasing, and we'll need to remove our work
  5655. * areas each time
  5656. */
  5657. IF_ASH_BASH_COMPAT(restart:)
  5658. amount = expdest - ((char *)stackblock() + resetloc);
  5659. STADJUST(-amount, expdest);
  5660. startp = (char *)stackblock() + startloc;
  5661. rmesc = startp;
  5662. rmescend = (char *)stackblock() + strloc;
  5663. if (quotes) {
  5664. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5665. if (rmesc != startp) {
  5666. rmescend = expdest;
  5667. startp = (char *)stackblock() + startloc;
  5668. }
  5669. }
  5670. rmescend--;
  5671. str = (char *)stackblock() + strloc;
  5672. preglob(str, varflags & VSQUOTE, 0);
  5673. workloc = expdest - (char *)stackblock();
  5674. #if ENABLE_ASH_BASH_COMPAT
  5675. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5676. char *idx, *end, *restart_detect;
  5677. if (!repl) {
  5678. repl = parse_sub_pattern(str, varflags & VSQUOTE);
  5679. if (!repl)
  5680. repl = &null;
  5681. }
  5682. /* If there's no pattern to match, return the expansion unmolested */
  5683. if (*str == '\0')
  5684. return 0;
  5685. len = 0;
  5686. idx = startp;
  5687. end = str - 1;
  5688. while (idx < end) {
  5689. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5690. if (!loc) {
  5691. /* No match, advance */
  5692. restart_detect = stackblock();
  5693. STPUTC(*idx, expdest);
  5694. if (quotes && (unsigned char)*idx == CTLESC) {
  5695. idx++;
  5696. len++;
  5697. STPUTC(*idx, expdest);
  5698. }
  5699. if (stackblock() != restart_detect)
  5700. goto restart;
  5701. idx++;
  5702. len++;
  5703. rmesc++;
  5704. continue;
  5705. }
  5706. if (subtype == VSREPLACEALL) {
  5707. while (idx < loc) {
  5708. if (quotes && (unsigned char)*idx == CTLESC)
  5709. idx++;
  5710. idx++;
  5711. rmesc++;
  5712. }
  5713. } else {
  5714. idx = loc;
  5715. }
  5716. for (loc = repl; *loc; loc++) {
  5717. restart_detect = stackblock();
  5718. STPUTC(*loc, expdest);
  5719. if (stackblock() != restart_detect)
  5720. goto restart;
  5721. len++;
  5722. }
  5723. if (subtype == VSREPLACE) {
  5724. while (*idx) {
  5725. restart_detect = stackblock();
  5726. STPUTC(*idx, expdest);
  5727. if (stackblock() != restart_detect)
  5728. goto restart;
  5729. len++;
  5730. idx++;
  5731. }
  5732. break;
  5733. }
  5734. }
  5735. /* We've put the replaced text into a buffer at workloc, now
  5736. * move it to the right place and adjust the stack.
  5737. */
  5738. startp = stackblock() + startloc;
  5739. STPUTC('\0', expdest);
  5740. memmove(startp, stackblock() + workloc, len);
  5741. startp[len++] = '\0';
  5742. amount = expdest - ((char *)stackblock() + startloc + len - 1);
  5743. STADJUST(-amount, expdest);
  5744. return startp;
  5745. }
  5746. #endif /* ENABLE_ASH_BASH_COMPAT */
  5747. subtype -= VSTRIMRIGHT;
  5748. #if DEBUG
  5749. if (subtype < 0 || subtype > 7)
  5750. abort();
  5751. #endif
  5752. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  5753. zero = subtype >> 1;
  5754. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5755. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5756. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5757. if (loc) {
  5758. if (zero) {
  5759. memmove(startp, loc, str - loc);
  5760. loc = startp + (str - loc) - 1;
  5761. }
  5762. *loc = '\0';
  5763. amount = loc - expdest;
  5764. STADJUST(amount, expdest);
  5765. }
  5766. return loc;
  5767. }
  5768. /*
  5769. * Add the value of a specialized variable to the stack string.
  5770. * name parameter (examples):
  5771. * ash -c 'echo $1' name:'1='
  5772. * ash -c 'echo $qwe' name:'qwe='
  5773. * ash -c 'echo $$' name:'$='
  5774. * ash -c 'echo ${$}' name:'$='
  5775. * ash -c 'echo ${$##q}' name:'$=q'
  5776. * ash -c 'echo ${#$}' name:'$='
  5777. * note: examples with bad shell syntax:
  5778. * ash -c 'echo ${#$1}' name:'$=1'
  5779. * ash -c 'echo ${#1#}' name:'1=#'
  5780. */
  5781. static NOINLINE ssize_t
  5782. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5783. {
  5784. const char *p;
  5785. int num;
  5786. int i;
  5787. int sepq = 0;
  5788. ssize_t len = 0;
  5789. int subtype = varflags & VSTYPE;
  5790. int quotes = flags & (EXP_FULL | EXP_CASE | EXP_REDIR);
  5791. int quoted = varflags & VSQUOTE;
  5792. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5793. switch (*name) {
  5794. case '$':
  5795. num = rootpid;
  5796. goto numvar;
  5797. case '?':
  5798. num = exitstatus;
  5799. goto numvar;
  5800. case '#':
  5801. num = shellparam.nparam;
  5802. goto numvar;
  5803. case '!':
  5804. num = backgndpid;
  5805. if (num == 0)
  5806. return -1;
  5807. numvar:
  5808. len = cvtnum(num);
  5809. goto check_1char_name;
  5810. case '-':
  5811. expdest = makestrspace(NOPTS, expdest);
  5812. for (i = NOPTS - 1; i >= 0; i--) {
  5813. if (optlist[i]) {
  5814. USTPUTC(optletters(i), expdest);
  5815. len++;
  5816. }
  5817. }
  5818. check_1char_name:
  5819. #if 0
  5820. /* handles cases similar to ${#$1} */
  5821. if (name[2] != '\0')
  5822. raise_error_syntax("bad substitution");
  5823. #endif
  5824. break;
  5825. case '@': {
  5826. char **ap;
  5827. int sep;
  5828. if (quoted && (flags & EXP_FULL)) {
  5829. /* note: this is not meant as PEOF value */
  5830. sep = 1 << CHAR_BIT;
  5831. goto param;
  5832. }
  5833. /* fall through */
  5834. case '*':
  5835. sep = ifsset() ? (unsigned char)(ifsval()[0]) : ' ';
  5836. i = SIT(sep, syntax);
  5837. if (quotes && (i == CCTL || i == CBACK))
  5838. sepq = 1;
  5839. param:
  5840. ap = shellparam.p;
  5841. if (!ap)
  5842. return -1;
  5843. while ((p = *ap++) != NULL) {
  5844. size_t partlen;
  5845. partlen = strlen(p);
  5846. len += partlen;
  5847. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5848. memtodest(p, partlen, syntax, quotes);
  5849. if (*ap && sep) {
  5850. char *q;
  5851. len++;
  5852. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5853. continue;
  5854. }
  5855. q = expdest;
  5856. if (sepq)
  5857. STPUTC(CTLESC, q);
  5858. /* note: may put NUL despite sep != 0
  5859. * (see sep = 1 << CHAR_BIT above) */
  5860. STPUTC(sep, q);
  5861. expdest = q;
  5862. }
  5863. }
  5864. return len;
  5865. } /* case '@' and '*' */
  5866. case '0':
  5867. case '1':
  5868. case '2':
  5869. case '3':
  5870. case '4':
  5871. case '5':
  5872. case '6':
  5873. case '7':
  5874. case '8':
  5875. case '9':
  5876. num = atoi(name); /* number(name) fails on ${N#str} etc */
  5877. if (num < 0 || num > shellparam.nparam)
  5878. return -1;
  5879. p = num ? shellparam.p[num - 1] : arg0;
  5880. goto value;
  5881. default:
  5882. /* NB: name has form "VAR=..." */
  5883. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  5884. * which should be considered before we check variables. */
  5885. if (var_str_list) {
  5886. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  5887. p = NULL;
  5888. do {
  5889. char *str, *eq;
  5890. str = var_str_list->text;
  5891. eq = strchr(str, '=');
  5892. if (!eq) /* stop at first non-assignment */
  5893. break;
  5894. eq++;
  5895. if (name_len == (unsigned)(eq - str)
  5896. && strncmp(str, name, name_len) == 0
  5897. ) {
  5898. p = eq;
  5899. /* goto value; - WRONG! */
  5900. /* think "A=1 A=2 B=$A" */
  5901. }
  5902. var_str_list = var_str_list->next;
  5903. } while (var_str_list);
  5904. if (p)
  5905. goto value;
  5906. }
  5907. p = lookupvar(name);
  5908. value:
  5909. if (!p)
  5910. return -1;
  5911. len = strlen(p);
  5912. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5913. memtodest(p, len, syntax, quotes);
  5914. return len;
  5915. }
  5916. if (subtype == VSPLUS || subtype == VSLENGTH)
  5917. STADJUST(-len, expdest);
  5918. return len;
  5919. }
  5920. /*
  5921. * Expand a variable, and return a pointer to the next character in the
  5922. * input string.
  5923. */
  5924. static char *
  5925. evalvar(char *p, int flags, struct strlist *var_str_list)
  5926. {
  5927. char varflags;
  5928. char subtype;
  5929. char quoted;
  5930. char easy;
  5931. char *var;
  5932. int patloc;
  5933. int startloc;
  5934. ssize_t varlen;
  5935. varflags = (unsigned char) *p++;
  5936. subtype = varflags & VSTYPE;
  5937. quoted = varflags & VSQUOTE;
  5938. var = p;
  5939. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5940. startloc = expdest - (char *)stackblock();
  5941. p = strchr(p, '=') + 1;
  5942. again:
  5943. varlen = varvalue(var, varflags, flags, var_str_list);
  5944. if (varflags & VSNUL)
  5945. varlen--;
  5946. if (subtype == VSPLUS) {
  5947. varlen = -1 - varlen;
  5948. goto vsplus;
  5949. }
  5950. if (subtype == VSMINUS) {
  5951. vsplus:
  5952. if (varlen < 0) {
  5953. argstr(
  5954. p, flags | EXP_TILDE |
  5955. (quoted ? EXP_QWORD : EXP_WORD),
  5956. var_str_list
  5957. );
  5958. goto end;
  5959. }
  5960. if (easy)
  5961. goto record;
  5962. goto end;
  5963. }
  5964. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  5965. if (varlen < 0) {
  5966. if (subevalvar(p, var, /* strloc: */ 0,
  5967. subtype, startloc, varflags,
  5968. /* quotes: */ 0,
  5969. var_str_list)
  5970. ) {
  5971. varflags &= ~VSNUL;
  5972. /*
  5973. * Remove any recorded regions beyond
  5974. * start of variable
  5975. */
  5976. removerecordregions(startloc);
  5977. goto again;
  5978. }
  5979. goto end;
  5980. }
  5981. if (easy)
  5982. goto record;
  5983. goto end;
  5984. }
  5985. if (varlen < 0 && uflag)
  5986. varunset(p, var, 0, 0);
  5987. if (subtype == VSLENGTH) {
  5988. cvtnum(varlen > 0 ? varlen : 0);
  5989. goto record;
  5990. }
  5991. if (subtype == VSNORMAL) {
  5992. if (easy)
  5993. goto record;
  5994. goto end;
  5995. }
  5996. #if DEBUG
  5997. switch (subtype) {
  5998. case VSTRIMLEFT:
  5999. case VSTRIMLEFTMAX:
  6000. case VSTRIMRIGHT:
  6001. case VSTRIMRIGHTMAX:
  6002. #if ENABLE_ASH_BASH_COMPAT
  6003. case VSSUBSTR:
  6004. case VSREPLACE:
  6005. case VSREPLACEALL:
  6006. #endif
  6007. break;
  6008. default:
  6009. abort();
  6010. }
  6011. #endif
  6012. if (varlen >= 0) {
  6013. /*
  6014. * Terminate the string and start recording the pattern
  6015. * right after it
  6016. */
  6017. STPUTC('\0', expdest);
  6018. patloc = expdest - (char *)stackblock();
  6019. if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
  6020. startloc, varflags,
  6021. //TODO: | EXP_REDIR too? All other such places do it too
  6022. /* quotes: */ flags & (EXP_FULL | EXP_CASE),
  6023. var_str_list)
  6024. ) {
  6025. int amount = expdest - (
  6026. (char *)stackblock() + patloc - 1
  6027. );
  6028. STADJUST(-amount, expdest);
  6029. }
  6030. /* Remove any recorded regions beyond start of variable */
  6031. removerecordregions(startloc);
  6032. record:
  6033. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6034. }
  6035. end:
  6036. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6037. int nesting = 1;
  6038. for (;;) {
  6039. unsigned char c = *p++;
  6040. if (c == CTLESC)
  6041. p++;
  6042. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  6043. if (varlen >= 0)
  6044. argbackq = argbackq->next;
  6045. } else if (c == CTLVAR) {
  6046. if ((*p++ & VSTYPE) != VSNORMAL)
  6047. nesting++;
  6048. } else if (c == CTLENDVAR) {
  6049. if (--nesting == 0)
  6050. break;
  6051. }
  6052. }
  6053. }
  6054. return p;
  6055. }
  6056. /*
  6057. * Break the argument string into pieces based upon IFS and add the
  6058. * strings to the argument list. The regions of the string to be
  6059. * searched for IFS characters have been stored by recordregion.
  6060. */
  6061. static void
  6062. ifsbreakup(char *string, struct arglist *arglist)
  6063. {
  6064. struct ifsregion *ifsp;
  6065. struct strlist *sp;
  6066. char *start;
  6067. char *p;
  6068. char *q;
  6069. const char *ifs, *realifs;
  6070. int ifsspc;
  6071. int nulonly;
  6072. start = string;
  6073. if (ifslastp != NULL) {
  6074. ifsspc = 0;
  6075. nulonly = 0;
  6076. realifs = ifsset() ? ifsval() : defifs;
  6077. ifsp = &ifsfirst;
  6078. do {
  6079. p = string + ifsp->begoff;
  6080. nulonly = ifsp->nulonly;
  6081. ifs = nulonly ? nullstr : realifs;
  6082. ifsspc = 0;
  6083. while (p < string + ifsp->endoff) {
  6084. q = p;
  6085. if ((unsigned char)*p == CTLESC)
  6086. p++;
  6087. if (!strchr(ifs, *p)) {
  6088. p++;
  6089. continue;
  6090. }
  6091. if (!nulonly)
  6092. ifsspc = (strchr(defifs, *p) != NULL);
  6093. /* Ignore IFS whitespace at start */
  6094. if (q == start && ifsspc) {
  6095. p++;
  6096. start = p;
  6097. continue;
  6098. }
  6099. *q = '\0';
  6100. sp = stzalloc(sizeof(*sp));
  6101. sp->text = start;
  6102. *arglist->lastp = sp;
  6103. arglist->lastp = &sp->next;
  6104. p++;
  6105. if (!nulonly) {
  6106. for (;;) {
  6107. if (p >= string + ifsp->endoff) {
  6108. break;
  6109. }
  6110. q = p;
  6111. if ((unsigned char)*p == CTLESC)
  6112. p++;
  6113. if (strchr(ifs, *p) == NULL) {
  6114. p = q;
  6115. break;
  6116. }
  6117. if (strchr(defifs, *p) == NULL) {
  6118. if (ifsspc) {
  6119. p++;
  6120. ifsspc = 0;
  6121. } else {
  6122. p = q;
  6123. break;
  6124. }
  6125. } else
  6126. p++;
  6127. }
  6128. }
  6129. start = p;
  6130. } /* while */
  6131. ifsp = ifsp->next;
  6132. } while (ifsp != NULL);
  6133. if (nulonly)
  6134. goto add;
  6135. }
  6136. if (!*start)
  6137. return;
  6138. add:
  6139. sp = stzalloc(sizeof(*sp));
  6140. sp->text = start;
  6141. *arglist->lastp = sp;
  6142. arglist->lastp = &sp->next;
  6143. }
  6144. static void
  6145. ifsfree(void)
  6146. {
  6147. struct ifsregion *p;
  6148. INT_OFF;
  6149. p = ifsfirst.next;
  6150. do {
  6151. struct ifsregion *ifsp;
  6152. ifsp = p->next;
  6153. free(p);
  6154. p = ifsp;
  6155. } while (p);
  6156. ifslastp = NULL;
  6157. ifsfirst.next = NULL;
  6158. INT_ON;
  6159. }
  6160. /*
  6161. * Add a file name to the list.
  6162. */
  6163. static void
  6164. addfname(const char *name)
  6165. {
  6166. struct strlist *sp;
  6167. sp = stzalloc(sizeof(*sp));
  6168. sp->text = ststrdup(name);
  6169. *exparg.lastp = sp;
  6170. exparg.lastp = &sp->next;
  6171. }
  6172. static char *expdir;
  6173. /*
  6174. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6175. */
  6176. static void
  6177. expmeta(char *enddir, char *name)
  6178. {
  6179. char *p;
  6180. const char *cp;
  6181. char *start;
  6182. char *endname;
  6183. int metaflag;
  6184. struct stat statb;
  6185. DIR *dirp;
  6186. struct dirent *dp;
  6187. int atend;
  6188. int matchdot;
  6189. metaflag = 0;
  6190. start = name;
  6191. for (p = name; *p; p++) {
  6192. if (*p == '*' || *p == '?')
  6193. metaflag = 1;
  6194. else if (*p == '[') {
  6195. char *q = p + 1;
  6196. if (*q == '!')
  6197. q++;
  6198. for (;;) {
  6199. if (*q == '\\')
  6200. q++;
  6201. if (*q == '/' || *q == '\0')
  6202. break;
  6203. if (*++q == ']') {
  6204. metaflag = 1;
  6205. break;
  6206. }
  6207. }
  6208. } else if (*p == '\\')
  6209. p++;
  6210. else if (*p == '/') {
  6211. if (metaflag)
  6212. goto out;
  6213. start = p + 1;
  6214. }
  6215. }
  6216. out:
  6217. if (metaflag == 0) { /* we've reached the end of the file name */
  6218. if (enddir != expdir)
  6219. metaflag++;
  6220. p = name;
  6221. do {
  6222. if (*p == '\\')
  6223. p++;
  6224. *enddir++ = *p;
  6225. } while (*p++);
  6226. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6227. addfname(expdir);
  6228. return;
  6229. }
  6230. endname = p;
  6231. if (name < start) {
  6232. p = name;
  6233. do {
  6234. if (*p == '\\')
  6235. p++;
  6236. *enddir++ = *p++;
  6237. } while (p < start);
  6238. }
  6239. if (enddir == expdir) {
  6240. cp = ".";
  6241. } else if (enddir == expdir + 1 && *expdir == '/') {
  6242. cp = "/";
  6243. } else {
  6244. cp = expdir;
  6245. enddir[-1] = '\0';
  6246. }
  6247. dirp = opendir(cp);
  6248. if (dirp == NULL)
  6249. return;
  6250. if (enddir != expdir)
  6251. enddir[-1] = '/';
  6252. if (*endname == 0) {
  6253. atend = 1;
  6254. } else {
  6255. atend = 0;
  6256. *endname++ = '\0';
  6257. }
  6258. matchdot = 0;
  6259. p = start;
  6260. if (*p == '\\')
  6261. p++;
  6262. if (*p == '.')
  6263. matchdot++;
  6264. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6265. if (dp->d_name[0] == '.' && !matchdot)
  6266. continue;
  6267. if (pmatch(start, dp->d_name)) {
  6268. if (atend) {
  6269. strcpy(enddir, dp->d_name);
  6270. addfname(expdir);
  6271. } else {
  6272. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6273. continue;
  6274. p[-1] = '/';
  6275. expmeta(p, endname);
  6276. }
  6277. }
  6278. }
  6279. closedir(dirp);
  6280. if (!atend)
  6281. endname[-1] = '/';
  6282. }
  6283. static struct strlist *
  6284. msort(struct strlist *list, int len)
  6285. {
  6286. struct strlist *p, *q = NULL;
  6287. struct strlist **lpp;
  6288. int half;
  6289. int n;
  6290. if (len <= 1)
  6291. return list;
  6292. half = len >> 1;
  6293. p = list;
  6294. for (n = half; --n >= 0;) {
  6295. q = p;
  6296. p = p->next;
  6297. }
  6298. q->next = NULL; /* terminate first half of list */
  6299. q = msort(list, half); /* sort first half of list */
  6300. p = msort(p, len - half); /* sort second half */
  6301. lpp = &list;
  6302. for (;;) {
  6303. #if ENABLE_LOCALE_SUPPORT
  6304. if (strcoll(p->text, q->text) < 0)
  6305. #else
  6306. if (strcmp(p->text, q->text) < 0)
  6307. #endif
  6308. {
  6309. *lpp = p;
  6310. lpp = &p->next;
  6311. p = *lpp;
  6312. if (p == NULL) {
  6313. *lpp = q;
  6314. break;
  6315. }
  6316. } else {
  6317. *lpp = q;
  6318. lpp = &q->next;
  6319. q = *lpp;
  6320. if (q == NULL) {
  6321. *lpp = p;
  6322. break;
  6323. }
  6324. }
  6325. }
  6326. return list;
  6327. }
  6328. /*
  6329. * Sort the results of file name expansion. It calculates the number of
  6330. * strings to sort and then calls msort (short for merge sort) to do the
  6331. * work.
  6332. */
  6333. static struct strlist *
  6334. expsort(struct strlist *str)
  6335. {
  6336. int len;
  6337. struct strlist *sp;
  6338. len = 0;
  6339. for (sp = str; sp; sp = sp->next)
  6340. len++;
  6341. return msort(str, len);
  6342. }
  6343. static void
  6344. expandmeta(struct strlist *str /*, int flag*/)
  6345. {
  6346. static const char metachars[] ALIGN1 = {
  6347. '*', '?', '[', 0
  6348. };
  6349. /* TODO - EXP_REDIR */
  6350. while (str) {
  6351. struct strlist **savelastp;
  6352. struct strlist *sp;
  6353. char *p;
  6354. if (fflag)
  6355. goto nometa;
  6356. if (!strpbrk(str->text, metachars))
  6357. goto nometa;
  6358. savelastp = exparg.lastp;
  6359. INT_OFF;
  6360. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6361. {
  6362. int i = strlen(str->text);
  6363. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6364. }
  6365. expmeta(expdir, p);
  6366. free(expdir);
  6367. if (p != str->text)
  6368. free(p);
  6369. INT_ON;
  6370. if (exparg.lastp == savelastp) {
  6371. /*
  6372. * no matches
  6373. */
  6374. nometa:
  6375. *exparg.lastp = str;
  6376. rmescapes(str->text, 0);
  6377. exparg.lastp = &str->next;
  6378. } else {
  6379. *exparg.lastp = NULL;
  6380. *savelastp = sp = expsort(*savelastp);
  6381. while (sp->next != NULL)
  6382. sp = sp->next;
  6383. exparg.lastp = &sp->next;
  6384. }
  6385. str = str->next;
  6386. }
  6387. }
  6388. /*
  6389. * Perform variable substitution and command substitution on an argument,
  6390. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6391. * perform splitting and file name expansion. When arglist is NULL, perform
  6392. * here document expansion.
  6393. */
  6394. static void
  6395. expandarg(union node *arg, struct arglist *arglist, int flag)
  6396. {
  6397. struct strlist *sp;
  6398. char *p;
  6399. argbackq = arg->narg.backquote;
  6400. STARTSTACKSTR(expdest);
  6401. ifsfirst.next = NULL;
  6402. ifslastp = NULL;
  6403. argstr(arg->narg.text, flag,
  6404. /* var_str_list: */ arglist ? arglist->list : NULL);
  6405. p = _STPUTC('\0', expdest);
  6406. expdest = p - 1;
  6407. if (arglist == NULL) {
  6408. return; /* here document expanded */
  6409. }
  6410. p = grabstackstr(p);
  6411. exparg.lastp = &exparg.list;
  6412. /*
  6413. * TODO - EXP_REDIR
  6414. */
  6415. if (flag & EXP_FULL) {
  6416. ifsbreakup(p, &exparg);
  6417. *exparg.lastp = NULL;
  6418. exparg.lastp = &exparg.list;
  6419. expandmeta(exparg.list /*, flag*/);
  6420. } else {
  6421. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6422. rmescapes(p, 0);
  6423. sp = stzalloc(sizeof(*sp));
  6424. sp->text = p;
  6425. *exparg.lastp = sp;
  6426. exparg.lastp = &sp->next;
  6427. }
  6428. if (ifsfirst.next)
  6429. ifsfree();
  6430. *exparg.lastp = NULL;
  6431. if (exparg.list) {
  6432. *arglist->lastp = exparg.list;
  6433. arglist->lastp = exparg.lastp;
  6434. }
  6435. }
  6436. /*
  6437. * Expand shell variables and backquotes inside a here document.
  6438. */
  6439. static void
  6440. expandhere(union node *arg, int fd)
  6441. {
  6442. herefd = fd;
  6443. expandarg(arg, (struct arglist *)NULL, 0);
  6444. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6445. }
  6446. /*
  6447. * Returns true if the pattern matches the string.
  6448. */
  6449. static int
  6450. patmatch(char *pattern, const char *string)
  6451. {
  6452. return pmatch(preglob(pattern, 0, 0), string);
  6453. }
  6454. /*
  6455. * See if a pattern matches in a case statement.
  6456. */
  6457. static int
  6458. casematch(union node *pattern, char *val)
  6459. {
  6460. struct stackmark smark;
  6461. int result;
  6462. setstackmark(&smark);
  6463. argbackq = pattern->narg.backquote;
  6464. STARTSTACKSTR(expdest);
  6465. ifslastp = NULL;
  6466. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6467. /* var_str_list: */ NULL);
  6468. STACKSTRNUL(expdest);
  6469. result = patmatch(stackblock(), val);
  6470. popstackmark(&smark);
  6471. return result;
  6472. }
  6473. /* ============ find_command */
  6474. struct builtincmd {
  6475. const char *name;
  6476. int (*builtin)(int, char **) FAST_FUNC;
  6477. /* unsigned flags; */
  6478. };
  6479. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6480. /* "regular" builtins always take precedence over commands,
  6481. * regardless of PATH=....%builtin... position */
  6482. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6483. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6484. struct cmdentry {
  6485. smallint cmdtype; /* CMDxxx */
  6486. union param {
  6487. int index;
  6488. /* index >= 0 for commands without path (slashes) */
  6489. /* (TODO: what exactly does the value mean? PATH position?) */
  6490. /* index == -1 for commands with slashes */
  6491. /* index == (-2 - applet_no) for NOFORK applets */
  6492. const struct builtincmd *cmd;
  6493. struct funcnode *func;
  6494. } u;
  6495. };
  6496. /* values of cmdtype */
  6497. #define CMDUNKNOWN -1 /* no entry in table for command */
  6498. #define CMDNORMAL 0 /* command is an executable program */
  6499. #define CMDFUNCTION 1 /* command is a shell function */
  6500. #define CMDBUILTIN 2 /* command is a shell builtin */
  6501. /* action to find_command() */
  6502. #define DO_ERR 0x01 /* prints errors */
  6503. #define DO_ABS 0x02 /* checks absolute paths */
  6504. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6505. #define DO_ALTPATH 0x08 /* using alternate path */
  6506. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6507. static void find_command(char *, struct cmdentry *, int, const char *);
  6508. /* ============ Hashing commands */
  6509. /*
  6510. * When commands are first encountered, they are entered in a hash table.
  6511. * This ensures that a full path search will not have to be done for them
  6512. * on each invocation.
  6513. *
  6514. * We should investigate converting to a linear search, even though that
  6515. * would make the command name "hash" a misnomer.
  6516. */
  6517. struct tblentry {
  6518. struct tblentry *next; /* next entry in hash chain */
  6519. union param param; /* definition of builtin function */
  6520. smallint cmdtype; /* CMDxxx */
  6521. char rehash; /* if set, cd done since entry created */
  6522. char cmdname[1]; /* name of command */
  6523. };
  6524. static struct tblentry **cmdtable;
  6525. #define INIT_G_cmdtable() do { \
  6526. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6527. } while (0)
  6528. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6529. static void
  6530. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6531. {
  6532. int repeated = 0;
  6533. #if ENABLE_FEATURE_SH_STANDALONE
  6534. if (applet_no >= 0) {
  6535. if (APPLET_IS_NOEXEC(applet_no)) {
  6536. while (*envp)
  6537. putenv(*envp++);
  6538. run_applet_no_and_exit(applet_no, argv);
  6539. }
  6540. /* re-exec ourselves with the new arguments */
  6541. execve(bb_busybox_exec_path, argv, envp);
  6542. /* If they called chroot or otherwise made the binary no longer
  6543. * executable, fall through */
  6544. }
  6545. #endif
  6546. repeat:
  6547. #ifdef SYSV
  6548. do {
  6549. execve(cmd, argv, envp);
  6550. } while (errno == EINTR);
  6551. #else
  6552. execve(cmd, argv, envp);
  6553. #endif
  6554. if (repeated) {
  6555. free(argv);
  6556. return;
  6557. }
  6558. if (errno == ENOEXEC) {
  6559. char **ap;
  6560. char **new;
  6561. for (ap = argv; *ap; ap++)
  6562. continue;
  6563. ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
  6564. ap[1] = cmd;
  6565. ap[0] = cmd = (char *)DEFAULT_SHELL;
  6566. ap += 2;
  6567. argv++;
  6568. while ((*ap++ = *argv++) != NULL)
  6569. continue;
  6570. argv = new;
  6571. repeated++;
  6572. goto repeat;
  6573. }
  6574. }
  6575. /*
  6576. * Exec a program. Never returns. If you change this routine, you may
  6577. * have to change the find_command routine as well.
  6578. */
  6579. static void shellexec(char **, const char *, int) NORETURN;
  6580. static void
  6581. shellexec(char **argv, const char *path, int idx)
  6582. {
  6583. char *cmdname;
  6584. int e;
  6585. char **envp;
  6586. int exerrno;
  6587. #if ENABLE_FEATURE_SH_STANDALONE
  6588. int applet_no = -1;
  6589. #endif
  6590. clearredir(/*drop:*/ 1);
  6591. envp = listvars(VEXPORT, VUNSET, 0);
  6592. if (strchr(argv[0], '/') != NULL
  6593. #if ENABLE_FEATURE_SH_STANDALONE
  6594. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6595. #endif
  6596. ) {
  6597. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6598. e = errno;
  6599. } else {
  6600. e = ENOENT;
  6601. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6602. if (--idx < 0 && pathopt == NULL) {
  6603. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6604. if (errno != ENOENT && errno != ENOTDIR)
  6605. e = errno;
  6606. }
  6607. stunalloc(cmdname);
  6608. }
  6609. }
  6610. /* Map to POSIX errors */
  6611. switch (e) {
  6612. case EACCES:
  6613. exerrno = 126;
  6614. break;
  6615. case ENOENT:
  6616. exerrno = 127;
  6617. break;
  6618. default:
  6619. exerrno = 2;
  6620. break;
  6621. }
  6622. exitstatus = exerrno;
  6623. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  6624. argv[0], e, suppress_int));
  6625. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6626. /* NOTREACHED */
  6627. }
  6628. static void
  6629. printentry(struct tblentry *cmdp)
  6630. {
  6631. int idx;
  6632. const char *path;
  6633. char *name;
  6634. idx = cmdp->param.index;
  6635. path = pathval();
  6636. do {
  6637. name = path_advance(&path, cmdp->cmdname);
  6638. stunalloc(name);
  6639. } while (--idx >= 0);
  6640. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6641. }
  6642. /*
  6643. * Clear out command entries. The argument specifies the first entry in
  6644. * PATH which has changed.
  6645. */
  6646. static void
  6647. clearcmdentry(int firstchange)
  6648. {
  6649. struct tblentry **tblp;
  6650. struct tblentry **pp;
  6651. struct tblentry *cmdp;
  6652. INT_OFF;
  6653. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6654. pp = tblp;
  6655. while ((cmdp = *pp) != NULL) {
  6656. if ((cmdp->cmdtype == CMDNORMAL &&
  6657. cmdp->param.index >= firstchange)
  6658. || (cmdp->cmdtype == CMDBUILTIN &&
  6659. builtinloc >= firstchange)
  6660. ) {
  6661. *pp = cmdp->next;
  6662. free(cmdp);
  6663. } else {
  6664. pp = &cmdp->next;
  6665. }
  6666. }
  6667. }
  6668. INT_ON;
  6669. }
  6670. /*
  6671. * Locate a command in the command hash table. If "add" is nonzero,
  6672. * add the command to the table if it is not already present. The
  6673. * variable "lastcmdentry" is set to point to the address of the link
  6674. * pointing to the entry, so that delete_cmd_entry can delete the
  6675. * entry.
  6676. *
  6677. * Interrupts must be off if called with add != 0.
  6678. */
  6679. static struct tblentry **lastcmdentry;
  6680. static struct tblentry *
  6681. cmdlookup(const char *name, int add)
  6682. {
  6683. unsigned int hashval;
  6684. const char *p;
  6685. struct tblentry *cmdp;
  6686. struct tblentry **pp;
  6687. p = name;
  6688. hashval = (unsigned char)*p << 4;
  6689. while (*p)
  6690. hashval += (unsigned char)*p++;
  6691. hashval &= 0x7FFF;
  6692. pp = &cmdtable[hashval % CMDTABLESIZE];
  6693. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6694. if (strcmp(cmdp->cmdname, name) == 0)
  6695. break;
  6696. pp = &cmdp->next;
  6697. }
  6698. if (add && cmdp == NULL) {
  6699. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6700. + strlen(name)
  6701. /* + 1 - already done because
  6702. * tblentry::cmdname is char[1] */);
  6703. /*cmdp->next = NULL; - ckzalloc did it */
  6704. cmdp->cmdtype = CMDUNKNOWN;
  6705. strcpy(cmdp->cmdname, name);
  6706. }
  6707. lastcmdentry = pp;
  6708. return cmdp;
  6709. }
  6710. /*
  6711. * Delete the command entry returned on the last lookup.
  6712. */
  6713. static void
  6714. delete_cmd_entry(void)
  6715. {
  6716. struct tblentry *cmdp;
  6717. INT_OFF;
  6718. cmdp = *lastcmdentry;
  6719. *lastcmdentry = cmdp->next;
  6720. if (cmdp->cmdtype == CMDFUNCTION)
  6721. freefunc(cmdp->param.func);
  6722. free(cmdp);
  6723. INT_ON;
  6724. }
  6725. /*
  6726. * Add a new command entry, replacing any existing command entry for
  6727. * the same name - except special builtins.
  6728. */
  6729. static void
  6730. addcmdentry(char *name, struct cmdentry *entry)
  6731. {
  6732. struct tblentry *cmdp;
  6733. cmdp = cmdlookup(name, 1);
  6734. if (cmdp->cmdtype == CMDFUNCTION) {
  6735. freefunc(cmdp->param.func);
  6736. }
  6737. cmdp->cmdtype = entry->cmdtype;
  6738. cmdp->param = entry->u;
  6739. cmdp->rehash = 0;
  6740. }
  6741. static int FAST_FUNC
  6742. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6743. {
  6744. struct tblentry **pp;
  6745. struct tblentry *cmdp;
  6746. int c;
  6747. struct cmdentry entry;
  6748. char *name;
  6749. if (nextopt("r") != '\0') {
  6750. clearcmdentry(0);
  6751. return 0;
  6752. }
  6753. if (*argptr == NULL) {
  6754. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6755. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6756. if (cmdp->cmdtype == CMDNORMAL)
  6757. printentry(cmdp);
  6758. }
  6759. }
  6760. return 0;
  6761. }
  6762. c = 0;
  6763. while ((name = *argptr) != NULL) {
  6764. cmdp = cmdlookup(name, 0);
  6765. if (cmdp != NULL
  6766. && (cmdp->cmdtype == CMDNORMAL
  6767. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6768. ) {
  6769. delete_cmd_entry();
  6770. }
  6771. find_command(name, &entry, DO_ERR, pathval());
  6772. if (entry.cmdtype == CMDUNKNOWN)
  6773. c = 1;
  6774. argptr++;
  6775. }
  6776. return c;
  6777. }
  6778. /*
  6779. * Called when a cd is done. Marks all commands so the next time they
  6780. * are executed they will be rehashed.
  6781. */
  6782. static void
  6783. hashcd(void)
  6784. {
  6785. struct tblentry **pp;
  6786. struct tblentry *cmdp;
  6787. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6788. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6789. if (cmdp->cmdtype == CMDNORMAL
  6790. || (cmdp->cmdtype == CMDBUILTIN
  6791. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  6792. && builtinloc > 0)
  6793. ) {
  6794. cmdp->rehash = 1;
  6795. }
  6796. }
  6797. }
  6798. }
  6799. /*
  6800. * Fix command hash table when PATH changed.
  6801. * Called before PATH is changed. The argument is the new value of PATH;
  6802. * pathval() still returns the old value at this point.
  6803. * Called with interrupts off.
  6804. */
  6805. static void FAST_FUNC
  6806. changepath(const char *new)
  6807. {
  6808. const char *old;
  6809. int firstchange;
  6810. int idx;
  6811. int idx_bltin;
  6812. old = pathval();
  6813. firstchange = 9999; /* assume no change */
  6814. idx = 0;
  6815. idx_bltin = -1;
  6816. for (;;) {
  6817. if (*old != *new) {
  6818. firstchange = idx;
  6819. if ((*old == '\0' && *new == ':')
  6820. || (*old == ':' && *new == '\0'))
  6821. firstchange++;
  6822. old = new; /* ignore subsequent differences */
  6823. }
  6824. if (*new == '\0')
  6825. break;
  6826. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6827. idx_bltin = idx;
  6828. if (*new == ':')
  6829. idx++;
  6830. new++, old++;
  6831. }
  6832. if (builtinloc < 0 && idx_bltin >= 0)
  6833. builtinloc = idx_bltin; /* zap builtins */
  6834. if (builtinloc >= 0 && idx_bltin < 0)
  6835. firstchange = 0;
  6836. clearcmdentry(firstchange);
  6837. builtinloc = idx_bltin;
  6838. }
  6839. #define TEOF 0
  6840. #define TNL 1
  6841. #define TREDIR 2
  6842. #define TWORD 3
  6843. #define TSEMI 4
  6844. #define TBACKGND 5
  6845. #define TAND 6
  6846. #define TOR 7
  6847. #define TPIPE 8
  6848. #define TLP 9
  6849. #define TRP 10
  6850. #define TENDCASE 11
  6851. #define TENDBQUOTE 12
  6852. #define TNOT 13
  6853. #define TCASE 14
  6854. #define TDO 15
  6855. #define TDONE 16
  6856. #define TELIF 17
  6857. #define TELSE 18
  6858. #define TESAC 19
  6859. #define TFI 20
  6860. #define TFOR 21
  6861. #define TIF 22
  6862. #define TIN 23
  6863. #define TTHEN 24
  6864. #define TUNTIL 25
  6865. #define TWHILE 26
  6866. #define TBEGIN 27
  6867. #define TEND 28
  6868. typedef smallint token_id_t;
  6869. /* first char is indicating which tokens mark the end of a list */
  6870. static const char *const tokname_array[] = {
  6871. "\1end of file",
  6872. "\0newline",
  6873. "\0redirection",
  6874. "\0word",
  6875. "\0;",
  6876. "\0&",
  6877. "\0&&",
  6878. "\0||",
  6879. "\0|",
  6880. "\0(",
  6881. "\1)",
  6882. "\1;;",
  6883. "\1`",
  6884. #define KWDOFFSET 13
  6885. /* the following are keywords */
  6886. "\0!",
  6887. "\0case",
  6888. "\1do",
  6889. "\1done",
  6890. "\1elif",
  6891. "\1else",
  6892. "\1esac",
  6893. "\1fi",
  6894. "\0for",
  6895. "\0if",
  6896. "\0in",
  6897. "\1then",
  6898. "\0until",
  6899. "\0while",
  6900. "\0{",
  6901. "\1}",
  6902. };
  6903. static const char *
  6904. tokname(int tok)
  6905. {
  6906. static char buf[16];
  6907. //try this:
  6908. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6909. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6910. //return buf;
  6911. if (tok >= TSEMI)
  6912. buf[0] = '"';
  6913. sprintf(buf + (tok >= TSEMI), "%s%c",
  6914. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6915. return buf;
  6916. }
  6917. /* Wrapper around strcmp for qsort/bsearch/... */
  6918. static int
  6919. pstrcmp(const void *a, const void *b)
  6920. {
  6921. return strcmp((char*) a, (*(char**) b) + 1);
  6922. }
  6923. static const char *const *
  6924. findkwd(const char *s)
  6925. {
  6926. return bsearch(s, tokname_array + KWDOFFSET,
  6927. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6928. sizeof(tokname_array[0]), pstrcmp);
  6929. }
  6930. /*
  6931. * Locate and print what a word is...
  6932. */
  6933. static int
  6934. describe_command(char *command, int describe_command_verbose)
  6935. {
  6936. struct cmdentry entry;
  6937. struct tblentry *cmdp;
  6938. #if ENABLE_ASH_ALIAS
  6939. const struct alias *ap;
  6940. #endif
  6941. const char *path = pathval();
  6942. if (describe_command_verbose) {
  6943. out1str(command);
  6944. }
  6945. /* First look at the keywords */
  6946. if (findkwd(command)) {
  6947. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6948. goto out;
  6949. }
  6950. #if ENABLE_ASH_ALIAS
  6951. /* Then look at the aliases */
  6952. ap = lookupalias(command, 0);
  6953. if (ap != NULL) {
  6954. if (!describe_command_verbose) {
  6955. out1str("alias ");
  6956. printalias(ap);
  6957. return 0;
  6958. }
  6959. out1fmt(" is an alias for %s", ap->val);
  6960. goto out;
  6961. }
  6962. #endif
  6963. /* Then check if it is a tracked alias */
  6964. cmdp = cmdlookup(command, 0);
  6965. if (cmdp != NULL) {
  6966. entry.cmdtype = cmdp->cmdtype;
  6967. entry.u = cmdp->param;
  6968. } else {
  6969. /* Finally use brute force */
  6970. find_command(command, &entry, DO_ABS, path);
  6971. }
  6972. switch (entry.cmdtype) {
  6973. case CMDNORMAL: {
  6974. int j = entry.u.index;
  6975. char *p;
  6976. if (j < 0) {
  6977. p = command;
  6978. } else {
  6979. do {
  6980. p = path_advance(&path, command);
  6981. stunalloc(p);
  6982. } while (--j >= 0);
  6983. }
  6984. if (describe_command_verbose) {
  6985. out1fmt(" is%s %s",
  6986. (cmdp ? " a tracked alias for" : nullstr), p
  6987. );
  6988. } else {
  6989. out1str(p);
  6990. }
  6991. break;
  6992. }
  6993. case CMDFUNCTION:
  6994. if (describe_command_verbose) {
  6995. out1str(" is a shell function");
  6996. } else {
  6997. out1str(command);
  6998. }
  6999. break;
  7000. case CMDBUILTIN:
  7001. if (describe_command_verbose) {
  7002. out1fmt(" is a %sshell builtin",
  7003. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7004. "special " : nullstr
  7005. );
  7006. } else {
  7007. out1str(command);
  7008. }
  7009. break;
  7010. default:
  7011. if (describe_command_verbose) {
  7012. out1str(": not found\n");
  7013. }
  7014. return 127;
  7015. }
  7016. out:
  7017. out1str("\n");
  7018. return 0;
  7019. }
  7020. static int FAST_FUNC
  7021. typecmd(int argc UNUSED_PARAM, char **argv)
  7022. {
  7023. int i = 1;
  7024. int err = 0;
  7025. int verbose = 1;
  7026. /* type -p ... ? (we don't bother checking for 'p') */
  7027. if (argv[1] && argv[1][0] == '-') {
  7028. i++;
  7029. verbose = 0;
  7030. }
  7031. while (argv[i]) {
  7032. err |= describe_command(argv[i++], verbose);
  7033. }
  7034. return err;
  7035. }
  7036. #if ENABLE_ASH_CMDCMD
  7037. static int FAST_FUNC
  7038. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7039. {
  7040. int c;
  7041. enum {
  7042. VERIFY_BRIEF = 1,
  7043. VERIFY_VERBOSE = 2,
  7044. } verify = 0;
  7045. while ((c = nextopt("pvV")) != '\0')
  7046. if (c == 'V')
  7047. verify |= VERIFY_VERBOSE;
  7048. else if (c == 'v')
  7049. verify |= VERIFY_BRIEF;
  7050. #if DEBUG
  7051. else if (c != 'p')
  7052. abort();
  7053. #endif
  7054. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7055. if (verify && (*argptr != NULL)) {
  7056. return describe_command(*argptr, verify - VERIFY_BRIEF);
  7057. }
  7058. return 0;
  7059. }
  7060. #endif
  7061. /* ============ eval.c */
  7062. static int funcblocksize; /* size of structures in function */
  7063. static int funcstringsize; /* size of strings in node */
  7064. static void *funcblock; /* block to allocate function from */
  7065. static char *funcstring; /* block to allocate strings from */
  7066. /* flags in argument to evaltree */
  7067. #define EV_EXIT 01 /* exit after evaluating tree */
  7068. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  7069. #define EV_BACKCMD 04 /* command executing within back quotes */
  7070. static const uint8_t nodesize[N_NUMBER] = {
  7071. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7072. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7073. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7074. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7075. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7076. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7077. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7078. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7079. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7080. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7081. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7082. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7083. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7084. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7085. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7086. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7087. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7088. #if ENABLE_ASH_BASH_COMPAT
  7089. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7090. #endif
  7091. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7092. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7093. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7094. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7095. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7096. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7097. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7098. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7099. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7100. };
  7101. static void calcsize(union node *n);
  7102. static void
  7103. sizenodelist(struct nodelist *lp)
  7104. {
  7105. while (lp) {
  7106. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7107. calcsize(lp->n);
  7108. lp = lp->next;
  7109. }
  7110. }
  7111. static void
  7112. calcsize(union node *n)
  7113. {
  7114. if (n == NULL)
  7115. return;
  7116. funcblocksize += nodesize[n->type];
  7117. switch (n->type) {
  7118. case NCMD:
  7119. calcsize(n->ncmd.redirect);
  7120. calcsize(n->ncmd.args);
  7121. calcsize(n->ncmd.assign);
  7122. break;
  7123. case NPIPE:
  7124. sizenodelist(n->npipe.cmdlist);
  7125. break;
  7126. case NREDIR:
  7127. case NBACKGND:
  7128. case NSUBSHELL:
  7129. calcsize(n->nredir.redirect);
  7130. calcsize(n->nredir.n);
  7131. break;
  7132. case NAND:
  7133. case NOR:
  7134. case NSEMI:
  7135. case NWHILE:
  7136. case NUNTIL:
  7137. calcsize(n->nbinary.ch2);
  7138. calcsize(n->nbinary.ch1);
  7139. break;
  7140. case NIF:
  7141. calcsize(n->nif.elsepart);
  7142. calcsize(n->nif.ifpart);
  7143. calcsize(n->nif.test);
  7144. break;
  7145. case NFOR:
  7146. funcstringsize += strlen(n->nfor.var) + 1;
  7147. calcsize(n->nfor.body);
  7148. calcsize(n->nfor.args);
  7149. break;
  7150. case NCASE:
  7151. calcsize(n->ncase.cases);
  7152. calcsize(n->ncase.expr);
  7153. break;
  7154. case NCLIST:
  7155. calcsize(n->nclist.body);
  7156. calcsize(n->nclist.pattern);
  7157. calcsize(n->nclist.next);
  7158. break;
  7159. case NDEFUN:
  7160. case NARG:
  7161. sizenodelist(n->narg.backquote);
  7162. funcstringsize += strlen(n->narg.text) + 1;
  7163. calcsize(n->narg.next);
  7164. break;
  7165. case NTO:
  7166. #if ENABLE_ASH_BASH_COMPAT
  7167. case NTO2:
  7168. #endif
  7169. case NCLOBBER:
  7170. case NFROM:
  7171. case NFROMTO:
  7172. case NAPPEND:
  7173. calcsize(n->nfile.fname);
  7174. calcsize(n->nfile.next);
  7175. break;
  7176. case NTOFD:
  7177. case NFROMFD:
  7178. calcsize(n->ndup.vname);
  7179. calcsize(n->ndup.next);
  7180. break;
  7181. case NHERE:
  7182. case NXHERE:
  7183. calcsize(n->nhere.doc);
  7184. calcsize(n->nhere.next);
  7185. break;
  7186. case NNOT:
  7187. calcsize(n->nnot.com);
  7188. break;
  7189. };
  7190. }
  7191. static char *
  7192. nodeckstrdup(char *s)
  7193. {
  7194. char *rtn = funcstring;
  7195. strcpy(funcstring, s);
  7196. funcstring += strlen(s) + 1;
  7197. return rtn;
  7198. }
  7199. static union node *copynode(union node *);
  7200. static struct nodelist *
  7201. copynodelist(struct nodelist *lp)
  7202. {
  7203. struct nodelist *start;
  7204. struct nodelist **lpp;
  7205. lpp = &start;
  7206. while (lp) {
  7207. *lpp = funcblock;
  7208. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7209. (*lpp)->n = copynode(lp->n);
  7210. lp = lp->next;
  7211. lpp = &(*lpp)->next;
  7212. }
  7213. *lpp = NULL;
  7214. return start;
  7215. }
  7216. static union node *
  7217. copynode(union node *n)
  7218. {
  7219. union node *new;
  7220. if (n == NULL)
  7221. return NULL;
  7222. new = funcblock;
  7223. funcblock = (char *) funcblock + nodesize[n->type];
  7224. switch (n->type) {
  7225. case NCMD:
  7226. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7227. new->ncmd.args = copynode(n->ncmd.args);
  7228. new->ncmd.assign = copynode(n->ncmd.assign);
  7229. break;
  7230. case NPIPE:
  7231. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7232. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7233. break;
  7234. case NREDIR:
  7235. case NBACKGND:
  7236. case NSUBSHELL:
  7237. new->nredir.redirect = copynode(n->nredir.redirect);
  7238. new->nredir.n = copynode(n->nredir.n);
  7239. break;
  7240. case NAND:
  7241. case NOR:
  7242. case NSEMI:
  7243. case NWHILE:
  7244. case NUNTIL:
  7245. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7246. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7247. break;
  7248. case NIF:
  7249. new->nif.elsepart = copynode(n->nif.elsepart);
  7250. new->nif.ifpart = copynode(n->nif.ifpart);
  7251. new->nif.test = copynode(n->nif.test);
  7252. break;
  7253. case NFOR:
  7254. new->nfor.var = nodeckstrdup(n->nfor.var);
  7255. new->nfor.body = copynode(n->nfor.body);
  7256. new->nfor.args = copynode(n->nfor.args);
  7257. break;
  7258. case NCASE:
  7259. new->ncase.cases = copynode(n->ncase.cases);
  7260. new->ncase.expr = copynode(n->ncase.expr);
  7261. break;
  7262. case NCLIST:
  7263. new->nclist.body = copynode(n->nclist.body);
  7264. new->nclist.pattern = copynode(n->nclist.pattern);
  7265. new->nclist.next = copynode(n->nclist.next);
  7266. break;
  7267. case NDEFUN:
  7268. case NARG:
  7269. new->narg.backquote = copynodelist(n->narg.backquote);
  7270. new->narg.text = nodeckstrdup(n->narg.text);
  7271. new->narg.next = copynode(n->narg.next);
  7272. break;
  7273. case NTO:
  7274. #if ENABLE_ASH_BASH_COMPAT
  7275. case NTO2:
  7276. #endif
  7277. case NCLOBBER:
  7278. case NFROM:
  7279. case NFROMTO:
  7280. case NAPPEND:
  7281. new->nfile.fname = copynode(n->nfile.fname);
  7282. new->nfile.fd = n->nfile.fd;
  7283. new->nfile.next = copynode(n->nfile.next);
  7284. break;
  7285. case NTOFD:
  7286. case NFROMFD:
  7287. new->ndup.vname = copynode(n->ndup.vname);
  7288. new->ndup.dupfd = n->ndup.dupfd;
  7289. new->ndup.fd = n->ndup.fd;
  7290. new->ndup.next = copynode(n->ndup.next);
  7291. break;
  7292. case NHERE:
  7293. case NXHERE:
  7294. new->nhere.doc = copynode(n->nhere.doc);
  7295. new->nhere.fd = n->nhere.fd;
  7296. new->nhere.next = copynode(n->nhere.next);
  7297. break;
  7298. case NNOT:
  7299. new->nnot.com = copynode(n->nnot.com);
  7300. break;
  7301. };
  7302. new->type = n->type;
  7303. return new;
  7304. }
  7305. /*
  7306. * Make a copy of a parse tree.
  7307. */
  7308. static struct funcnode *
  7309. copyfunc(union node *n)
  7310. {
  7311. struct funcnode *f;
  7312. size_t blocksize;
  7313. funcblocksize = offsetof(struct funcnode, n);
  7314. funcstringsize = 0;
  7315. calcsize(n);
  7316. blocksize = funcblocksize;
  7317. f = ckmalloc(blocksize + funcstringsize);
  7318. funcblock = (char *) f + offsetof(struct funcnode, n);
  7319. funcstring = (char *) f + blocksize;
  7320. copynode(n);
  7321. f->count = 0;
  7322. return f;
  7323. }
  7324. /*
  7325. * Define a shell function.
  7326. */
  7327. static void
  7328. defun(char *name, union node *func)
  7329. {
  7330. struct cmdentry entry;
  7331. INT_OFF;
  7332. entry.cmdtype = CMDFUNCTION;
  7333. entry.u.func = copyfunc(func);
  7334. addcmdentry(name, &entry);
  7335. INT_ON;
  7336. }
  7337. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7338. #define SKIPBREAK (1 << 0)
  7339. #define SKIPCONT (1 << 1)
  7340. #define SKIPFUNC (1 << 2)
  7341. #define SKIPFILE (1 << 3)
  7342. #define SKIPEVAL (1 << 4)
  7343. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7344. static int skipcount; /* number of levels to skip */
  7345. static int funcnest; /* depth of function calls */
  7346. static int loopnest; /* current loop nesting level */
  7347. /* Forward decl way out to parsing code - dotrap needs it */
  7348. static int evalstring(char *s, int mask);
  7349. /* Called to execute a trap.
  7350. * Single callsite - at the end of evaltree().
  7351. * If we return non-zero, exaltree raises EXEXIT exception.
  7352. *
  7353. * Perhaps we should avoid entering new trap handlers
  7354. * while we are executing a trap handler. [is it a TODO?]
  7355. */
  7356. static int
  7357. dotrap(void)
  7358. {
  7359. uint8_t *g;
  7360. int sig;
  7361. uint8_t savestatus;
  7362. savestatus = exitstatus;
  7363. pending_sig = 0;
  7364. xbarrier();
  7365. TRACE(("dotrap entered\n"));
  7366. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7367. int want_exexit;
  7368. char *t;
  7369. if (*g == 0)
  7370. continue;
  7371. t = trap[sig];
  7372. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7373. * don't upset it by resetting gotsig[SIGINT-1] */
  7374. if (sig == SIGINT && !t)
  7375. continue;
  7376. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7377. *g = 0;
  7378. if (!t)
  7379. continue;
  7380. want_exexit = evalstring(t, SKIPEVAL);
  7381. exitstatus = savestatus;
  7382. if (want_exexit) {
  7383. TRACE(("dotrap returns %d\n", want_exexit));
  7384. return want_exexit;
  7385. }
  7386. }
  7387. TRACE(("dotrap returns 0\n"));
  7388. return 0;
  7389. }
  7390. /* forward declarations - evaluation is fairly recursive business... */
  7391. static void evalloop(union node *, int);
  7392. static void evalfor(union node *, int);
  7393. static void evalcase(union node *, int);
  7394. static void evalsubshell(union node *, int);
  7395. static void expredir(union node *);
  7396. static void evalpipe(union node *, int);
  7397. static void evalcommand(union node *, int);
  7398. static int evalbltin(const struct builtincmd *, int, char **);
  7399. static void prehash(union node *);
  7400. /*
  7401. * Evaluate a parse tree. The value is left in the global variable
  7402. * exitstatus.
  7403. */
  7404. static void
  7405. evaltree(union node *n, int flags)
  7406. {
  7407. struct jmploc *volatile savehandler = exception_handler;
  7408. struct jmploc jmploc;
  7409. int checkexit = 0;
  7410. void (*evalfn)(union node *, int);
  7411. int status;
  7412. int int_level;
  7413. SAVE_INT(int_level);
  7414. if (n == NULL) {
  7415. TRACE(("evaltree(NULL) called\n"));
  7416. goto out1;
  7417. }
  7418. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7419. exception_handler = &jmploc;
  7420. {
  7421. int err = setjmp(jmploc.loc);
  7422. if (err) {
  7423. /* if it was a signal, check for trap handlers */
  7424. if (exception_type == EXSIG) {
  7425. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7426. exception_type, err));
  7427. goto out;
  7428. }
  7429. /* continue on the way out */
  7430. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7431. exception_type, err));
  7432. exception_handler = savehandler;
  7433. longjmp(exception_handler->loc, err);
  7434. }
  7435. }
  7436. switch (n->type) {
  7437. default:
  7438. #if DEBUG
  7439. out1fmt("Node type = %d\n", n->type);
  7440. fflush_all();
  7441. break;
  7442. #endif
  7443. case NNOT:
  7444. evaltree(n->nnot.com, EV_TESTED);
  7445. status = !exitstatus;
  7446. goto setstatus;
  7447. case NREDIR:
  7448. expredir(n->nredir.redirect);
  7449. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7450. if (!status) {
  7451. evaltree(n->nredir.n, flags & EV_TESTED);
  7452. status = exitstatus;
  7453. }
  7454. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7455. goto setstatus;
  7456. case NCMD:
  7457. evalfn = evalcommand;
  7458. checkexit:
  7459. if (eflag && !(flags & EV_TESTED))
  7460. checkexit = ~0;
  7461. goto calleval;
  7462. case NFOR:
  7463. evalfn = evalfor;
  7464. goto calleval;
  7465. case NWHILE:
  7466. case NUNTIL:
  7467. evalfn = evalloop;
  7468. goto calleval;
  7469. case NSUBSHELL:
  7470. case NBACKGND:
  7471. evalfn = evalsubshell;
  7472. goto calleval;
  7473. case NPIPE:
  7474. evalfn = evalpipe;
  7475. goto checkexit;
  7476. case NCASE:
  7477. evalfn = evalcase;
  7478. goto calleval;
  7479. case NAND:
  7480. case NOR:
  7481. case NSEMI: {
  7482. #if NAND + 1 != NOR
  7483. #error NAND + 1 != NOR
  7484. #endif
  7485. #if NOR + 1 != NSEMI
  7486. #error NOR + 1 != NSEMI
  7487. #endif
  7488. unsigned is_or = n->type - NAND;
  7489. evaltree(
  7490. n->nbinary.ch1,
  7491. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7492. );
  7493. if (!exitstatus == is_or)
  7494. break;
  7495. if (!evalskip) {
  7496. n = n->nbinary.ch2;
  7497. evaln:
  7498. evalfn = evaltree;
  7499. calleval:
  7500. evalfn(n, flags);
  7501. break;
  7502. }
  7503. break;
  7504. }
  7505. case NIF:
  7506. evaltree(n->nif.test, EV_TESTED);
  7507. if (evalskip)
  7508. break;
  7509. if (exitstatus == 0) {
  7510. n = n->nif.ifpart;
  7511. goto evaln;
  7512. }
  7513. if (n->nif.elsepart) {
  7514. n = n->nif.elsepart;
  7515. goto evaln;
  7516. }
  7517. goto success;
  7518. case NDEFUN:
  7519. defun(n->narg.text, n->narg.next);
  7520. success:
  7521. status = 0;
  7522. setstatus:
  7523. exitstatus = status;
  7524. break;
  7525. }
  7526. out:
  7527. exception_handler = savehandler;
  7528. out1:
  7529. if (checkexit & exitstatus)
  7530. evalskip |= SKIPEVAL;
  7531. else if (pending_sig && dotrap())
  7532. goto exexit;
  7533. if (flags & EV_EXIT) {
  7534. exexit:
  7535. raise_exception(EXEXIT);
  7536. }
  7537. RESTORE_INT(int_level);
  7538. TRACE(("leaving evaltree (no interrupts)\n"));
  7539. }
  7540. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7541. static
  7542. #endif
  7543. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7544. static void
  7545. evalloop(union node *n, int flags)
  7546. {
  7547. int status;
  7548. loopnest++;
  7549. status = 0;
  7550. flags &= EV_TESTED;
  7551. for (;;) {
  7552. int i;
  7553. evaltree(n->nbinary.ch1, EV_TESTED);
  7554. if (evalskip) {
  7555. skipping:
  7556. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7557. evalskip = 0;
  7558. continue;
  7559. }
  7560. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7561. evalskip = 0;
  7562. break;
  7563. }
  7564. i = exitstatus;
  7565. if (n->type != NWHILE)
  7566. i = !i;
  7567. if (i != 0)
  7568. break;
  7569. evaltree(n->nbinary.ch2, flags);
  7570. status = exitstatus;
  7571. if (evalskip)
  7572. goto skipping;
  7573. }
  7574. loopnest--;
  7575. exitstatus = status;
  7576. }
  7577. static void
  7578. evalfor(union node *n, int flags)
  7579. {
  7580. struct arglist arglist;
  7581. union node *argp;
  7582. struct strlist *sp;
  7583. struct stackmark smark;
  7584. setstackmark(&smark);
  7585. arglist.list = NULL;
  7586. arglist.lastp = &arglist.list;
  7587. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7588. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7589. /* XXX */
  7590. if (evalskip)
  7591. goto out;
  7592. }
  7593. *arglist.lastp = NULL;
  7594. exitstatus = 0;
  7595. loopnest++;
  7596. flags &= EV_TESTED;
  7597. for (sp = arglist.list; sp; sp = sp->next) {
  7598. setvar(n->nfor.var, sp->text, 0);
  7599. evaltree(n->nfor.body, flags);
  7600. if (evalskip) {
  7601. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7602. evalskip = 0;
  7603. continue;
  7604. }
  7605. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7606. evalskip = 0;
  7607. break;
  7608. }
  7609. }
  7610. loopnest--;
  7611. out:
  7612. popstackmark(&smark);
  7613. }
  7614. static void
  7615. evalcase(union node *n, int flags)
  7616. {
  7617. union node *cp;
  7618. union node *patp;
  7619. struct arglist arglist;
  7620. struct stackmark smark;
  7621. setstackmark(&smark);
  7622. arglist.list = NULL;
  7623. arglist.lastp = &arglist.list;
  7624. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7625. exitstatus = 0;
  7626. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7627. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7628. if (casematch(patp, arglist.list->text)) {
  7629. if (evalskip == 0) {
  7630. evaltree(cp->nclist.body, flags);
  7631. }
  7632. goto out;
  7633. }
  7634. }
  7635. }
  7636. out:
  7637. popstackmark(&smark);
  7638. }
  7639. /*
  7640. * Kick off a subshell to evaluate a tree.
  7641. */
  7642. static void
  7643. evalsubshell(union node *n, int flags)
  7644. {
  7645. struct job *jp;
  7646. int backgnd = (n->type == NBACKGND);
  7647. int status;
  7648. expredir(n->nredir.redirect);
  7649. if (!backgnd && flags & EV_EXIT && !trap[0])
  7650. goto nofork;
  7651. INT_OFF;
  7652. jp = makejob(/*n,*/ 1);
  7653. if (forkshell(jp, n, backgnd) == 0) {
  7654. INT_ON;
  7655. flags |= EV_EXIT;
  7656. if (backgnd)
  7657. flags &=~ EV_TESTED;
  7658. nofork:
  7659. redirect(n->nredir.redirect, 0);
  7660. evaltreenr(n->nredir.n, flags);
  7661. /* never returns */
  7662. }
  7663. status = 0;
  7664. if (!backgnd)
  7665. status = waitforjob(jp);
  7666. exitstatus = status;
  7667. INT_ON;
  7668. }
  7669. /*
  7670. * Compute the names of the files in a redirection list.
  7671. */
  7672. static void fixredir(union node *, const char *, int);
  7673. static void
  7674. expredir(union node *n)
  7675. {
  7676. union node *redir;
  7677. for (redir = n; redir; redir = redir->nfile.next) {
  7678. struct arglist fn;
  7679. fn.list = NULL;
  7680. fn.lastp = &fn.list;
  7681. switch (redir->type) {
  7682. case NFROMTO:
  7683. case NFROM:
  7684. case NTO:
  7685. #if ENABLE_ASH_BASH_COMPAT
  7686. case NTO2:
  7687. #endif
  7688. case NCLOBBER:
  7689. case NAPPEND:
  7690. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7691. #if ENABLE_ASH_BASH_COMPAT
  7692. store_expfname:
  7693. #endif
  7694. redir->nfile.expfname = fn.list->text;
  7695. break;
  7696. case NFROMFD:
  7697. case NTOFD: /* >& */
  7698. if (redir->ndup.vname) {
  7699. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7700. if (fn.list == NULL)
  7701. ash_msg_and_raise_error("redir error");
  7702. #if ENABLE_ASH_BASH_COMPAT
  7703. //FIXME: we used expandarg with different args!
  7704. if (!isdigit_str9(fn.list->text)) {
  7705. /* >&file, not >&fd */
  7706. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7707. ash_msg_and_raise_error("redir error");
  7708. redir->type = NTO2;
  7709. goto store_expfname;
  7710. }
  7711. #endif
  7712. fixredir(redir, fn.list->text, 1);
  7713. }
  7714. break;
  7715. }
  7716. }
  7717. }
  7718. /*
  7719. * Evaluate a pipeline. All the processes in the pipeline are children
  7720. * of the process creating the pipeline. (This differs from some versions
  7721. * of the shell, which make the last process in a pipeline the parent
  7722. * of all the rest.)
  7723. */
  7724. static void
  7725. evalpipe(union node *n, int flags)
  7726. {
  7727. struct job *jp;
  7728. struct nodelist *lp;
  7729. int pipelen;
  7730. int prevfd;
  7731. int pip[2];
  7732. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7733. pipelen = 0;
  7734. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7735. pipelen++;
  7736. flags |= EV_EXIT;
  7737. INT_OFF;
  7738. jp = makejob(/*n,*/ pipelen);
  7739. prevfd = -1;
  7740. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7741. prehash(lp->n);
  7742. pip[1] = -1;
  7743. if (lp->next) {
  7744. if (pipe(pip) < 0) {
  7745. close(prevfd);
  7746. ash_msg_and_raise_error("pipe call failed");
  7747. }
  7748. }
  7749. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7750. INT_ON;
  7751. if (pip[1] >= 0) {
  7752. close(pip[0]);
  7753. }
  7754. if (prevfd > 0) {
  7755. dup2(prevfd, 0);
  7756. close(prevfd);
  7757. }
  7758. if (pip[1] > 1) {
  7759. dup2(pip[1], 1);
  7760. close(pip[1]);
  7761. }
  7762. evaltreenr(lp->n, flags);
  7763. /* never returns */
  7764. }
  7765. if (prevfd >= 0)
  7766. close(prevfd);
  7767. prevfd = pip[0];
  7768. /* Don't want to trigger debugging */
  7769. if (pip[1] != -1)
  7770. close(pip[1]);
  7771. }
  7772. if (n->npipe.pipe_backgnd == 0) {
  7773. exitstatus = waitforjob(jp);
  7774. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7775. }
  7776. INT_ON;
  7777. }
  7778. /*
  7779. * Controls whether the shell is interactive or not.
  7780. */
  7781. static void
  7782. setinteractive(int on)
  7783. {
  7784. static smallint is_interactive;
  7785. if (++on == is_interactive)
  7786. return;
  7787. is_interactive = on;
  7788. setsignal(SIGINT);
  7789. setsignal(SIGQUIT);
  7790. setsignal(SIGTERM);
  7791. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7792. if (is_interactive > 1) {
  7793. /* Looks like they want an interactive shell */
  7794. static smallint did_banner;
  7795. if (!did_banner) {
  7796. /* note: ash and hush share this string */
  7797. out1fmt("\n\n%s %s\n"
  7798. "Enter 'help' for a list of built-in commands."
  7799. "\n\n",
  7800. bb_banner,
  7801. "built-in shell (ash)"
  7802. );
  7803. did_banner = 1;
  7804. }
  7805. }
  7806. #endif
  7807. }
  7808. static void
  7809. optschanged(void)
  7810. {
  7811. #if DEBUG
  7812. opentrace();
  7813. #endif
  7814. setinteractive(iflag);
  7815. setjobctl(mflag);
  7816. #if ENABLE_FEATURE_EDITING_VI
  7817. if (viflag)
  7818. line_input_state->flags |= VI_MODE;
  7819. else
  7820. line_input_state->flags &= ~VI_MODE;
  7821. #else
  7822. viflag = 0; /* forcibly keep the option off */
  7823. #endif
  7824. }
  7825. static struct localvar *localvars;
  7826. /*
  7827. * Called after a function returns.
  7828. * Interrupts must be off.
  7829. */
  7830. static void
  7831. poplocalvars(void)
  7832. {
  7833. struct localvar *lvp;
  7834. struct var *vp;
  7835. while ((lvp = localvars) != NULL) {
  7836. localvars = lvp->next;
  7837. vp = lvp->vp;
  7838. TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
  7839. if (vp == NULL) { /* $- saved */
  7840. memcpy(optlist, lvp->text, sizeof(optlist));
  7841. free((char*)lvp->text);
  7842. optschanged();
  7843. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7844. unsetvar(vp->text);
  7845. } else {
  7846. if (vp->func)
  7847. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7848. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7849. free((char*)vp->text);
  7850. vp->flags = lvp->flags;
  7851. vp->text = lvp->text;
  7852. }
  7853. free(lvp);
  7854. }
  7855. }
  7856. static int
  7857. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7858. {
  7859. volatile struct shparam saveparam;
  7860. struct localvar *volatile savelocalvars;
  7861. struct jmploc *volatile savehandler;
  7862. struct jmploc jmploc;
  7863. int e;
  7864. saveparam = shellparam;
  7865. savelocalvars = localvars;
  7866. e = setjmp(jmploc.loc);
  7867. if (e) {
  7868. goto funcdone;
  7869. }
  7870. INT_OFF;
  7871. savehandler = exception_handler;
  7872. exception_handler = &jmploc;
  7873. localvars = NULL;
  7874. shellparam.malloced = 0;
  7875. func->count++;
  7876. funcnest++;
  7877. INT_ON;
  7878. shellparam.nparam = argc - 1;
  7879. shellparam.p = argv + 1;
  7880. #if ENABLE_ASH_GETOPTS
  7881. shellparam.optind = 1;
  7882. shellparam.optoff = -1;
  7883. #endif
  7884. evaltree(&func->n, flags & EV_TESTED);
  7885. funcdone:
  7886. INT_OFF;
  7887. funcnest--;
  7888. freefunc(func);
  7889. poplocalvars();
  7890. localvars = savelocalvars;
  7891. freeparam(&shellparam);
  7892. shellparam = saveparam;
  7893. exception_handler = savehandler;
  7894. INT_ON;
  7895. evalskip &= ~SKIPFUNC;
  7896. return e;
  7897. }
  7898. #if ENABLE_ASH_CMDCMD
  7899. static char **
  7900. parse_command_args(char **argv, const char **path)
  7901. {
  7902. char *cp, c;
  7903. for (;;) {
  7904. cp = *++argv;
  7905. if (!cp)
  7906. return 0;
  7907. if (*cp++ != '-')
  7908. break;
  7909. c = *cp++;
  7910. if (!c)
  7911. break;
  7912. if (c == '-' && !*cp) {
  7913. argv++;
  7914. break;
  7915. }
  7916. do {
  7917. switch (c) {
  7918. case 'p':
  7919. *path = bb_default_path;
  7920. break;
  7921. default:
  7922. /* run 'typecmd' for other options */
  7923. return 0;
  7924. }
  7925. c = *cp++;
  7926. } while (c);
  7927. }
  7928. return argv;
  7929. }
  7930. #endif
  7931. /*
  7932. * Make a variable a local variable. When a variable is made local, it's
  7933. * value and flags are saved in a localvar structure. The saved values
  7934. * will be restored when the shell function returns. We handle the name
  7935. * "-" as a special case.
  7936. */
  7937. static void
  7938. mklocal(char *name)
  7939. {
  7940. struct localvar *lvp;
  7941. struct var **vpp;
  7942. struct var *vp;
  7943. INT_OFF;
  7944. lvp = ckzalloc(sizeof(struct localvar));
  7945. if (LONE_DASH(name)) {
  7946. char *p;
  7947. p = ckmalloc(sizeof(optlist));
  7948. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7949. vp = NULL;
  7950. } else {
  7951. char *eq;
  7952. vpp = hashvar(name);
  7953. vp = *findvar(vpp, name);
  7954. eq = strchr(name, '=');
  7955. if (vp == NULL) {
  7956. if (eq)
  7957. setvareq(name, VSTRFIXED);
  7958. else
  7959. setvar(name, NULL, VSTRFIXED);
  7960. vp = *vpp; /* the new variable */
  7961. lvp->flags = VUNSET;
  7962. } else {
  7963. lvp->text = vp->text;
  7964. lvp->flags = vp->flags;
  7965. vp->flags |= VSTRFIXED|VTEXTFIXED;
  7966. if (eq)
  7967. setvareq(name, 0);
  7968. }
  7969. }
  7970. lvp->vp = vp;
  7971. lvp->next = localvars;
  7972. localvars = lvp;
  7973. INT_ON;
  7974. }
  7975. /*
  7976. * The "local" command.
  7977. */
  7978. static int FAST_FUNC
  7979. localcmd(int argc UNUSED_PARAM, char **argv)
  7980. {
  7981. char *name;
  7982. argv = argptr;
  7983. while ((name = *argv++) != NULL) {
  7984. mklocal(name);
  7985. }
  7986. return 0;
  7987. }
  7988. static int FAST_FUNC
  7989. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7990. {
  7991. return 1;
  7992. }
  7993. static int FAST_FUNC
  7994. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7995. {
  7996. return 0;
  7997. }
  7998. static int FAST_FUNC
  7999. execcmd(int argc UNUSED_PARAM, char **argv)
  8000. {
  8001. if (argv[1]) {
  8002. iflag = 0; /* exit on error */
  8003. mflag = 0;
  8004. optschanged();
  8005. shellexec(argv + 1, pathval(), 0);
  8006. }
  8007. return 0;
  8008. }
  8009. /*
  8010. * The return command.
  8011. */
  8012. static int FAST_FUNC
  8013. returncmd(int argc UNUSED_PARAM, char **argv)
  8014. {
  8015. /*
  8016. * If called outside a function, do what ksh does;
  8017. * skip the rest of the file.
  8018. */
  8019. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  8020. return argv[1] ? number(argv[1]) : exitstatus;
  8021. }
  8022. /* Forward declarations for builtintab[] */
  8023. static int breakcmd(int, char **) FAST_FUNC;
  8024. static int dotcmd(int, char **) FAST_FUNC;
  8025. static int evalcmd(int, char **) FAST_FUNC;
  8026. static int exitcmd(int, char **) FAST_FUNC;
  8027. static int exportcmd(int, char **) FAST_FUNC;
  8028. #if ENABLE_ASH_GETOPTS
  8029. static int getoptscmd(int, char **) FAST_FUNC;
  8030. #endif
  8031. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8032. static int helpcmd(int, char **) FAST_FUNC;
  8033. #endif
  8034. #if ENABLE_SH_MATH_SUPPORT
  8035. static int letcmd(int, char **) FAST_FUNC;
  8036. #endif
  8037. static int readcmd(int, char **) FAST_FUNC;
  8038. static int setcmd(int, char **) FAST_FUNC;
  8039. static int shiftcmd(int, char **) FAST_FUNC;
  8040. static int timescmd(int, char **) FAST_FUNC;
  8041. static int trapcmd(int, char **) FAST_FUNC;
  8042. static int umaskcmd(int, char **) FAST_FUNC;
  8043. static int unsetcmd(int, char **) FAST_FUNC;
  8044. static int ulimitcmd(int, char **) FAST_FUNC;
  8045. #define BUILTIN_NOSPEC "0"
  8046. #define BUILTIN_SPECIAL "1"
  8047. #define BUILTIN_REGULAR "2"
  8048. #define BUILTIN_SPEC_REG "3"
  8049. #define BUILTIN_ASSIGN "4"
  8050. #define BUILTIN_SPEC_ASSG "5"
  8051. #define BUILTIN_REG_ASSG "6"
  8052. #define BUILTIN_SPEC_REG_ASSG "7"
  8053. /* Stubs for calling non-FAST_FUNC's */
  8054. #if ENABLE_ASH_BUILTIN_ECHO
  8055. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8056. #endif
  8057. #if ENABLE_ASH_BUILTIN_PRINTF
  8058. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8059. #endif
  8060. #if ENABLE_ASH_BUILTIN_TEST
  8061. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8062. #endif
  8063. /* Keep these in proper order since it is searched via bsearch() */
  8064. static const struct builtincmd builtintab[] = {
  8065. { BUILTIN_SPEC_REG ".", dotcmd },
  8066. { BUILTIN_SPEC_REG ":", truecmd },
  8067. #if ENABLE_ASH_BUILTIN_TEST
  8068. { BUILTIN_REGULAR "[", testcmd },
  8069. #if ENABLE_ASH_BASH_COMPAT
  8070. { BUILTIN_REGULAR "[[", testcmd },
  8071. #endif
  8072. #endif
  8073. #if ENABLE_ASH_ALIAS
  8074. { BUILTIN_REG_ASSG "alias", aliascmd },
  8075. #endif
  8076. #if JOBS
  8077. { BUILTIN_REGULAR "bg", fg_bgcmd },
  8078. #endif
  8079. { BUILTIN_SPEC_REG "break", breakcmd },
  8080. { BUILTIN_REGULAR "cd", cdcmd },
  8081. { BUILTIN_NOSPEC "chdir", cdcmd },
  8082. #if ENABLE_ASH_CMDCMD
  8083. { BUILTIN_REGULAR "command", commandcmd },
  8084. #endif
  8085. { BUILTIN_SPEC_REG "continue", breakcmd },
  8086. #if ENABLE_ASH_BUILTIN_ECHO
  8087. { BUILTIN_REGULAR "echo", echocmd },
  8088. #endif
  8089. { BUILTIN_SPEC_REG "eval", evalcmd },
  8090. { BUILTIN_SPEC_REG "exec", execcmd },
  8091. { BUILTIN_SPEC_REG "exit", exitcmd },
  8092. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  8093. { BUILTIN_REGULAR "false", falsecmd },
  8094. #if JOBS
  8095. { BUILTIN_REGULAR "fg", fg_bgcmd },
  8096. #endif
  8097. #if ENABLE_ASH_GETOPTS
  8098. { BUILTIN_REGULAR "getopts", getoptscmd },
  8099. #endif
  8100. { BUILTIN_NOSPEC "hash", hashcmd },
  8101. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8102. { BUILTIN_NOSPEC "help", helpcmd },
  8103. #endif
  8104. #if JOBS
  8105. { BUILTIN_REGULAR "jobs", jobscmd },
  8106. { BUILTIN_REGULAR "kill", killcmd },
  8107. #endif
  8108. #if ENABLE_SH_MATH_SUPPORT
  8109. { BUILTIN_NOSPEC "let", letcmd },
  8110. #endif
  8111. { BUILTIN_ASSIGN "local", localcmd },
  8112. #if ENABLE_ASH_BUILTIN_PRINTF
  8113. { BUILTIN_REGULAR "printf", printfcmd },
  8114. #endif
  8115. { BUILTIN_NOSPEC "pwd", pwdcmd },
  8116. { BUILTIN_REGULAR "read", readcmd },
  8117. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8118. { BUILTIN_SPEC_REG "return", returncmd },
  8119. { BUILTIN_SPEC_REG "set", setcmd },
  8120. { BUILTIN_SPEC_REG "shift", shiftcmd },
  8121. { BUILTIN_SPEC_REG "source", dotcmd },
  8122. #if ENABLE_ASH_BUILTIN_TEST
  8123. { BUILTIN_REGULAR "test", testcmd },
  8124. #endif
  8125. { BUILTIN_SPEC_REG "times", timescmd },
  8126. { BUILTIN_SPEC_REG "trap", trapcmd },
  8127. { BUILTIN_REGULAR "true", truecmd },
  8128. { BUILTIN_NOSPEC "type", typecmd },
  8129. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  8130. { BUILTIN_REGULAR "umask", umaskcmd },
  8131. #if ENABLE_ASH_ALIAS
  8132. { BUILTIN_REGULAR "unalias", unaliascmd },
  8133. #endif
  8134. { BUILTIN_SPEC_REG "unset", unsetcmd },
  8135. { BUILTIN_REGULAR "wait", waitcmd },
  8136. };
  8137. /* Should match the above table! */
  8138. #define COMMANDCMD (builtintab + \
  8139. 2 + \
  8140. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8141. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8142. 1 * ENABLE_ASH_ALIAS + \
  8143. 1 * ENABLE_ASH_JOB_CONTROL + \
  8144. 3)
  8145. #define EXECCMD (builtintab + \
  8146. 2 + \
  8147. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8148. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8149. 1 * ENABLE_ASH_ALIAS + \
  8150. 1 * ENABLE_ASH_JOB_CONTROL + \
  8151. 3 + \
  8152. 1 * ENABLE_ASH_CMDCMD + \
  8153. 1 + \
  8154. ENABLE_ASH_BUILTIN_ECHO + \
  8155. 1)
  8156. /*
  8157. * Search the table of builtin commands.
  8158. */
  8159. static struct builtincmd *
  8160. find_builtin(const char *name)
  8161. {
  8162. struct builtincmd *bp;
  8163. bp = bsearch(
  8164. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8165. pstrcmp
  8166. );
  8167. return bp;
  8168. }
  8169. /*
  8170. * Execute a simple command.
  8171. */
  8172. static int
  8173. isassignment(const char *p)
  8174. {
  8175. const char *q = endofname(p);
  8176. if (p == q)
  8177. return 0;
  8178. return *q == '=';
  8179. }
  8180. static int FAST_FUNC
  8181. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8182. {
  8183. /* Preserve exitstatus of a previous possible redirection
  8184. * as POSIX mandates */
  8185. return back_exitstatus;
  8186. }
  8187. static void
  8188. evalcommand(union node *cmd, int flags)
  8189. {
  8190. static const struct builtincmd null_bltin = {
  8191. "\0\0", bltincmd /* why three NULs? */
  8192. };
  8193. struct stackmark smark;
  8194. union node *argp;
  8195. struct arglist arglist;
  8196. struct arglist varlist;
  8197. char **argv;
  8198. int argc;
  8199. const struct strlist *sp;
  8200. struct cmdentry cmdentry;
  8201. struct job *jp;
  8202. char *lastarg;
  8203. const char *path;
  8204. int spclbltin;
  8205. int status;
  8206. char **nargv;
  8207. struct builtincmd *bcmd;
  8208. smallint cmd_is_exec;
  8209. smallint pseudovarflag = 0;
  8210. /* First expand the arguments. */
  8211. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8212. setstackmark(&smark);
  8213. back_exitstatus = 0;
  8214. cmdentry.cmdtype = CMDBUILTIN;
  8215. cmdentry.u.cmd = &null_bltin;
  8216. varlist.lastp = &varlist.list;
  8217. *varlist.lastp = NULL;
  8218. arglist.lastp = &arglist.list;
  8219. *arglist.lastp = NULL;
  8220. argc = 0;
  8221. if (cmd->ncmd.args) {
  8222. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8223. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8224. }
  8225. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8226. struct strlist **spp;
  8227. spp = arglist.lastp;
  8228. if (pseudovarflag && isassignment(argp->narg.text))
  8229. expandarg(argp, &arglist, EXP_VARTILDE);
  8230. else
  8231. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8232. for (sp = *spp; sp; sp = sp->next)
  8233. argc++;
  8234. }
  8235. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8236. for (sp = arglist.list; sp; sp = sp->next) {
  8237. TRACE(("evalcommand arg: %s\n", sp->text));
  8238. *nargv++ = sp->text;
  8239. }
  8240. *nargv = NULL;
  8241. lastarg = NULL;
  8242. if (iflag && funcnest == 0 && argc > 0)
  8243. lastarg = nargv[-1];
  8244. preverrout_fd = 2;
  8245. expredir(cmd->ncmd.redirect);
  8246. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8247. path = vpath.text;
  8248. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8249. struct strlist **spp;
  8250. char *p;
  8251. spp = varlist.lastp;
  8252. expandarg(argp, &varlist, EXP_VARTILDE);
  8253. /*
  8254. * Modify the command lookup path, if a PATH= assignment
  8255. * is present
  8256. */
  8257. p = (*spp)->text;
  8258. if (varequal(p, path))
  8259. path = p;
  8260. }
  8261. /* Print the command if xflag is set. */
  8262. if (xflag) {
  8263. int n;
  8264. const char *p = " %s";
  8265. p++;
  8266. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8267. sp = varlist.list;
  8268. for (n = 0; n < 2; n++) {
  8269. while (sp) {
  8270. fdprintf(preverrout_fd, p, sp->text);
  8271. sp = sp->next;
  8272. if (*p == '%') {
  8273. p--;
  8274. }
  8275. }
  8276. sp = arglist.list;
  8277. }
  8278. safe_write(preverrout_fd, "\n", 1);
  8279. }
  8280. cmd_is_exec = 0;
  8281. spclbltin = -1;
  8282. /* Now locate the command. */
  8283. if (argc) {
  8284. const char *oldpath;
  8285. int cmd_flag = DO_ERR;
  8286. path += 5;
  8287. oldpath = path;
  8288. for (;;) {
  8289. find_command(argv[0], &cmdentry, cmd_flag, path);
  8290. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8291. flush_stdout_stderr();
  8292. status = 127;
  8293. goto bail;
  8294. }
  8295. /* implement bltin and command here */
  8296. if (cmdentry.cmdtype != CMDBUILTIN)
  8297. break;
  8298. if (spclbltin < 0)
  8299. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8300. if (cmdentry.u.cmd == EXECCMD)
  8301. cmd_is_exec = 1;
  8302. #if ENABLE_ASH_CMDCMD
  8303. if (cmdentry.u.cmd == COMMANDCMD) {
  8304. path = oldpath;
  8305. nargv = parse_command_args(argv, &path);
  8306. if (!nargv)
  8307. break;
  8308. argc -= nargv - argv;
  8309. argv = nargv;
  8310. cmd_flag |= DO_NOFUNC;
  8311. } else
  8312. #endif
  8313. break;
  8314. }
  8315. }
  8316. if (status) {
  8317. /* We have a redirection error. */
  8318. if (spclbltin > 0)
  8319. raise_exception(EXERROR);
  8320. bail:
  8321. exitstatus = status;
  8322. goto out;
  8323. }
  8324. /* Execute the command. */
  8325. switch (cmdentry.cmdtype) {
  8326. default:
  8327. #if ENABLE_FEATURE_SH_NOFORK
  8328. /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
  8329. * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
  8330. {
  8331. /* find_command() encodes applet_no as (-2 - applet_no) */
  8332. int applet_no = (- cmdentry.u.index - 2);
  8333. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8334. listsetvar(varlist.list, VEXPORT|VSTACK);
  8335. /* run <applet>_main() */
  8336. exitstatus = run_nofork_applet(applet_no, argv);
  8337. break;
  8338. }
  8339. }
  8340. #endif
  8341. /* Fork off a child process if necessary. */
  8342. if (!(flags & EV_EXIT) || trap[0]) {
  8343. INT_OFF;
  8344. jp = makejob(/*cmd,*/ 1);
  8345. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8346. exitstatus = waitforjob(jp);
  8347. INT_ON;
  8348. TRACE(("forked child exited with %d\n", exitstatus));
  8349. break;
  8350. }
  8351. FORCE_INT_ON;
  8352. }
  8353. listsetvar(varlist.list, VEXPORT|VSTACK);
  8354. shellexec(argv, path, cmdentry.u.index);
  8355. /* NOTREACHED */
  8356. case CMDBUILTIN:
  8357. cmdenviron = varlist.list;
  8358. if (cmdenviron) {
  8359. struct strlist *list = cmdenviron;
  8360. int i = VNOSET;
  8361. if (spclbltin > 0 || argc == 0) {
  8362. i = 0;
  8363. if (cmd_is_exec && argc > 1)
  8364. i = VEXPORT;
  8365. }
  8366. listsetvar(list, i);
  8367. }
  8368. /* Tight loop with builtins only:
  8369. * "while kill -0 $child; do true; done"
  8370. * will never exit even if $child died, unless we do this
  8371. * to reap the zombie and make kill detect that it's gone: */
  8372. dowait(DOWAIT_NONBLOCK, NULL);
  8373. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8374. int exit_status;
  8375. int i = exception_type;
  8376. if (i == EXEXIT)
  8377. goto raise;
  8378. exit_status = 2;
  8379. if (i == EXINT)
  8380. exit_status = 128 + SIGINT;
  8381. if (i == EXSIG)
  8382. exit_status = 128 + pending_sig;
  8383. exitstatus = exit_status;
  8384. if (i == EXINT || spclbltin > 0) {
  8385. raise:
  8386. longjmp(exception_handler->loc, 1);
  8387. }
  8388. FORCE_INT_ON;
  8389. }
  8390. break;
  8391. case CMDFUNCTION:
  8392. listsetvar(varlist.list, 0);
  8393. /* See above for the rationale */
  8394. dowait(DOWAIT_NONBLOCK, NULL);
  8395. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8396. goto raise;
  8397. break;
  8398. }
  8399. out:
  8400. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8401. if (lastarg) {
  8402. /* dsl: I think this is intended to be used to support
  8403. * '_' in 'vi' command mode during line editing...
  8404. * However I implemented that within libedit itself.
  8405. */
  8406. setvar("_", lastarg, 0);
  8407. }
  8408. popstackmark(&smark);
  8409. }
  8410. static int
  8411. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8412. {
  8413. char *volatile savecmdname;
  8414. struct jmploc *volatile savehandler;
  8415. struct jmploc jmploc;
  8416. int i;
  8417. savecmdname = commandname;
  8418. i = setjmp(jmploc.loc);
  8419. if (i)
  8420. goto cmddone;
  8421. savehandler = exception_handler;
  8422. exception_handler = &jmploc;
  8423. commandname = argv[0];
  8424. argptr = argv + 1;
  8425. optptr = NULL; /* initialize nextopt */
  8426. exitstatus = (*cmd->builtin)(argc, argv);
  8427. flush_stdout_stderr();
  8428. cmddone:
  8429. exitstatus |= ferror(stdout);
  8430. clearerr(stdout);
  8431. commandname = savecmdname;
  8432. exception_handler = savehandler;
  8433. return i;
  8434. }
  8435. static int
  8436. goodname(const char *p)
  8437. {
  8438. return !*endofname(p);
  8439. }
  8440. /*
  8441. * Search for a command. This is called before we fork so that the
  8442. * location of the command will be available in the parent as well as
  8443. * the child. The check for "goodname" is an overly conservative
  8444. * check that the name will not be subject to expansion.
  8445. */
  8446. static void
  8447. prehash(union node *n)
  8448. {
  8449. struct cmdentry entry;
  8450. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8451. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8452. }
  8453. /* ============ Builtin commands
  8454. *
  8455. * Builtin commands whose functions are closely tied to evaluation
  8456. * are implemented here.
  8457. */
  8458. /*
  8459. * Handle break and continue commands. Break, continue, and return are
  8460. * all handled by setting the evalskip flag. The evaluation routines
  8461. * above all check this flag, and if it is set they start skipping
  8462. * commands rather than executing them. The variable skipcount is
  8463. * the number of loops to break/continue, or the number of function
  8464. * levels to return. (The latter is always 1.) It should probably
  8465. * be an error to break out of more loops than exist, but it isn't
  8466. * in the standard shell so we don't make it one here.
  8467. */
  8468. static int FAST_FUNC
  8469. breakcmd(int argc UNUSED_PARAM, char **argv)
  8470. {
  8471. int n = argv[1] ? number(argv[1]) : 1;
  8472. if (n <= 0)
  8473. ash_msg_and_raise_error(msg_illnum, argv[1]);
  8474. if (n > loopnest)
  8475. n = loopnest;
  8476. if (n > 0) {
  8477. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8478. skipcount = n;
  8479. }
  8480. return 0;
  8481. }
  8482. /* ============ input.c
  8483. *
  8484. * This implements the input routines used by the parser.
  8485. */
  8486. enum {
  8487. INPUT_PUSH_FILE = 1,
  8488. INPUT_NOFILE_OK = 2,
  8489. };
  8490. static smallint checkkwd;
  8491. /* values of checkkwd variable */
  8492. #define CHKALIAS 0x1
  8493. #define CHKKWD 0x2
  8494. #define CHKNL 0x4
  8495. /*
  8496. * Push a string back onto the input at this current parsefile level.
  8497. * We handle aliases this way.
  8498. */
  8499. #if !ENABLE_ASH_ALIAS
  8500. #define pushstring(s, ap) pushstring(s)
  8501. #endif
  8502. static void
  8503. pushstring(char *s, struct alias *ap)
  8504. {
  8505. struct strpush *sp;
  8506. int len;
  8507. len = strlen(s);
  8508. INT_OFF;
  8509. if (g_parsefile->strpush) {
  8510. sp = ckzalloc(sizeof(*sp));
  8511. sp->prev = g_parsefile->strpush;
  8512. } else {
  8513. sp = &(g_parsefile->basestrpush);
  8514. }
  8515. g_parsefile->strpush = sp;
  8516. sp->prev_string = g_parsefile->next_to_pgetc;
  8517. sp->prev_left_in_line = g_parsefile->left_in_line;
  8518. #if ENABLE_ASH_ALIAS
  8519. sp->ap = ap;
  8520. if (ap) {
  8521. ap->flag |= ALIASINUSE;
  8522. sp->string = s;
  8523. }
  8524. #endif
  8525. g_parsefile->next_to_pgetc = s;
  8526. g_parsefile->left_in_line = len;
  8527. INT_ON;
  8528. }
  8529. static void
  8530. popstring(void)
  8531. {
  8532. struct strpush *sp = g_parsefile->strpush;
  8533. INT_OFF;
  8534. #if ENABLE_ASH_ALIAS
  8535. if (sp->ap) {
  8536. if (g_parsefile->next_to_pgetc[-1] == ' '
  8537. || g_parsefile->next_to_pgetc[-1] == '\t'
  8538. ) {
  8539. checkkwd |= CHKALIAS;
  8540. }
  8541. if (sp->string != sp->ap->val) {
  8542. free(sp->string);
  8543. }
  8544. sp->ap->flag &= ~ALIASINUSE;
  8545. if (sp->ap->flag & ALIASDEAD) {
  8546. unalias(sp->ap->name);
  8547. }
  8548. }
  8549. #endif
  8550. g_parsefile->next_to_pgetc = sp->prev_string;
  8551. g_parsefile->left_in_line = sp->prev_left_in_line;
  8552. g_parsefile->strpush = sp->prev;
  8553. if (sp != &(g_parsefile->basestrpush))
  8554. free(sp);
  8555. INT_ON;
  8556. }
  8557. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8558. //it peeks whether it is &>, and then pushes back both chars.
  8559. //This function needs to save last *next_to_pgetc to buf[0]
  8560. //to make two pungetc() reliable. Currently,
  8561. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8562. static int
  8563. preadfd(void)
  8564. {
  8565. int nr;
  8566. char *buf = g_parsefile->buf;
  8567. g_parsefile->next_to_pgetc = buf;
  8568. #if ENABLE_FEATURE_EDITING
  8569. retry:
  8570. if (!iflag || g_parsefile->fd != STDIN_FILENO)
  8571. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8572. else {
  8573. #if ENABLE_FEATURE_TAB_COMPLETION
  8574. line_input_state->path_lookup = pathval();
  8575. #endif
  8576. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  8577. if (nr == 0) {
  8578. /* Ctrl+C pressed */
  8579. if (trap[SIGINT]) {
  8580. buf[0] = '\n';
  8581. buf[1] = '\0';
  8582. raise(SIGINT);
  8583. return 1;
  8584. }
  8585. goto retry;
  8586. }
  8587. if (nr < 0 && errno == 0) {
  8588. /* Ctrl+D pressed */
  8589. nr = 0;
  8590. }
  8591. }
  8592. #else
  8593. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8594. #endif
  8595. #if 0
  8596. /* nonblock_safe_read() handles this problem */
  8597. if (nr < 0) {
  8598. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8599. int flags = fcntl(0, F_GETFL);
  8600. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8601. flags &= ~O_NONBLOCK;
  8602. if (fcntl(0, F_SETFL, flags) >= 0) {
  8603. out2str("sh: turning off NDELAY mode\n");
  8604. goto retry;
  8605. }
  8606. }
  8607. }
  8608. }
  8609. #endif
  8610. return nr;
  8611. }
  8612. /*
  8613. * Refill the input buffer and return the next input character:
  8614. *
  8615. * 1) If a string was pushed back on the input, pop it;
  8616. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8617. * or we are reading from a string so we can't refill the buffer,
  8618. * return EOF.
  8619. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8620. * 4) Process input up to the next newline, deleting nul characters.
  8621. */
  8622. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8623. #define pgetc_debug(...) ((void)0)
  8624. static int
  8625. preadbuffer(void)
  8626. {
  8627. char *q;
  8628. int more;
  8629. while (g_parsefile->strpush) {
  8630. #if ENABLE_ASH_ALIAS
  8631. if (g_parsefile->left_in_line == -1
  8632. && g_parsefile->strpush->ap
  8633. && g_parsefile->next_to_pgetc[-1] != ' '
  8634. && g_parsefile->next_to_pgetc[-1] != '\t'
  8635. ) {
  8636. pgetc_debug("preadbuffer PEOA");
  8637. return PEOA;
  8638. }
  8639. #endif
  8640. popstring();
  8641. /* try "pgetc" now: */
  8642. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8643. g_parsefile->left_in_line,
  8644. g_parsefile->next_to_pgetc,
  8645. g_parsefile->next_to_pgetc);
  8646. if (--g_parsefile->left_in_line >= 0)
  8647. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8648. }
  8649. /* on both branches above g_parsefile->left_in_line < 0.
  8650. * "pgetc" needs refilling.
  8651. */
  8652. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8653. * pungetc() may increment it a few times.
  8654. * Assuming it won't increment it to less than -90.
  8655. */
  8656. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8657. pgetc_debug("preadbuffer PEOF1");
  8658. /* even in failure keep left_in_line and next_to_pgetc
  8659. * in lock step, for correct multi-layer pungetc.
  8660. * left_in_line was decremented before preadbuffer(),
  8661. * must inc next_to_pgetc: */
  8662. g_parsefile->next_to_pgetc++;
  8663. return PEOF;
  8664. }
  8665. more = g_parsefile->left_in_buffer;
  8666. if (more <= 0) {
  8667. flush_stdout_stderr();
  8668. again:
  8669. more = preadfd();
  8670. if (more <= 0) {
  8671. /* don't try reading again */
  8672. g_parsefile->left_in_line = -99;
  8673. pgetc_debug("preadbuffer PEOF2");
  8674. g_parsefile->next_to_pgetc++;
  8675. return PEOF;
  8676. }
  8677. }
  8678. /* Find out where's the end of line.
  8679. * Set g_parsefile->left_in_line
  8680. * and g_parsefile->left_in_buffer acordingly.
  8681. * NUL chars are deleted.
  8682. */
  8683. q = g_parsefile->next_to_pgetc;
  8684. for (;;) {
  8685. char c;
  8686. more--;
  8687. c = *q;
  8688. if (c == '\0') {
  8689. memmove(q, q + 1, more);
  8690. } else {
  8691. q++;
  8692. if (c == '\n') {
  8693. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8694. break;
  8695. }
  8696. }
  8697. if (more <= 0) {
  8698. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8699. if (g_parsefile->left_in_line < 0)
  8700. goto again;
  8701. break;
  8702. }
  8703. }
  8704. g_parsefile->left_in_buffer = more;
  8705. if (vflag) {
  8706. char save = *q;
  8707. *q = '\0';
  8708. out2str(g_parsefile->next_to_pgetc);
  8709. *q = save;
  8710. }
  8711. pgetc_debug("preadbuffer at %d:%p'%s'",
  8712. g_parsefile->left_in_line,
  8713. g_parsefile->next_to_pgetc,
  8714. g_parsefile->next_to_pgetc);
  8715. return (unsigned char)*g_parsefile->next_to_pgetc++;
  8716. }
  8717. #define pgetc_as_macro() \
  8718. (--g_parsefile->left_in_line >= 0 \
  8719. ? (unsigned char)*g_parsefile->next_to_pgetc++ \
  8720. : preadbuffer() \
  8721. )
  8722. static int
  8723. pgetc(void)
  8724. {
  8725. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8726. g_parsefile->left_in_line,
  8727. g_parsefile->next_to_pgetc,
  8728. g_parsefile->next_to_pgetc);
  8729. return pgetc_as_macro();
  8730. }
  8731. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8732. # define pgetc_fast() pgetc()
  8733. #else
  8734. # define pgetc_fast() pgetc_as_macro()
  8735. #endif
  8736. #if ENABLE_ASH_ALIAS
  8737. static int
  8738. pgetc_without_PEOA(void)
  8739. {
  8740. int c;
  8741. do {
  8742. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8743. g_parsefile->left_in_line,
  8744. g_parsefile->next_to_pgetc,
  8745. g_parsefile->next_to_pgetc);
  8746. c = pgetc_fast();
  8747. } while (c == PEOA);
  8748. return c;
  8749. }
  8750. #else
  8751. # define pgetc_without_PEOA() pgetc()
  8752. #endif
  8753. /*
  8754. * Read a line from the script.
  8755. */
  8756. static char *
  8757. pfgets(char *line, int len)
  8758. {
  8759. char *p = line;
  8760. int nleft = len;
  8761. int c;
  8762. while (--nleft > 0) {
  8763. c = pgetc_without_PEOA();
  8764. if (c == PEOF) {
  8765. if (p == line)
  8766. return NULL;
  8767. break;
  8768. }
  8769. *p++ = c;
  8770. if (c == '\n')
  8771. break;
  8772. }
  8773. *p = '\0';
  8774. return line;
  8775. }
  8776. /*
  8777. * Undo the last call to pgetc. Only one character may be pushed back.
  8778. * PEOF may be pushed back.
  8779. */
  8780. static void
  8781. pungetc(void)
  8782. {
  8783. g_parsefile->left_in_line++;
  8784. g_parsefile->next_to_pgetc--;
  8785. pgetc_debug("pushed back to %d:%p'%s'",
  8786. g_parsefile->left_in_line,
  8787. g_parsefile->next_to_pgetc,
  8788. g_parsefile->next_to_pgetc);
  8789. }
  8790. /*
  8791. * To handle the "." command, a stack of input files is used. Pushfile
  8792. * adds a new entry to the stack and popfile restores the previous level.
  8793. */
  8794. static void
  8795. pushfile(void)
  8796. {
  8797. struct parsefile *pf;
  8798. pf = ckzalloc(sizeof(*pf));
  8799. pf->prev = g_parsefile;
  8800. pf->fd = -1;
  8801. /*pf->strpush = NULL; - ckzalloc did it */
  8802. /*pf->basestrpush.prev = NULL;*/
  8803. g_parsefile = pf;
  8804. }
  8805. static void
  8806. popfile(void)
  8807. {
  8808. struct parsefile *pf = g_parsefile;
  8809. INT_OFF;
  8810. if (pf->fd >= 0)
  8811. close(pf->fd);
  8812. free(pf->buf);
  8813. while (pf->strpush)
  8814. popstring();
  8815. g_parsefile = pf->prev;
  8816. free(pf);
  8817. INT_ON;
  8818. }
  8819. /*
  8820. * Return to top level.
  8821. */
  8822. static void
  8823. popallfiles(void)
  8824. {
  8825. while (g_parsefile != &basepf)
  8826. popfile();
  8827. }
  8828. /*
  8829. * Close the file(s) that the shell is reading commands from. Called
  8830. * after a fork is done.
  8831. */
  8832. static void
  8833. closescript(void)
  8834. {
  8835. popallfiles();
  8836. if (g_parsefile->fd > 0) {
  8837. close(g_parsefile->fd);
  8838. g_parsefile->fd = 0;
  8839. }
  8840. }
  8841. /*
  8842. * Like setinputfile, but takes an open file descriptor. Call this with
  8843. * interrupts off.
  8844. */
  8845. static void
  8846. setinputfd(int fd, int push)
  8847. {
  8848. close_on_exec_on(fd);
  8849. if (push) {
  8850. pushfile();
  8851. g_parsefile->buf = NULL;
  8852. }
  8853. g_parsefile->fd = fd;
  8854. if (g_parsefile->buf == NULL)
  8855. g_parsefile->buf = ckmalloc(IBUFSIZ);
  8856. g_parsefile->left_in_buffer = 0;
  8857. g_parsefile->left_in_line = 0;
  8858. g_parsefile->linno = 1;
  8859. }
  8860. /*
  8861. * Set the input to take input from a file. If push is set, push the
  8862. * old input onto the stack first.
  8863. */
  8864. static int
  8865. setinputfile(const char *fname, int flags)
  8866. {
  8867. int fd;
  8868. int fd2;
  8869. INT_OFF;
  8870. fd = open(fname, O_RDONLY);
  8871. if (fd < 0) {
  8872. if (flags & INPUT_NOFILE_OK)
  8873. goto out;
  8874. ash_msg_and_raise_error("can't open '%s'", fname);
  8875. }
  8876. if (fd < 10) {
  8877. fd2 = copyfd(fd, 10);
  8878. close(fd);
  8879. if (fd2 < 0)
  8880. ash_msg_and_raise_error("out of file descriptors");
  8881. fd = fd2;
  8882. }
  8883. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8884. out:
  8885. INT_ON;
  8886. return fd;
  8887. }
  8888. /*
  8889. * Like setinputfile, but takes input from a string.
  8890. */
  8891. static void
  8892. setinputstring(char *string)
  8893. {
  8894. INT_OFF;
  8895. pushfile();
  8896. g_parsefile->next_to_pgetc = string;
  8897. g_parsefile->left_in_line = strlen(string);
  8898. g_parsefile->buf = NULL;
  8899. g_parsefile->linno = 1;
  8900. INT_ON;
  8901. }
  8902. /* ============ mail.c
  8903. *
  8904. * Routines to check for mail.
  8905. */
  8906. #if ENABLE_ASH_MAIL
  8907. #define MAXMBOXES 10
  8908. /* times of mailboxes */
  8909. static time_t mailtime[MAXMBOXES];
  8910. /* Set if MAIL or MAILPATH is changed. */
  8911. static smallint mail_var_path_changed;
  8912. /*
  8913. * Print appropriate message(s) if mail has arrived.
  8914. * If mail_var_path_changed is set,
  8915. * then the value of MAIL has mail_var_path_changed,
  8916. * so we just update the values.
  8917. */
  8918. static void
  8919. chkmail(void)
  8920. {
  8921. const char *mpath;
  8922. char *p;
  8923. char *q;
  8924. time_t *mtp;
  8925. struct stackmark smark;
  8926. struct stat statb;
  8927. setstackmark(&smark);
  8928. mpath = mpathset() ? mpathval() : mailval();
  8929. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8930. p = path_advance(&mpath, nullstr);
  8931. if (p == NULL)
  8932. break;
  8933. if (*p == '\0')
  8934. continue;
  8935. for (q = p; *q; q++)
  8936. continue;
  8937. #if DEBUG
  8938. if (q[-1] != '/')
  8939. abort();
  8940. #endif
  8941. q[-1] = '\0'; /* delete trailing '/' */
  8942. if (stat(p, &statb) < 0) {
  8943. *mtp = 0;
  8944. continue;
  8945. }
  8946. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8947. fprintf(
  8948. stderr, snlfmt,
  8949. pathopt ? pathopt : "you have mail"
  8950. );
  8951. }
  8952. *mtp = statb.st_mtime;
  8953. }
  8954. mail_var_path_changed = 0;
  8955. popstackmark(&smark);
  8956. }
  8957. static void FAST_FUNC
  8958. changemail(const char *val UNUSED_PARAM)
  8959. {
  8960. mail_var_path_changed = 1;
  8961. }
  8962. #endif /* ASH_MAIL */
  8963. /* ============ ??? */
  8964. /*
  8965. * Set the shell parameters.
  8966. */
  8967. static void
  8968. setparam(char **argv)
  8969. {
  8970. char **newparam;
  8971. char **ap;
  8972. int nparam;
  8973. for (nparam = 0; argv[nparam]; nparam++)
  8974. continue;
  8975. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  8976. while (*argv) {
  8977. *ap++ = ckstrdup(*argv++);
  8978. }
  8979. *ap = NULL;
  8980. freeparam(&shellparam);
  8981. shellparam.malloced = 1;
  8982. shellparam.nparam = nparam;
  8983. shellparam.p = newparam;
  8984. #if ENABLE_ASH_GETOPTS
  8985. shellparam.optind = 1;
  8986. shellparam.optoff = -1;
  8987. #endif
  8988. }
  8989. /*
  8990. * Process shell options. The global variable argptr contains a pointer
  8991. * to the argument list; we advance it past the options.
  8992. *
  8993. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  8994. * For a non-interactive shell, an error condition encountered
  8995. * by a special built-in ... shall cause the shell to write a diagnostic message
  8996. * to standard error and exit as shown in the following table:
  8997. * Error Special Built-In
  8998. * ...
  8999. * Utility syntax error (option or operand error) Shall exit
  9000. * ...
  9001. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9002. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9003. * and shell continues), and people rely on this behavior!
  9004. * Testcase:
  9005. * set -o barfoo 2>/dev/null
  9006. * echo $?
  9007. *
  9008. * Oh well. Let's mimic that.
  9009. */
  9010. static int
  9011. plus_minus_o(char *name, int val)
  9012. {
  9013. int i;
  9014. if (name) {
  9015. for (i = 0; i < NOPTS; i++) {
  9016. if (strcmp(name, optnames(i)) == 0) {
  9017. optlist[i] = val;
  9018. return 0;
  9019. }
  9020. }
  9021. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9022. return 1;
  9023. }
  9024. for (i = 0; i < NOPTS; i++) {
  9025. if (val) {
  9026. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9027. } else {
  9028. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9029. }
  9030. }
  9031. return 0;
  9032. }
  9033. static void
  9034. setoption(int flag, int val)
  9035. {
  9036. int i;
  9037. for (i = 0; i < NOPTS; i++) {
  9038. if (optletters(i) == flag) {
  9039. optlist[i] = val;
  9040. return;
  9041. }
  9042. }
  9043. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9044. /* NOTREACHED */
  9045. }
  9046. static int
  9047. options(int cmdline)
  9048. {
  9049. char *p;
  9050. int val;
  9051. int c;
  9052. if (cmdline)
  9053. minusc = NULL;
  9054. while ((p = *argptr) != NULL) {
  9055. c = *p++;
  9056. if (c != '-' && c != '+')
  9057. break;
  9058. argptr++;
  9059. val = 0; /* val = 0 if c == '+' */
  9060. if (c == '-') {
  9061. val = 1;
  9062. if (p[0] == '\0' || LONE_DASH(p)) {
  9063. if (!cmdline) {
  9064. /* "-" means turn off -x and -v */
  9065. if (p[0] == '\0')
  9066. xflag = vflag = 0;
  9067. /* "--" means reset params */
  9068. else if (*argptr == NULL)
  9069. setparam(argptr);
  9070. }
  9071. break; /* "-" or "--" terminates options */
  9072. }
  9073. }
  9074. /* first char was + or - */
  9075. while ((c = *p++) != '\0') {
  9076. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9077. if (c == 'c' && cmdline) {
  9078. minusc = p; /* command is after shell args */
  9079. } else if (c == 'o') {
  9080. if (plus_minus_o(*argptr, val)) {
  9081. /* it already printed err message */
  9082. return 1; /* error */
  9083. }
  9084. if (*argptr)
  9085. argptr++;
  9086. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9087. isloginsh = 1;
  9088. /* bash does not accept +-login, we also won't */
  9089. } else if (cmdline && val && (c == '-')) { /* long options */
  9090. if (strcmp(p, "login") == 0)
  9091. isloginsh = 1;
  9092. break;
  9093. } else {
  9094. setoption(c, val);
  9095. }
  9096. }
  9097. }
  9098. return 0;
  9099. }
  9100. /*
  9101. * The shift builtin command.
  9102. */
  9103. static int FAST_FUNC
  9104. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9105. {
  9106. int n;
  9107. char **ap1, **ap2;
  9108. n = 1;
  9109. if (argv[1])
  9110. n = number(argv[1]);
  9111. if (n > shellparam.nparam)
  9112. n = 0; /* bash compat, was = shellparam.nparam; */
  9113. INT_OFF;
  9114. shellparam.nparam -= n;
  9115. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9116. if (shellparam.malloced)
  9117. free(*ap1);
  9118. }
  9119. ap2 = shellparam.p;
  9120. while ((*ap2++ = *ap1++) != NULL)
  9121. continue;
  9122. #if ENABLE_ASH_GETOPTS
  9123. shellparam.optind = 1;
  9124. shellparam.optoff = -1;
  9125. #endif
  9126. INT_ON;
  9127. return 0;
  9128. }
  9129. /*
  9130. * POSIX requires that 'set' (but not export or readonly) output the
  9131. * variables in lexicographic order - by the locale's collating order (sigh).
  9132. * Maybe we could keep them in an ordered balanced binary tree
  9133. * instead of hashed lists.
  9134. * For now just roll 'em through qsort for printing...
  9135. */
  9136. static int
  9137. showvars(const char *sep_prefix, int on, int off)
  9138. {
  9139. const char *sep;
  9140. char **ep, **epend;
  9141. ep = listvars(on, off, &epend);
  9142. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9143. sep = *sep_prefix ? " " : sep_prefix;
  9144. for (; ep < epend; ep++) {
  9145. const char *p;
  9146. const char *q;
  9147. p = strchrnul(*ep, '=');
  9148. q = nullstr;
  9149. if (*p)
  9150. q = single_quote(++p);
  9151. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9152. }
  9153. return 0;
  9154. }
  9155. /*
  9156. * The set command builtin.
  9157. */
  9158. static int FAST_FUNC
  9159. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9160. {
  9161. int retval;
  9162. if (!argv[1])
  9163. return showvars(nullstr, 0, VUNSET);
  9164. INT_OFF;
  9165. retval = 1;
  9166. if (!options(0)) { /* if no parse error... */
  9167. retval = 0;
  9168. optschanged();
  9169. if (*argptr != NULL) {
  9170. setparam(argptr);
  9171. }
  9172. }
  9173. INT_ON;
  9174. return retval;
  9175. }
  9176. #if ENABLE_ASH_RANDOM_SUPPORT
  9177. static void FAST_FUNC
  9178. change_random(const char *value)
  9179. {
  9180. uint32_t t;
  9181. if (value == NULL) {
  9182. /* "get", generate */
  9183. t = next_random(&random_gen);
  9184. /* set without recursion */
  9185. setvar(vrandom.text, utoa(t), VNOFUNC);
  9186. vrandom.flags &= ~VNOFUNC;
  9187. } else {
  9188. /* set/reset */
  9189. t = strtoul(value, NULL, 10);
  9190. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9191. }
  9192. }
  9193. #endif
  9194. #if ENABLE_ASH_GETOPTS
  9195. static int
  9196. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9197. {
  9198. char *p, *q;
  9199. char c = '?';
  9200. int done = 0;
  9201. int err = 0;
  9202. char s[12];
  9203. char **optnext;
  9204. if (*param_optind < 1)
  9205. return 1;
  9206. optnext = optfirst + *param_optind - 1;
  9207. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9208. p = NULL;
  9209. else
  9210. p = optnext[-1] + *optoff;
  9211. if (p == NULL || *p == '\0') {
  9212. /* Current word is done, advance */
  9213. p = *optnext;
  9214. if (p == NULL || *p != '-' || *++p == '\0') {
  9215. atend:
  9216. p = NULL;
  9217. done = 1;
  9218. goto out;
  9219. }
  9220. optnext++;
  9221. if (LONE_DASH(p)) /* check for "--" */
  9222. goto atend;
  9223. }
  9224. c = *p++;
  9225. for (q = optstr; *q != c;) {
  9226. if (*q == '\0') {
  9227. if (optstr[0] == ':') {
  9228. s[0] = c;
  9229. s[1] = '\0';
  9230. err |= setvarsafe("OPTARG", s, 0);
  9231. } else {
  9232. fprintf(stderr, "Illegal option -%c\n", c);
  9233. unsetvar("OPTARG");
  9234. }
  9235. c = '?';
  9236. goto out;
  9237. }
  9238. if (*++q == ':')
  9239. q++;
  9240. }
  9241. if (*++q == ':') {
  9242. if (*p == '\0' && (p = *optnext) == NULL) {
  9243. if (optstr[0] == ':') {
  9244. s[0] = c;
  9245. s[1] = '\0';
  9246. err |= setvarsafe("OPTARG", s, 0);
  9247. c = ':';
  9248. } else {
  9249. fprintf(stderr, "No arg for -%c option\n", c);
  9250. unsetvar("OPTARG");
  9251. c = '?';
  9252. }
  9253. goto out;
  9254. }
  9255. if (p == *optnext)
  9256. optnext++;
  9257. err |= setvarsafe("OPTARG", p, 0);
  9258. p = NULL;
  9259. } else
  9260. err |= setvarsafe("OPTARG", nullstr, 0);
  9261. out:
  9262. *optoff = p ? p - *(optnext - 1) : -1;
  9263. *param_optind = optnext - optfirst + 1;
  9264. fmtstr(s, sizeof(s), "%d", *param_optind);
  9265. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9266. s[0] = c;
  9267. s[1] = '\0';
  9268. err |= setvarsafe(optvar, s, 0);
  9269. if (err) {
  9270. *param_optind = 1;
  9271. *optoff = -1;
  9272. flush_stdout_stderr();
  9273. raise_exception(EXERROR);
  9274. }
  9275. return done;
  9276. }
  9277. /*
  9278. * The getopts builtin. Shellparam.optnext points to the next argument
  9279. * to be processed. Shellparam.optptr points to the next character to
  9280. * be processed in the current argument. If shellparam.optnext is NULL,
  9281. * then it's the first time getopts has been called.
  9282. */
  9283. static int FAST_FUNC
  9284. getoptscmd(int argc, char **argv)
  9285. {
  9286. char **optbase;
  9287. if (argc < 3)
  9288. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9289. if (argc == 3) {
  9290. optbase = shellparam.p;
  9291. if (shellparam.optind > shellparam.nparam + 1) {
  9292. shellparam.optind = 1;
  9293. shellparam.optoff = -1;
  9294. }
  9295. } else {
  9296. optbase = &argv[3];
  9297. if (shellparam.optind > argc - 2) {
  9298. shellparam.optind = 1;
  9299. shellparam.optoff = -1;
  9300. }
  9301. }
  9302. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9303. &shellparam.optoff);
  9304. }
  9305. #endif /* ASH_GETOPTS */
  9306. /* ============ Shell parser */
  9307. struct heredoc {
  9308. struct heredoc *next; /* next here document in list */
  9309. union node *here; /* redirection node */
  9310. char *eofmark; /* string indicating end of input */
  9311. smallint striptabs; /* if set, strip leading tabs */
  9312. };
  9313. static smallint tokpushback; /* last token pushed back */
  9314. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9315. static smallint quoteflag; /* set if (part of) last token was quoted */
  9316. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9317. static struct heredoc *heredoclist; /* list of here documents to read */
  9318. static char *wordtext; /* text of last word returned by readtoken */
  9319. static struct nodelist *backquotelist;
  9320. static union node *redirnode;
  9321. static struct heredoc *heredoc;
  9322. /*
  9323. * Called when an unexpected token is read during the parse. The argument
  9324. * is the token that is expected, or -1 if more than one type of token can
  9325. * occur at this point.
  9326. */
  9327. static void raise_error_unexpected_syntax(int) NORETURN;
  9328. static void
  9329. raise_error_unexpected_syntax(int token)
  9330. {
  9331. char msg[64];
  9332. int l;
  9333. l = sprintf(msg, "unexpected %s", tokname(lasttoken));
  9334. if (token >= 0)
  9335. sprintf(msg + l, " (expecting %s)", tokname(token));
  9336. raise_error_syntax(msg);
  9337. /* NOTREACHED */
  9338. }
  9339. #define EOFMARKLEN 79
  9340. /* parsing is heavily cross-recursive, need these forward decls */
  9341. static union node *andor(void);
  9342. static union node *pipeline(void);
  9343. static union node *parse_command(void);
  9344. static void parseheredoc(void);
  9345. static char peektoken(void);
  9346. static int readtoken(void);
  9347. static union node *
  9348. list(int nlflag)
  9349. {
  9350. union node *n1, *n2, *n3;
  9351. int tok;
  9352. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9353. if (nlflag == 2 && peektoken())
  9354. return NULL;
  9355. n1 = NULL;
  9356. for (;;) {
  9357. n2 = andor();
  9358. tok = readtoken();
  9359. if (tok == TBACKGND) {
  9360. if (n2->type == NPIPE) {
  9361. n2->npipe.pipe_backgnd = 1;
  9362. } else {
  9363. if (n2->type != NREDIR) {
  9364. n3 = stzalloc(sizeof(struct nredir));
  9365. n3->nredir.n = n2;
  9366. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9367. n2 = n3;
  9368. }
  9369. n2->type = NBACKGND;
  9370. }
  9371. }
  9372. if (n1 == NULL) {
  9373. n1 = n2;
  9374. } else {
  9375. n3 = stzalloc(sizeof(struct nbinary));
  9376. n3->type = NSEMI;
  9377. n3->nbinary.ch1 = n1;
  9378. n3->nbinary.ch2 = n2;
  9379. n1 = n3;
  9380. }
  9381. switch (tok) {
  9382. case TBACKGND:
  9383. case TSEMI:
  9384. tok = readtoken();
  9385. /* fall through */
  9386. case TNL:
  9387. if (tok == TNL) {
  9388. parseheredoc();
  9389. if (nlflag == 1)
  9390. return n1;
  9391. } else {
  9392. tokpushback = 1;
  9393. }
  9394. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9395. if (peektoken())
  9396. return n1;
  9397. break;
  9398. case TEOF:
  9399. if (heredoclist)
  9400. parseheredoc();
  9401. else
  9402. pungetc(); /* push back EOF on input */
  9403. return n1;
  9404. default:
  9405. if (nlflag == 1)
  9406. raise_error_unexpected_syntax(-1);
  9407. tokpushback = 1;
  9408. return n1;
  9409. }
  9410. }
  9411. }
  9412. static union node *
  9413. andor(void)
  9414. {
  9415. union node *n1, *n2, *n3;
  9416. int t;
  9417. n1 = pipeline();
  9418. for (;;) {
  9419. t = readtoken();
  9420. if (t == TAND) {
  9421. t = NAND;
  9422. } else if (t == TOR) {
  9423. t = NOR;
  9424. } else {
  9425. tokpushback = 1;
  9426. return n1;
  9427. }
  9428. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9429. n2 = pipeline();
  9430. n3 = stzalloc(sizeof(struct nbinary));
  9431. n3->type = t;
  9432. n3->nbinary.ch1 = n1;
  9433. n3->nbinary.ch2 = n2;
  9434. n1 = n3;
  9435. }
  9436. }
  9437. static union node *
  9438. pipeline(void)
  9439. {
  9440. union node *n1, *n2, *pipenode;
  9441. struct nodelist *lp, *prev;
  9442. int negate;
  9443. negate = 0;
  9444. TRACE(("pipeline: entered\n"));
  9445. if (readtoken() == TNOT) {
  9446. negate = !negate;
  9447. checkkwd = CHKKWD | CHKALIAS;
  9448. } else
  9449. tokpushback = 1;
  9450. n1 = parse_command();
  9451. if (readtoken() == TPIPE) {
  9452. pipenode = stzalloc(sizeof(struct npipe));
  9453. pipenode->type = NPIPE;
  9454. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9455. lp = stzalloc(sizeof(struct nodelist));
  9456. pipenode->npipe.cmdlist = lp;
  9457. lp->n = n1;
  9458. do {
  9459. prev = lp;
  9460. lp = stzalloc(sizeof(struct nodelist));
  9461. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9462. lp->n = parse_command();
  9463. prev->next = lp;
  9464. } while (readtoken() == TPIPE);
  9465. lp->next = NULL;
  9466. n1 = pipenode;
  9467. }
  9468. tokpushback = 1;
  9469. if (negate) {
  9470. n2 = stzalloc(sizeof(struct nnot));
  9471. n2->type = NNOT;
  9472. n2->nnot.com = n1;
  9473. return n2;
  9474. }
  9475. return n1;
  9476. }
  9477. static union node *
  9478. makename(void)
  9479. {
  9480. union node *n;
  9481. n = stzalloc(sizeof(struct narg));
  9482. n->type = NARG;
  9483. /*n->narg.next = NULL; - stzalloc did it */
  9484. n->narg.text = wordtext;
  9485. n->narg.backquote = backquotelist;
  9486. return n;
  9487. }
  9488. static void
  9489. fixredir(union node *n, const char *text, int err)
  9490. {
  9491. int fd;
  9492. TRACE(("Fix redir %s %d\n", text, err));
  9493. if (!err)
  9494. n->ndup.vname = NULL;
  9495. fd = bb_strtou(text, NULL, 10);
  9496. if (!errno && fd >= 0)
  9497. n->ndup.dupfd = fd;
  9498. else if (LONE_DASH(text))
  9499. n->ndup.dupfd = -1;
  9500. else {
  9501. if (err)
  9502. raise_error_syntax("bad fd number");
  9503. n->ndup.vname = makename();
  9504. }
  9505. }
  9506. /*
  9507. * Returns true if the text contains nothing to expand (no dollar signs
  9508. * or backquotes).
  9509. */
  9510. static int
  9511. noexpand(const char *text)
  9512. {
  9513. unsigned char c;
  9514. while ((c = *text++) != '\0') {
  9515. if (c == CTLQUOTEMARK)
  9516. continue;
  9517. if (c == CTLESC)
  9518. text++;
  9519. else if (SIT(c, BASESYNTAX) == CCTL)
  9520. return 0;
  9521. }
  9522. return 1;
  9523. }
  9524. static void
  9525. parsefname(void)
  9526. {
  9527. union node *n = redirnode;
  9528. if (readtoken() != TWORD)
  9529. raise_error_unexpected_syntax(-1);
  9530. if (n->type == NHERE) {
  9531. struct heredoc *here = heredoc;
  9532. struct heredoc *p;
  9533. int i;
  9534. if (quoteflag == 0)
  9535. n->type = NXHERE;
  9536. TRACE(("Here document %d\n", n->type));
  9537. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9538. raise_error_syntax("illegal eof marker for << redirection");
  9539. rmescapes(wordtext, 0);
  9540. here->eofmark = wordtext;
  9541. here->next = NULL;
  9542. if (heredoclist == NULL)
  9543. heredoclist = here;
  9544. else {
  9545. for (p = heredoclist; p->next; p = p->next)
  9546. continue;
  9547. p->next = here;
  9548. }
  9549. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9550. fixredir(n, wordtext, 0);
  9551. } else {
  9552. n->nfile.fname = makename();
  9553. }
  9554. }
  9555. static union node *
  9556. simplecmd(void)
  9557. {
  9558. union node *args, **app;
  9559. union node *n = NULL;
  9560. union node *vars, **vpp;
  9561. union node **rpp, *redir;
  9562. int savecheckkwd;
  9563. #if ENABLE_ASH_BASH_COMPAT
  9564. smallint double_brackets_flag = 0;
  9565. #endif
  9566. args = NULL;
  9567. app = &args;
  9568. vars = NULL;
  9569. vpp = &vars;
  9570. redir = NULL;
  9571. rpp = &redir;
  9572. savecheckkwd = CHKALIAS;
  9573. for (;;) {
  9574. int t;
  9575. checkkwd = savecheckkwd;
  9576. t = readtoken();
  9577. switch (t) {
  9578. #if ENABLE_ASH_BASH_COMPAT
  9579. case TAND: /* "&&" */
  9580. case TOR: /* "||" */
  9581. if (!double_brackets_flag) {
  9582. tokpushback = 1;
  9583. goto out;
  9584. }
  9585. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9586. #endif
  9587. case TWORD:
  9588. n = stzalloc(sizeof(struct narg));
  9589. n->type = NARG;
  9590. /*n->narg.next = NULL; - stzalloc did it */
  9591. n->narg.text = wordtext;
  9592. #if ENABLE_ASH_BASH_COMPAT
  9593. if (strcmp("[[", wordtext) == 0)
  9594. double_brackets_flag = 1;
  9595. else if (strcmp("]]", wordtext) == 0)
  9596. double_brackets_flag = 0;
  9597. #endif
  9598. n->narg.backquote = backquotelist;
  9599. if (savecheckkwd && isassignment(wordtext)) {
  9600. *vpp = n;
  9601. vpp = &n->narg.next;
  9602. } else {
  9603. *app = n;
  9604. app = &n->narg.next;
  9605. savecheckkwd = 0;
  9606. }
  9607. break;
  9608. case TREDIR:
  9609. *rpp = n = redirnode;
  9610. rpp = &n->nfile.next;
  9611. parsefname(); /* read name of redirection file */
  9612. break;
  9613. case TLP:
  9614. if (args && app == &args->narg.next
  9615. && !vars && !redir
  9616. ) {
  9617. struct builtincmd *bcmd;
  9618. const char *name;
  9619. /* We have a function */
  9620. if (readtoken() != TRP)
  9621. raise_error_unexpected_syntax(TRP);
  9622. name = n->narg.text;
  9623. if (!goodname(name)
  9624. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9625. ) {
  9626. raise_error_syntax("bad function name");
  9627. }
  9628. n->type = NDEFUN;
  9629. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9630. n->narg.next = parse_command();
  9631. return n;
  9632. }
  9633. /* fall through */
  9634. default:
  9635. tokpushback = 1;
  9636. goto out;
  9637. }
  9638. }
  9639. out:
  9640. *app = NULL;
  9641. *vpp = NULL;
  9642. *rpp = NULL;
  9643. n = stzalloc(sizeof(struct ncmd));
  9644. n->type = NCMD;
  9645. n->ncmd.args = args;
  9646. n->ncmd.assign = vars;
  9647. n->ncmd.redirect = redir;
  9648. return n;
  9649. }
  9650. static union node *
  9651. parse_command(void)
  9652. {
  9653. union node *n1, *n2;
  9654. union node *ap, **app;
  9655. union node *cp, **cpp;
  9656. union node *redir, **rpp;
  9657. union node **rpp2;
  9658. int t;
  9659. redir = NULL;
  9660. rpp2 = &redir;
  9661. switch (readtoken()) {
  9662. default:
  9663. raise_error_unexpected_syntax(-1);
  9664. /* NOTREACHED */
  9665. case TIF:
  9666. n1 = stzalloc(sizeof(struct nif));
  9667. n1->type = NIF;
  9668. n1->nif.test = list(0);
  9669. if (readtoken() != TTHEN)
  9670. raise_error_unexpected_syntax(TTHEN);
  9671. n1->nif.ifpart = list(0);
  9672. n2 = n1;
  9673. while (readtoken() == TELIF) {
  9674. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9675. n2 = n2->nif.elsepart;
  9676. n2->type = NIF;
  9677. n2->nif.test = list(0);
  9678. if (readtoken() != TTHEN)
  9679. raise_error_unexpected_syntax(TTHEN);
  9680. n2->nif.ifpart = list(0);
  9681. }
  9682. if (lasttoken == TELSE)
  9683. n2->nif.elsepart = list(0);
  9684. else {
  9685. n2->nif.elsepart = NULL;
  9686. tokpushback = 1;
  9687. }
  9688. t = TFI;
  9689. break;
  9690. case TWHILE:
  9691. case TUNTIL: {
  9692. int got;
  9693. n1 = stzalloc(sizeof(struct nbinary));
  9694. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9695. n1->nbinary.ch1 = list(0);
  9696. got = readtoken();
  9697. if (got != TDO) {
  9698. TRACE(("expecting DO got %s %s\n", tokname(got),
  9699. got == TWORD ? wordtext : ""));
  9700. raise_error_unexpected_syntax(TDO);
  9701. }
  9702. n1->nbinary.ch2 = list(0);
  9703. t = TDONE;
  9704. break;
  9705. }
  9706. case TFOR:
  9707. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9708. raise_error_syntax("bad for loop variable");
  9709. n1 = stzalloc(sizeof(struct nfor));
  9710. n1->type = NFOR;
  9711. n1->nfor.var = wordtext;
  9712. checkkwd = CHKKWD | CHKALIAS;
  9713. if (readtoken() == TIN) {
  9714. app = &ap;
  9715. while (readtoken() == TWORD) {
  9716. n2 = stzalloc(sizeof(struct narg));
  9717. n2->type = NARG;
  9718. /*n2->narg.next = NULL; - stzalloc did it */
  9719. n2->narg.text = wordtext;
  9720. n2->narg.backquote = backquotelist;
  9721. *app = n2;
  9722. app = &n2->narg.next;
  9723. }
  9724. *app = NULL;
  9725. n1->nfor.args = ap;
  9726. if (lasttoken != TNL && lasttoken != TSEMI)
  9727. raise_error_unexpected_syntax(-1);
  9728. } else {
  9729. n2 = stzalloc(sizeof(struct narg));
  9730. n2->type = NARG;
  9731. /*n2->narg.next = NULL; - stzalloc did it */
  9732. n2->narg.text = (char *)dolatstr;
  9733. /*n2->narg.backquote = NULL;*/
  9734. n1->nfor.args = n2;
  9735. /*
  9736. * Newline or semicolon here is optional (but note
  9737. * that the original Bourne shell only allowed NL).
  9738. */
  9739. if (lasttoken != TNL && lasttoken != TSEMI)
  9740. tokpushback = 1;
  9741. }
  9742. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9743. if (readtoken() != TDO)
  9744. raise_error_unexpected_syntax(TDO);
  9745. n1->nfor.body = list(0);
  9746. t = TDONE;
  9747. break;
  9748. case TCASE:
  9749. n1 = stzalloc(sizeof(struct ncase));
  9750. n1->type = NCASE;
  9751. if (readtoken() != TWORD)
  9752. raise_error_unexpected_syntax(TWORD);
  9753. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  9754. n2->type = NARG;
  9755. /*n2->narg.next = NULL; - stzalloc did it */
  9756. n2->narg.text = wordtext;
  9757. n2->narg.backquote = backquotelist;
  9758. do {
  9759. checkkwd = CHKKWD | CHKALIAS;
  9760. } while (readtoken() == TNL);
  9761. if (lasttoken != TIN)
  9762. raise_error_unexpected_syntax(TIN);
  9763. cpp = &n1->ncase.cases;
  9764. next_case:
  9765. checkkwd = CHKNL | CHKKWD;
  9766. t = readtoken();
  9767. while (t != TESAC) {
  9768. if (lasttoken == TLP)
  9769. readtoken();
  9770. *cpp = cp = stzalloc(sizeof(struct nclist));
  9771. cp->type = NCLIST;
  9772. app = &cp->nclist.pattern;
  9773. for (;;) {
  9774. *app = ap = stzalloc(sizeof(struct narg));
  9775. ap->type = NARG;
  9776. /*ap->narg.next = NULL; - stzalloc did it */
  9777. ap->narg.text = wordtext;
  9778. ap->narg.backquote = backquotelist;
  9779. if (readtoken() != TPIPE)
  9780. break;
  9781. app = &ap->narg.next;
  9782. readtoken();
  9783. }
  9784. //ap->narg.next = NULL;
  9785. if (lasttoken != TRP)
  9786. raise_error_unexpected_syntax(TRP);
  9787. cp->nclist.body = list(2);
  9788. cpp = &cp->nclist.next;
  9789. checkkwd = CHKNL | CHKKWD;
  9790. t = readtoken();
  9791. if (t != TESAC) {
  9792. if (t != TENDCASE)
  9793. raise_error_unexpected_syntax(TENDCASE);
  9794. goto next_case;
  9795. }
  9796. }
  9797. *cpp = NULL;
  9798. goto redir;
  9799. case TLP:
  9800. n1 = stzalloc(sizeof(struct nredir));
  9801. n1->type = NSUBSHELL;
  9802. n1->nredir.n = list(0);
  9803. /*n1->nredir.redirect = NULL; - stzalloc did it */
  9804. t = TRP;
  9805. break;
  9806. case TBEGIN:
  9807. n1 = list(0);
  9808. t = TEND;
  9809. break;
  9810. case TWORD:
  9811. case TREDIR:
  9812. tokpushback = 1;
  9813. return simplecmd();
  9814. }
  9815. if (readtoken() != t)
  9816. raise_error_unexpected_syntax(t);
  9817. redir:
  9818. /* Now check for redirection which may follow command */
  9819. checkkwd = CHKKWD | CHKALIAS;
  9820. rpp = rpp2;
  9821. while (readtoken() == TREDIR) {
  9822. *rpp = n2 = redirnode;
  9823. rpp = &n2->nfile.next;
  9824. parsefname();
  9825. }
  9826. tokpushback = 1;
  9827. *rpp = NULL;
  9828. if (redir) {
  9829. if (n1->type != NSUBSHELL) {
  9830. n2 = stzalloc(sizeof(struct nredir));
  9831. n2->type = NREDIR;
  9832. n2->nredir.n = n1;
  9833. n1 = n2;
  9834. }
  9835. n1->nredir.redirect = redir;
  9836. }
  9837. return n1;
  9838. }
  9839. #if ENABLE_ASH_BASH_COMPAT
  9840. static int decode_dollar_squote(void)
  9841. {
  9842. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  9843. int c, cnt;
  9844. char *p;
  9845. char buf[4];
  9846. c = pgetc();
  9847. p = strchr(C_escapes, c);
  9848. if (p) {
  9849. buf[0] = c;
  9850. p = buf;
  9851. cnt = 3;
  9852. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  9853. do {
  9854. c = pgetc();
  9855. *++p = c;
  9856. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  9857. pungetc();
  9858. } else if (c == 'x') { /* \xHH */
  9859. do {
  9860. c = pgetc();
  9861. *++p = c;
  9862. } while (isxdigit(c) && --cnt);
  9863. pungetc();
  9864. if (cnt == 3) { /* \x but next char is "bad" */
  9865. c = 'x';
  9866. goto unrecognized;
  9867. }
  9868. } else { /* simple seq like \\ or \t */
  9869. p++;
  9870. }
  9871. *p = '\0';
  9872. p = buf;
  9873. c = bb_process_escape_sequence((void*)&p);
  9874. } else { /* unrecognized "\z": print both chars unless ' or " */
  9875. if (c != '\'' && c != '"') {
  9876. unrecognized:
  9877. c |= 0x100; /* "please encode \, then me" */
  9878. }
  9879. }
  9880. return c;
  9881. }
  9882. #endif
  9883. /*
  9884. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  9885. * is not NULL, read a here document. In the latter case, eofmark is the
  9886. * word which marks the end of the document and striptabs is true if
  9887. * leading tabs should be stripped from the document. The argument c
  9888. * is the first character of the input token or document.
  9889. *
  9890. * Because C does not have internal subroutines, I have simulated them
  9891. * using goto's to implement the subroutine linkage. The following macros
  9892. * will run code that appears at the end of readtoken1.
  9893. */
  9894. #define CHECKEND() {goto checkend; checkend_return:;}
  9895. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  9896. #define PARSESUB() {goto parsesub; parsesub_return:;}
  9897. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  9898. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  9899. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  9900. static int
  9901. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  9902. {
  9903. /* NB: syntax parameter fits into smallint */
  9904. /* c parameter is an unsigned char or PEOF or PEOA */
  9905. char *out;
  9906. int len;
  9907. char line[EOFMARKLEN + 1];
  9908. struct nodelist *bqlist;
  9909. smallint quotef;
  9910. smallint dblquote;
  9911. smallint oldstyle;
  9912. smallint prevsyntax; /* syntax before arithmetic */
  9913. #if ENABLE_ASH_EXPAND_PRMT
  9914. smallint pssyntax; /* we are expanding a prompt string */
  9915. #endif
  9916. int varnest; /* levels of variables expansion */
  9917. int arinest; /* levels of arithmetic expansion */
  9918. int parenlevel; /* levels of parens in arithmetic */
  9919. int dqvarnest; /* levels of variables expansion within double quotes */
  9920. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  9921. #if __GNUC__
  9922. /* Avoid longjmp clobbering */
  9923. (void) &out;
  9924. (void) &quotef;
  9925. (void) &dblquote;
  9926. (void) &varnest;
  9927. (void) &arinest;
  9928. (void) &parenlevel;
  9929. (void) &dqvarnest;
  9930. (void) &oldstyle;
  9931. (void) &prevsyntax;
  9932. (void) &syntax;
  9933. #endif
  9934. startlinno = g_parsefile->linno;
  9935. bqlist = NULL;
  9936. quotef = 0;
  9937. oldstyle = 0;
  9938. prevsyntax = 0;
  9939. #if ENABLE_ASH_EXPAND_PRMT
  9940. pssyntax = (syntax == PSSYNTAX);
  9941. if (pssyntax)
  9942. syntax = DQSYNTAX;
  9943. #endif
  9944. dblquote = (syntax == DQSYNTAX);
  9945. varnest = 0;
  9946. arinest = 0;
  9947. parenlevel = 0;
  9948. dqvarnest = 0;
  9949. STARTSTACKSTR(out);
  9950. loop:
  9951. /* For each line, until end of word */
  9952. {
  9953. CHECKEND(); /* set c to PEOF if at end of here document */
  9954. for (;;) { /* until end of line or end of word */
  9955. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  9956. switch (SIT(c, syntax)) {
  9957. case CNL: /* '\n' */
  9958. if (syntax == BASESYNTAX)
  9959. goto endword; /* exit outer loop */
  9960. USTPUTC(c, out);
  9961. g_parsefile->linno++;
  9962. if (doprompt)
  9963. setprompt(2);
  9964. c = pgetc();
  9965. goto loop; /* continue outer loop */
  9966. case CWORD:
  9967. USTPUTC(c, out);
  9968. break;
  9969. case CCTL:
  9970. if (eofmark == NULL || dblquote)
  9971. USTPUTC(CTLESC, out);
  9972. #if ENABLE_ASH_BASH_COMPAT
  9973. if (c == '\\' && bash_dollar_squote) {
  9974. c = decode_dollar_squote();
  9975. if (c & 0x100) {
  9976. USTPUTC('\\', out);
  9977. c = (unsigned char)c;
  9978. }
  9979. }
  9980. #endif
  9981. USTPUTC(c, out);
  9982. break;
  9983. case CBACK: /* backslash */
  9984. c = pgetc_without_PEOA();
  9985. if (c == PEOF) {
  9986. USTPUTC(CTLESC, out);
  9987. USTPUTC('\\', out);
  9988. pungetc();
  9989. } else if (c == '\n') {
  9990. if (doprompt)
  9991. setprompt(2);
  9992. } else {
  9993. #if ENABLE_ASH_EXPAND_PRMT
  9994. if (c == '$' && pssyntax) {
  9995. USTPUTC(CTLESC, out);
  9996. USTPUTC('\\', out);
  9997. }
  9998. #endif
  9999. if (dblquote && c != '\\'
  10000. && c != '`' && c != '$'
  10001. && (c != '"' || eofmark != NULL)
  10002. ) {
  10003. USTPUTC(CTLESC, out);
  10004. USTPUTC('\\', out);
  10005. }
  10006. if (SIT(c, SQSYNTAX) == CCTL)
  10007. USTPUTC(CTLESC, out);
  10008. USTPUTC(c, out);
  10009. quotef = 1;
  10010. }
  10011. break;
  10012. case CSQUOTE:
  10013. syntax = SQSYNTAX;
  10014. quotemark:
  10015. if (eofmark == NULL) {
  10016. USTPUTC(CTLQUOTEMARK, out);
  10017. }
  10018. break;
  10019. case CDQUOTE:
  10020. syntax = DQSYNTAX;
  10021. dblquote = 1;
  10022. goto quotemark;
  10023. case CENDQUOTE:
  10024. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  10025. if (eofmark != NULL && arinest == 0
  10026. && varnest == 0
  10027. ) {
  10028. USTPUTC(c, out);
  10029. } else {
  10030. if (dqvarnest == 0) {
  10031. syntax = BASESYNTAX;
  10032. dblquote = 0;
  10033. }
  10034. quotef = 1;
  10035. goto quotemark;
  10036. }
  10037. break;
  10038. case CVAR: /* '$' */
  10039. PARSESUB(); /* parse substitution */
  10040. break;
  10041. case CENDVAR: /* '}' */
  10042. if (varnest > 0) {
  10043. varnest--;
  10044. if (dqvarnest > 0) {
  10045. dqvarnest--;
  10046. }
  10047. USTPUTC(CTLENDVAR, out);
  10048. } else {
  10049. USTPUTC(c, out);
  10050. }
  10051. break;
  10052. #if ENABLE_SH_MATH_SUPPORT
  10053. case CLP: /* '(' in arithmetic */
  10054. parenlevel++;
  10055. USTPUTC(c, out);
  10056. break;
  10057. case CRP: /* ')' in arithmetic */
  10058. if (parenlevel > 0) {
  10059. USTPUTC(c, out);
  10060. --parenlevel;
  10061. } else {
  10062. if (pgetc() == ')') {
  10063. if (--arinest == 0) {
  10064. USTPUTC(CTLENDARI, out);
  10065. syntax = prevsyntax;
  10066. dblquote = (syntax == DQSYNTAX);
  10067. } else
  10068. USTPUTC(')', out);
  10069. } else {
  10070. /*
  10071. * unbalanced parens
  10072. * (don't 2nd guess - no error)
  10073. */
  10074. pungetc();
  10075. USTPUTC(')', out);
  10076. }
  10077. }
  10078. break;
  10079. #endif
  10080. case CBQUOTE: /* '`' */
  10081. PARSEBACKQOLD();
  10082. break;
  10083. case CENDFILE:
  10084. goto endword; /* exit outer loop */
  10085. case CIGN:
  10086. break;
  10087. default:
  10088. if (varnest == 0) {
  10089. #if ENABLE_ASH_BASH_COMPAT
  10090. if (c == '&') {
  10091. if (pgetc() == '>')
  10092. c = 0x100 + '>'; /* flag &> */
  10093. pungetc();
  10094. }
  10095. #endif
  10096. goto endword; /* exit outer loop */
  10097. }
  10098. IF_ASH_ALIAS(if (c != PEOA))
  10099. USTPUTC(c, out);
  10100. }
  10101. c = pgetc_fast();
  10102. } /* for (;;) */
  10103. }
  10104. endword:
  10105. #if ENABLE_SH_MATH_SUPPORT
  10106. if (syntax == ARISYNTAX)
  10107. raise_error_syntax("missing '))'");
  10108. #endif
  10109. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  10110. raise_error_syntax("unterminated quoted string");
  10111. if (varnest != 0) {
  10112. startlinno = g_parsefile->linno;
  10113. /* { */
  10114. raise_error_syntax("missing '}'");
  10115. }
  10116. USTPUTC('\0', out);
  10117. len = out - (char *)stackblock();
  10118. out = stackblock();
  10119. if (eofmark == NULL) {
  10120. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10121. && quotef == 0
  10122. ) {
  10123. if (isdigit_str9(out)) {
  10124. PARSEREDIR(); /* passed as params: out, c */
  10125. lasttoken = TREDIR;
  10126. return lasttoken;
  10127. }
  10128. /* else: non-number X seen, interpret it
  10129. * as "NNNX>file" = "NNNX >file" */
  10130. }
  10131. pungetc();
  10132. }
  10133. quoteflag = quotef;
  10134. backquotelist = bqlist;
  10135. grabstackblock(len);
  10136. wordtext = out;
  10137. lasttoken = TWORD;
  10138. return lasttoken;
  10139. /* end of readtoken routine */
  10140. /*
  10141. * Check to see whether we are at the end of the here document. When this
  10142. * is called, c is set to the first character of the next input line. If
  10143. * we are at the end of the here document, this routine sets the c to PEOF.
  10144. */
  10145. checkend: {
  10146. if (eofmark) {
  10147. #if ENABLE_ASH_ALIAS
  10148. if (c == PEOA)
  10149. c = pgetc_without_PEOA();
  10150. #endif
  10151. if (striptabs) {
  10152. while (c == '\t') {
  10153. c = pgetc_without_PEOA();
  10154. }
  10155. }
  10156. if (c == *eofmark) {
  10157. if (pfgets(line, sizeof(line)) != NULL) {
  10158. char *p, *q;
  10159. p = line;
  10160. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10161. continue;
  10162. if (*p == '\n' && *q == '\0') {
  10163. c = PEOF;
  10164. g_parsefile->linno++;
  10165. needprompt = doprompt;
  10166. } else {
  10167. pushstring(line, NULL);
  10168. }
  10169. }
  10170. }
  10171. }
  10172. goto checkend_return;
  10173. }
  10174. /*
  10175. * Parse a redirection operator. The variable "out" points to a string
  10176. * specifying the fd to be redirected. The variable "c" contains the
  10177. * first character of the redirection operator.
  10178. */
  10179. parseredir: {
  10180. /* out is already checked to be a valid number or "" */
  10181. int fd = (*out == '\0' ? -1 : atoi(out));
  10182. union node *np;
  10183. np = stzalloc(sizeof(struct nfile));
  10184. if (c == '>') {
  10185. np->nfile.fd = 1;
  10186. c = pgetc();
  10187. if (c == '>')
  10188. np->type = NAPPEND;
  10189. else if (c == '|')
  10190. np->type = NCLOBBER;
  10191. else if (c == '&')
  10192. np->type = NTOFD;
  10193. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10194. else {
  10195. np->type = NTO;
  10196. pungetc();
  10197. }
  10198. }
  10199. #if ENABLE_ASH_BASH_COMPAT
  10200. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10201. np->nfile.fd = 1;
  10202. pgetc(); /* this is '>', no need to check */
  10203. np->type = NTO2;
  10204. }
  10205. #endif
  10206. else { /* c == '<' */
  10207. /*np->nfile.fd = 0; - stzalloc did it */
  10208. c = pgetc();
  10209. switch (c) {
  10210. case '<':
  10211. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10212. np = stzalloc(sizeof(struct nhere));
  10213. /*np->nfile.fd = 0; - stzalloc did it */
  10214. }
  10215. np->type = NHERE;
  10216. heredoc = stzalloc(sizeof(struct heredoc));
  10217. heredoc->here = np;
  10218. c = pgetc();
  10219. if (c == '-') {
  10220. heredoc->striptabs = 1;
  10221. } else {
  10222. /*heredoc->striptabs = 0; - stzalloc did it */
  10223. pungetc();
  10224. }
  10225. break;
  10226. case '&':
  10227. np->type = NFROMFD;
  10228. break;
  10229. case '>':
  10230. np->type = NFROMTO;
  10231. break;
  10232. default:
  10233. np->type = NFROM;
  10234. pungetc();
  10235. break;
  10236. }
  10237. }
  10238. if (fd >= 0)
  10239. np->nfile.fd = fd;
  10240. redirnode = np;
  10241. goto parseredir_return;
  10242. }
  10243. /*
  10244. * Parse a substitution. At this point, we have read the dollar sign
  10245. * and nothing else.
  10246. */
  10247. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10248. * (assuming ascii char codes, as the original implementation did) */
  10249. #define is_special(c) \
  10250. (((unsigned)(c) - 33 < 32) \
  10251. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10252. parsesub: {
  10253. unsigned char subtype;
  10254. int typeloc;
  10255. int flags;
  10256. char *p;
  10257. static const char types[] ALIGN1 = "}-+?=";
  10258. c = pgetc();
  10259. if (c > 255 /* PEOA or PEOF */
  10260. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10261. ) {
  10262. #if ENABLE_ASH_BASH_COMPAT
  10263. if (c == '\'')
  10264. bash_dollar_squote = 1;
  10265. else
  10266. #endif
  10267. USTPUTC('$', out);
  10268. pungetc();
  10269. } else if (c == '(') { /* $(command) or $((arith)) */
  10270. if (pgetc() == '(') {
  10271. #if ENABLE_SH_MATH_SUPPORT
  10272. PARSEARITH();
  10273. #else
  10274. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10275. #endif
  10276. } else {
  10277. pungetc();
  10278. PARSEBACKQNEW();
  10279. }
  10280. } else {
  10281. USTPUTC(CTLVAR, out);
  10282. typeloc = out - (char *)stackblock();
  10283. USTPUTC(VSNORMAL, out);
  10284. subtype = VSNORMAL;
  10285. if (c == '{') {
  10286. c = pgetc();
  10287. if (c == '#') {
  10288. c = pgetc();
  10289. if (c == '}')
  10290. c = '#';
  10291. else
  10292. subtype = VSLENGTH;
  10293. } else
  10294. subtype = 0;
  10295. }
  10296. if (c <= 255 /* not PEOA or PEOF */ && is_name(c)) {
  10297. do {
  10298. STPUTC(c, out);
  10299. c = pgetc();
  10300. } while (c <= 255 /* not PEOA or PEOF */ && is_in_name(c));
  10301. } else if (isdigit(c)) {
  10302. do {
  10303. STPUTC(c, out);
  10304. c = pgetc();
  10305. } while (isdigit(c));
  10306. } else if (is_special(c)) {
  10307. USTPUTC(c, out);
  10308. c = pgetc();
  10309. } else {
  10310. badsub:
  10311. raise_error_syntax("bad substitution");
  10312. }
  10313. if (c != '}' && subtype == VSLENGTH)
  10314. goto badsub;
  10315. STPUTC('=', out);
  10316. flags = 0;
  10317. if (subtype == 0) {
  10318. switch (c) {
  10319. case ':':
  10320. c = pgetc();
  10321. #if ENABLE_ASH_BASH_COMPAT
  10322. if (c == ':' || c == '$' || isdigit(c)) {
  10323. pungetc();
  10324. subtype = VSSUBSTR;
  10325. break;
  10326. }
  10327. #endif
  10328. flags = VSNUL;
  10329. /*FALLTHROUGH*/
  10330. default:
  10331. p = strchr(types, c);
  10332. if (p == NULL)
  10333. goto badsub;
  10334. subtype = p - types + VSNORMAL;
  10335. break;
  10336. case '%':
  10337. case '#': {
  10338. int cc = c;
  10339. subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
  10340. c = pgetc();
  10341. if (c == cc)
  10342. subtype++;
  10343. else
  10344. pungetc();
  10345. break;
  10346. }
  10347. #if ENABLE_ASH_BASH_COMPAT
  10348. case '/':
  10349. subtype = VSREPLACE;
  10350. c = pgetc();
  10351. if (c == '/')
  10352. subtype++; /* VSREPLACEALL */
  10353. else
  10354. pungetc();
  10355. break;
  10356. #endif
  10357. }
  10358. } else {
  10359. pungetc();
  10360. }
  10361. if (dblquote || arinest)
  10362. flags |= VSQUOTE;
  10363. ((unsigned char *)stackblock())[typeloc] = subtype | flags;
  10364. if (subtype != VSNORMAL) {
  10365. varnest++;
  10366. if (dblquote || arinest) {
  10367. dqvarnest++;
  10368. }
  10369. }
  10370. }
  10371. goto parsesub_return;
  10372. }
  10373. /*
  10374. * Called to parse command substitutions. Newstyle is set if the command
  10375. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10376. * list of commands (passed by reference), and savelen is the number of
  10377. * characters on the top of the stack which must be preserved.
  10378. */
  10379. parsebackq: {
  10380. struct nodelist **nlpp;
  10381. smallint savepbq;
  10382. union node *n;
  10383. char *volatile str;
  10384. struct jmploc jmploc;
  10385. struct jmploc *volatile savehandler;
  10386. size_t savelen;
  10387. smallint saveprompt = 0;
  10388. #ifdef __GNUC__
  10389. (void) &saveprompt;
  10390. #endif
  10391. savepbq = parsebackquote;
  10392. if (setjmp(jmploc.loc)) {
  10393. free(str);
  10394. parsebackquote = 0;
  10395. exception_handler = savehandler;
  10396. longjmp(exception_handler->loc, 1);
  10397. }
  10398. INT_OFF;
  10399. str = NULL;
  10400. savelen = out - (char *)stackblock();
  10401. if (savelen > 0) {
  10402. str = ckmalloc(savelen);
  10403. memcpy(str, stackblock(), savelen);
  10404. }
  10405. savehandler = exception_handler;
  10406. exception_handler = &jmploc;
  10407. INT_ON;
  10408. if (oldstyle) {
  10409. /* We must read until the closing backquote, giving special
  10410. treatment to some slashes, and then push the string and
  10411. reread it as input, interpreting it normally. */
  10412. char *pout;
  10413. int pc;
  10414. size_t psavelen;
  10415. char *pstr;
  10416. STARTSTACKSTR(pout);
  10417. for (;;) {
  10418. if (needprompt) {
  10419. setprompt(2);
  10420. }
  10421. pc = pgetc();
  10422. switch (pc) {
  10423. case '`':
  10424. goto done;
  10425. case '\\':
  10426. pc = pgetc();
  10427. if (pc == '\n') {
  10428. g_parsefile->linno++;
  10429. if (doprompt)
  10430. setprompt(2);
  10431. /*
  10432. * If eating a newline, avoid putting
  10433. * the newline into the new character
  10434. * stream (via the STPUTC after the
  10435. * switch).
  10436. */
  10437. continue;
  10438. }
  10439. if (pc != '\\' && pc != '`' && pc != '$'
  10440. && (!dblquote || pc != '"')
  10441. ) {
  10442. STPUTC('\\', pout);
  10443. }
  10444. if (pc <= 255 /* not PEOA or PEOF */) {
  10445. break;
  10446. }
  10447. /* fall through */
  10448. case PEOF:
  10449. IF_ASH_ALIAS(case PEOA:)
  10450. startlinno = g_parsefile->linno;
  10451. raise_error_syntax("EOF in backquote substitution");
  10452. case '\n':
  10453. g_parsefile->linno++;
  10454. needprompt = doprompt;
  10455. break;
  10456. default:
  10457. break;
  10458. }
  10459. STPUTC(pc, pout);
  10460. }
  10461. done:
  10462. STPUTC('\0', pout);
  10463. psavelen = pout - (char *)stackblock();
  10464. if (psavelen > 0) {
  10465. pstr = grabstackstr(pout);
  10466. setinputstring(pstr);
  10467. }
  10468. }
  10469. nlpp = &bqlist;
  10470. while (*nlpp)
  10471. nlpp = &(*nlpp)->next;
  10472. *nlpp = stzalloc(sizeof(**nlpp));
  10473. /* (*nlpp)->next = NULL; - stzalloc did it */
  10474. parsebackquote = oldstyle;
  10475. if (oldstyle) {
  10476. saveprompt = doprompt;
  10477. doprompt = 0;
  10478. }
  10479. n = list(2);
  10480. if (oldstyle)
  10481. doprompt = saveprompt;
  10482. else if (readtoken() != TRP)
  10483. raise_error_unexpected_syntax(TRP);
  10484. (*nlpp)->n = n;
  10485. if (oldstyle) {
  10486. /*
  10487. * Start reading from old file again, ignoring any pushed back
  10488. * tokens left from the backquote parsing
  10489. */
  10490. popfile();
  10491. tokpushback = 0;
  10492. }
  10493. while (stackblocksize() <= savelen)
  10494. growstackblock();
  10495. STARTSTACKSTR(out);
  10496. if (str) {
  10497. memcpy(out, str, savelen);
  10498. STADJUST(savelen, out);
  10499. INT_OFF;
  10500. free(str);
  10501. str = NULL;
  10502. INT_ON;
  10503. }
  10504. parsebackquote = savepbq;
  10505. exception_handler = savehandler;
  10506. if (arinest || dblquote)
  10507. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10508. else
  10509. USTPUTC(CTLBACKQ, out);
  10510. if (oldstyle)
  10511. goto parsebackq_oldreturn;
  10512. goto parsebackq_newreturn;
  10513. }
  10514. #if ENABLE_SH_MATH_SUPPORT
  10515. /*
  10516. * Parse an arithmetic expansion (indicate start of one and set state)
  10517. */
  10518. parsearith: {
  10519. if (++arinest == 1) {
  10520. prevsyntax = syntax;
  10521. syntax = ARISYNTAX;
  10522. USTPUTC(CTLARI, out);
  10523. if (dblquote)
  10524. USTPUTC('"', out);
  10525. else
  10526. USTPUTC(' ', out);
  10527. } else {
  10528. /*
  10529. * we collapse embedded arithmetic expansion to
  10530. * parenthesis, which should be equivalent
  10531. */
  10532. USTPUTC('(', out);
  10533. }
  10534. goto parsearith_return;
  10535. }
  10536. #endif
  10537. } /* end of readtoken */
  10538. /*
  10539. * Read the next input token.
  10540. * If the token is a word, we set backquotelist to the list of cmds in
  10541. * backquotes. We set quoteflag to true if any part of the word was
  10542. * quoted.
  10543. * If the token is TREDIR, then we set redirnode to a structure containing
  10544. * the redirection.
  10545. * In all cases, the variable startlinno is set to the number of the line
  10546. * on which the token starts.
  10547. *
  10548. * [Change comment: here documents and internal procedures]
  10549. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10550. * word parsing code into a separate routine. In this case, readtoken
  10551. * doesn't need to have any internal procedures, but parseword does.
  10552. * We could also make parseoperator in essence the main routine, and
  10553. * have parseword (readtoken1?) handle both words and redirection.]
  10554. */
  10555. #define NEW_xxreadtoken
  10556. #ifdef NEW_xxreadtoken
  10557. /* singles must be first! */
  10558. static const char xxreadtoken_chars[7] ALIGN1 = {
  10559. '\n', '(', ')', /* singles */
  10560. '&', '|', ';', /* doubles */
  10561. 0
  10562. };
  10563. #define xxreadtoken_singles 3
  10564. #define xxreadtoken_doubles 3
  10565. static const char xxreadtoken_tokens[] ALIGN1 = {
  10566. TNL, TLP, TRP, /* only single occurrence allowed */
  10567. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10568. TEOF, /* corresponds to trailing nul */
  10569. TAND, TOR, TENDCASE /* if double occurrence */
  10570. };
  10571. static int
  10572. xxreadtoken(void)
  10573. {
  10574. int c;
  10575. if (tokpushback) {
  10576. tokpushback = 0;
  10577. return lasttoken;
  10578. }
  10579. if (needprompt) {
  10580. setprompt(2);
  10581. }
  10582. startlinno = g_parsefile->linno;
  10583. for (;;) { /* until token or start of word found */
  10584. c = pgetc_fast();
  10585. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10586. continue;
  10587. if (c == '#') {
  10588. while ((c = pgetc()) != '\n' && c != PEOF)
  10589. continue;
  10590. pungetc();
  10591. } else if (c == '\\') {
  10592. if (pgetc() != '\n') {
  10593. pungetc();
  10594. break; /* return readtoken1(...) */
  10595. }
  10596. startlinno = ++g_parsefile->linno;
  10597. if (doprompt)
  10598. setprompt(2);
  10599. } else {
  10600. const char *p;
  10601. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10602. if (c != PEOF) {
  10603. if (c == '\n') {
  10604. g_parsefile->linno++;
  10605. needprompt = doprompt;
  10606. }
  10607. p = strchr(xxreadtoken_chars, c);
  10608. if (p == NULL)
  10609. break; /* return readtoken1(...) */
  10610. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10611. int cc = pgetc();
  10612. if (cc == c) { /* double occurrence? */
  10613. p += xxreadtoken_doubles + 1;
  10614. } else {
  10615. pungetc();
  10616. #if ENABLE_ASH_BASH_COMPAT
  10617. if (c == '&' && cc == '>') /* &> */
  10618. break; /* return readtoken1(...) */
  10619. #endif
  10620. }
  10621. }
  10622. }
  10623. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10624. return lasttoken;
  10625. }
  10626. } /* for (;;) */
  10627. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10628. }
  10629. #else /* old xxreadtoken */
  10630. #define RETURN(token) return lasttoken = token
  10631. static int
  10632. xxreadtoken(void)
  10633. {
  10634. int c;
  10635. if (tokpushback) {
  10636. tokpushback = 0;
  10637. return lasttoken;
  10638. }
  10639. if (needprompt) {
  10640. setprompt(2);
  10641. }
  10642. startlinno = g_parsefile->linno;
  10643. for (;;) { /* until token or start of word found */
  10644. c = pgetc_fast();
  10645. switch (c) {
  10646. case ' ': case '\t':
  10647. IF_ASH_ALIAS(case PEOA:)
  10648. continue;
  10649. case '#':
  10650. while ((c = pgetc()) != '\n' && c != PEOF)
  10651. continue;
  10652. pungetc();
  10653. continue;
  10654. case '\\':
  10655. if (pgetc() == '\n') {
  10656. startlinno = ++g_parsefile->linno;
  10657. if (doprompt)
  10658. setprompt(2);
  10659. continue;
  10660. }
  10661. pungetc();
  10662. goto breakloop;
  10663. case '\n':
  10664. g_parsefile->linno++;
  10665. needprompt = doprompt;
  10666. RETURN(TNL);
  10667. case PEOF:
  10668. RETURN(TEOF);
  10669. case '&':
  10670. if (pgetc() == '&')
  10671. RETURN(TAND);
  10672. pungetc();
  10673. RETURN(TBACKGND);
  10674. case '|':
  10675. if (pgetc() == '|')
  10676. RETURN(TOR);
  10677. pungetc();
  10678. RETURN(TPIPE);
  10679. case ';':
  10680. if (pgetc() == ';')
  10681. RETURN(TENDCASE);
  10682. pungetc();
  10683. RETURN(TSEMI);
  10684. case '(':
  10685. RETURN(TLP);
  10686. case ')':
  10687. RETURN(TRP);
  10688. default:
  10689. goto breakloop;
  10690. }
  10691. }
  10692. breakloop:
  10693. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10694. #undef RETURN
  10695. }
  10696. #endif /* old xxreadtoken */
  10697. static int
  10698. readtoken(void)
  10699. {
  10700. int t;
  10701. #if DEBUG
  10702. smallint alreadyseen = tokpushback;
  10703. #endif
  10704. #if ENABLE_ASH_ALIAS
  10705. top:
  10706. #endif
  10707. t = xxreadtoken();
  10708. /*
  10709. * eat newlines
  10710. */
  10711. if (checkkwd & CHKNL) {
  10712. while (t == TNL) {
  10713. parseheredoc();
  10714. t = xxreadtoken();
  10715. }
  10716. }
  10717. if (t != TWORD || quoteflag) {
  10718. goto out;
  10719. }
  10720. /*
  10721. * check for keywords
  10722. */
  10723. if (checkkwd & CHKKWD) {
  10724. const char *const *pp;
  10725. pp = findkwd(wordtext);
  10726. if (pp) {
  10727. lasttoken = t = pp - tokname_array;
  10728. TRACE(("keyword %s recognized\n", tokname(t)));
  10729. goto out;
  10730. }
  10731. }
  10732. if (checkkwd & CHKALIAS) {
  10733. #if ENABLE_ASH_ALIAS
  10734. struct alias *ap;
  10735. ap = lookupalias(wordtext, 1);
  10736. if (ap != NULL) {
  10737. if (*ap->val) {
  10738. pushstring(ap->val, ap);
  10739. }
  10740. goto top;
  10741. }
  10742. #endif
  10743. }
  10744. out:
  10745. checkkwd = 0;
  10746. #if DEBUG
  10747. if (!alreadyseen)
  10748. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10749. else
  10750. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10751. #endif
  10752. return t;
  10753. }
  10754. static char
  10755. peektoken(void)
  10756. {
  10757. int t;
  10758. t = readtoken();
  10759. tokpushback = 1;
  10760. return tokname_array[t][0];
  10761. }
  10762. /*
  10763. * Read and parse a command. Returns NODE_EOF on end of file.
  10764. * (NULL is a valid parse tree indicating a blank line.)
  10765. */
  10766. static union node *
  10767. parsecmd(int interact)
  10768. {
  10769. int t;
  10770. tokpushback = 0;
  10771. doprompt = interact;
  10772. if (doprompt)
  10773. setprompt(doprompt);
  10774. needprompt = 0;
  10775. t = readtoken();
  10776. if (t == TEOF)
  10777. return NODE_EOF;
  10778. if (t == TNL)
  10779. return NULL;
  10780. tokpushback = 1;
  10781. return list(1);
  10782. }
  10783. /*
  10784. * Input any here documents.
  10785. */
  10786. static void
  10787. parseheredoc(void)
  10788. {
  10789. struct heredoc *here;
  10790. union node *n;
  10791. here = heredoclist;
  10792. heredoclist = NULL;
  10793. while (here) {
  10794. if (needprompt) {
  10795. setprompt(2);
  10796. }
  10797. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  10798. here->eofmark, here->striptabs);
  10799. n = stzalloc(sizeof(struct narg));
  10800. n->narg.type = NARG;
  10801. /*n->narg.next = NULL; - stzalloc did it */
  10802. n->narg.text = wordtext;
  10803. n->narg.backquote = backquotelist;
  10804. here->here->nhere.doc = n;
  10805. here = here->next;
  10806. }
  10807. }
  10808. /*
  10809. * called by editline -- any expansions to the prompt should be added here.
  10810. */
  10811. #if ENABLE_ASH_EXPAND_PRMT
  10812. static const char *
  10813. expandstr(const char *ps)
  10814. {
  10815. union node n;
  10816. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  10817. * and token processing _can_ alter it (delete NULs etc). */
  10818. setinputstring((char *)ps);
  10819. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  10820. popfile();
  10821. n.narg.type = NARG;
  10822. n.narg.next = NULL;
  10823. n.narg.text = wordtext;
  10824. n.narg.backquote = backquotelist;
  10825. expandarg(&n, NULL, 0);
  10826. return stackblock();
  10827. }
  10828. #endif
  10829. /*
  10830. * Execute a command or commands contained in a string.
  10831. */
  10832. static int
  10833. evalstring(char *s, int mask)
  10834. {
  10835. union node *n;
  10836. struct stackmark smark;
  10837. int skip;
  10838. setinputstring(s);
  10839. setstackmark(&smark);
  10840. skip = 0;
  10841. while ((n = parsecmd(0)) != NODE_EOF) {
  10842. evaltree(n, 0);
  10843. popstackmark(&smark);
  10844. skip = evalskip;
  10845. if (skip)
  10846. break;
  10847. }
  10848. popfile();
  10849. skip &= mask;
  10850. evalskip = skip;
  10851. return skip;
  10852. }
  10853. /*
  10854. * The eval command.
  10855. */
  10856. static int FAST_FUNC
  10857. evalcmd(int argc UNUSED_PARAM, char **argv)
  10858. {
  10859. char *p;
  10860. char *concat;
  10861. if (argv[1]) {
  10862. p = argv[1];
  10863. argv += 2;
  10864. if (argv[0]) {
  10865. STARTSTACKSTR(concat);
  10866. for (;;) {
  10867. concat = stack_putstr(p, concat);
  10868. p = *argv++;
  10869. if (p == NULL)
  10870. break;
  10871. STPUTC(' ', concat);
  10872. }
  10873. STPUTC('\0', concat);
  10874. p = grabstackstr(concat);
  10875. }
  10876. evalstring(p, ~SKIPEVAL);
  10877. }
  10878. return exitstatus;
  10879. }
  10880. /*
  10881. * Read and execute commands.
  10882. * "Top" is nonzero for the top level command loop;
  10883. * it turns on prompting if the shell is interactive.
  10884. */
  10885. static int
  10886. cmdloop(int top)
  10887. {
  10888. union node *n;
  10889. struct stackmark smark;
  10890. int inter;
  10891. int numeof = 0;
  10892. TRACE(("cmdloop(%d) called\n", top));
  10893. for (;;) {
  10894. int skip;
  10895. setstackmark(&smark);
  10896. #if JOBS
  10897. if (doing_jobctl)
  10898. showjobs(stderr, SHOW_CHANGED);
  10899. #endif
  10900. inter = 0;
  10901. if (iflag && top) {
  10902. inter++;
  10903. #if ENABLE_ASH_MAIL
  10904. chkmail();
  10905. #endif
  10906. }
  10907. n = parsecmd(inter);
  10908. #if DEBUG
  10909. if (DEBUG > 2 && debug && (n != NODE_EOF))
  10910. showtree(n);
  10911. #endif
  10912. if (n == NODE_EOF) {
  10913. if (!top || numeof >= 50)
  10914. break;
  10915. if (!stoppedjobs()) {
  10916. if (!Iflag)
  10917. break;
  10918. out2str("\nUse \"exit\" to leave shell.\n");
  10919. }
  10920. numeof++;
  10921. } else if (nflag == 0) {
  10922. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  10923. job_warning >>= 1;
  10924. numeof = 0;
  10925. evaltree(n, 0);
  10926. }
  10927. popstackmark(&smark);
  10928. skip = evalskip;
  10929. if (skip) {
  10930. evalskip = 0;
  10931. return skip & SKIPEVAL;
  10932. }
  10933. }
  10934. return 0;
  10935. }
  10936. /*
  10937. * Take commands from a file. To be compatible we should do a path
  10938. * search for the file, which is necessary to find sub-commands.
  10939. */
  10940. static char *
  10941. find_dot_file(char *name)
  10942. {
  10943. char *fullname;
  10944. const char *path = pathval();
  10945. struct stat statb;
  10946. /* don't try this for absolute or relative paths */
  10947. if (strchr(name, '/'))
  10948. return name;
  10949. /* IIRC standards do not say whether . is to be searched.
  10950. * And it is even smaller this way, making it unconditional for now:
  10951. */
  10952. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  10953. fullname = name;
  10954. goto try_cur_dir;
  10955. }
  10956. while ((fullname = path_advance(&path, name)) != NULL) {
  10957. try_cur_dir:
  10958. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  10959. /*
  10960. * Don't bother freeing here, since it will
  10961. * be freed by the caller.
  10962. */
  10963. return fullname;
  10964. }
  10965. if (fullname != name)
  10966. stunalloc(fullname);
  10967. }
  10968. /* not found in the PATH */
  10969. ash_msg_and_raise_error("%s: not found", name);
  10970. /* NOTREACHED */
  10971. }
  10972. static int FAST_FUNC
  10973. dotcmd(int argc, char **argv)
  10974. {
  10975. struct strlist *sp;
  10976. volatile struct shparam saveparam;
  10977. int status = 0;
  10978. for (sp = cmdenviron; sp; sp = sp->next)
  10979. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  10980. if (argv[1]) { /* That's what SVR2 does */
  10981. char *fullname = find_dot_file(argv[1]);
  10982. argv += 2;
  10983. argc -= 2;
  10984. if (argc) { /* argc > 0, argv[0] != NULL */
  10985. saveparam = shellparam;
  10986. shellparam.malloced = 0;
  10987. shellparam.nparam = argc;
  10988. shellparam.p = argv;
  10989. };
  10990. setinputfile(fullname, INPUT_PUSH_FILE);
  10991. commandname = fullname;
  10992. cmdloop(0);
  10993. popfile();
  10994. if (argc) {
  10995. freeparam(&shellparam);
  10996. shellparam = saveparam;
  10997. };
  10998. status = exitstatus;
  10999. }
  11000. return status;
  11001. }
  11002. static int FAST_FUNC
  11003. exitcmd(int argc UNUSED_PARAM, char **argv)
  11004. {
  11005. if (stoppedjobs())
  11006. return 0;
  11007. if (argv[1])
  11008. exitstatus = number(argv[1]);
  11009. raise_exception(EXEXIT);
  11010. /* NOTREACHED */
  11011. }
  11012. /*
  11013. * Read a file containing shell functions.
  11014. */
  11015. static void
  11016. readcmdfile(char *name)
  11017. {
  11018. setinputfile(name, INPUT_PUSH_FILE);
  11019. cmdloop(0);
  11020. popfile();
  11021. }
  11022. /* ============ find_command inplementation */
  11023. /*
  11024. * Resolve a command name. If you change this routine, you may have to
  11025. * change the shellexec routine as well.
  11026. */
  11027. static void
  11028. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11029. {
  11030. struct tblentry *cmdp;
  11031. int idx;
  11032. int prev;
  11033. char *fullname;
  11034. struct stat statb;
  11035. int e;
  11036. int updatetbl;
  11037. struct builtincmd *bcmd;
  11038. /* If name contains a slash, don't use PATH or hash table */
  11039. if (strchr(name, '/') != NULL) {
  11040. entry->u.index = -1;
  11041. if (act & DO_ABS) {
  11042. while (stat(name, &statb) < 0) {
  11043. #ifdef SYSV
  11044. if (errno == EINTR)
  11045. continue;
  11046. #endif
  11047. entry->cmdtype = CMDUNKNOWN;
  11048. return;
  11049. }
  11050. }
  11051. entry->cmdtype = CMDNORMAL;
  11052. return;
  11053. }
  11054. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11055. updatetbl = (path == pathval());
  11056. if (!updatetbl) {
  11057. act |= DO_ALTPATH;
  11058. if (strstr(path, "%builtin") != NULL)
  11059. act |= DO_ALTBLTIN;
  11060. }
  11061. /* If name is in the table, check answer will be ok */
  11062. cmdp = cmdlookup(name, 0);
  11063. if (cmdp != NULL) {
  11064. int bit;
  11065. switch (cmdp->cmdtype) {
  11066. default:
  11067. #if DEBUG
  11068. abort();
  11069. #endif
  11070. case CMDNORMAL:
  11071. bit = DO_ALTPATH;
  11072. break;
  11073. case CMDFUNCTION:
  11074. bit = DO_NOFUNC;
  11075. break;
  11076. case CMDBUILTIN:
  11077. bit = DO_ALTBLTIN;
  11078. break;
  11079. }
  11080. if (act & bit) {
  11081. updatetbl = 0;
  11082. cmdp = NULL;
  11083. } else if (cmdp->rehash == 0)
  11084. /* if not invalidated by cd, we're done */
  11085. goto success;
  11086. }
  11087. /* If %builtin not in path, check for builtin next */
  11088. bcmd = find_builtin(name);
  11089. if (bcmd) {
  11090. if (IS_BUILTIN_REGULAR(bcmd))
  11091. goto builtin_success;
  11092. if (act & DO_ALTPATH) {
  11093. if (!(act & DO_ALTBLTIN))
  11094. goto builtin_success;
  11095. } else if (builtinloc <= 0) {
  11096. goto builtin_success;
  11097. }
  11098. }
  11099. #if ENABLE_FEATURE_SH_STANDALONE
  11100. {
  11101. int applet_no = find_applet_by_name(name);
  11102. if (applet_no >= 0) {
  11103. entry->cmdtype = CMDNORMAL;
  11104. entry->u.index = -2 - applet_no;
  11105. return;
  11106. }
  11107. }
  11108. #endif
  11109. /* We have to search path. */
  11110. prev = -1; /* where to start */
  11111. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11112. if (cmdp->cmdtype == CMDBUILTIN)
  11113. prev = builtinloc;
  11114. else
  11115. prev = cmdp->param.index;
  11116. }
  11117. e = ENOENT;
  11118. idx = -1;
  11119. loop:
  11120. while ((fullname = path_advance(&path, name)) != NULL) {
  11121. stunalloc(fullname);
  11122. /* NB: code below will still use fullname
  11123. * despite it being "unallocated" */
  11124. idx++;
  11125. if (pathopt) {
  11126. if (prefix(pathopt, "builtin")) {
  11127. if (bcmd)
  11128. goto builtin_success;
  11129. continue;
  11130. }
  11131. if ((act & DO_NOFUNC)
  11132. || !prefix(pathopt, "func")
  11133. ) { /* ignore unimplemented options */
  11134. continue;
  11135. }
  11136. }
  11137. /* if rehash, don't redo absolute path names */
  11138. if (fullname[0] == '/' && idx <= prev) {
  11139. if (idx < prev)
  11140. continue;
  11141. TRACE(("searchexec \"%s\": no change\n", name));
  11142. goto success;
  11143. }
  11144. while (stat(fullname, &statb) < 0) {
  11145. #ifdef SYSV
  11146. if (errno == EINTR)
  11147. continue;
  11148. #endif
  11149. if (errno != ENOENT && errno != ENOTDIR)
  11150. e = errno;
  11151. goto loop;
  11152. }
  11153. e = EACCES; /* if we fail, this will be the error */
  11154. if (!S_ISREG(statb.st_mode))
  11155. continue;
  11156. if (pathopt) { /* this is a %func directory */
  11157. stalloc(strlen(fullname) + 1);
  11158. /* NB: stalloc will return space pointed by fullname
  11159. * (because we don't have any intervening allocations
  11160. * between stunalloc above and this stalloc) */
  11161. readcmdfile(fullname);
  11162. cmdp = cmdlookup(name, 0);
  11163. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11164. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11165. stunalloc(fullname);
  11166. goto success;
  11167. }
  11168. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11169. if (!updatetbl) {
  11170. entry->cmdtype = CMDNORMAL;
  11171. entry->u.index = idx;
  11172. return;
  11173. }
  11174. INT_OFF;
  11175. cmdp = cmdlookup(name, 1);
  11176. cmdp->cmdtype = CMDNORMAL;
  11177. cmdp->param.index = idx;
  11178. INT_ON;
  11179. goto success;
  11180. }
  11181. /* We failed. If there was an entry for this command, delete it */
  11182. if (cmdp && updatetbl)
  11183. delete_cmd_entry();
  11184. if (act & DO_ERR)
  11185. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11186. entry->cmdtype = CMDUNKNOWN;
  11187. return;
  11188. builtin_success:
  11189. if (!updatetbl) {
  11190. entry->cmdtype = CMDBUILTIN;
  11191. entry->u.cmd = bcmd;
  11192. return;
  11193. }
  11194. INT_OFF;
  11195. cmdp = cmdlookup(name, 1);
  11196. cmdp->cmdtype = CMDBUILTIN;
  11197. cmdp->param.cmd = bcmd;
  11198. INT_ON;
  11199. success:
  11200. cmdp->rehash = 0;
  11201. entry->cmdtype = cmdp->cmdtype;
  11202. entry->u = cmdp->param;
  11203. }
  11204. /* ============ trap.c */
  11205. /*
  11206. * The trap builtin.
  11207. */
  11208. static int FAST_FUNC
  11209. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11210. {
  11211. char *action;
  11212. char **ap;
  11213. int signo;
  11214. nextopt(nullstr);
  11215. ap = argptr;
  11216. if (!*ap) {
  11217. for (signo = 0; signo < NSIG; signo++) {
  11218. char *tr = trap_ptr[signo];
  11219. if (tr) {
  11220. /* note: bash adds "SIG", but only if invoked
  11221. * as "bash". If called as "sh", or if set -o posix,
  11222. * then it prints short signal names.
  11223. * We are printing short names: */
  11224. out1fmt("trap -- %s %s\n",
  11225. single_quote(tr),
  11226. get_signame(signo));
  11227. /* trap_ptr != trap only if we are in special-cased `trap` code.
  11228. * In this case, we will exit very soon, no need to free(). */
  11229. /* if (trap_ptr != trap && tp[0]) */
  11230. /* free(tr); */
  11231. }
  11232. }
  11233. /*
  11234. if (trap_ptr != trap) {
  11235. free(trap_ptr);
  11236. trap_ptr = trap;
  11237. }
  11238. */
  11239. return 0;
  11240. }
  11241. action = NULL;
  11242. if (ap[1])
  11243. action = *ap++;
  11244. while (*ap) {
  11245. signo = get_signum(*ap);
  11246. if (signo < 0)
  11247. ash_msg_and_raise_error("%s: bad trap", *ap);
  11248. INT_OFF;
  11249. if (action) {
  11250. if (LONE_DASH(action))
  11251. action = NULL;
  11252. else
  11253. action = ckstrdup(action);
  11254. }
  11255. free(trap[signo]);
  11256. trap[signo] = action;
  11257. if (signo != 0)
  11258. setsignal(signo);
  11259. INT_ON;
  11260. ap++;
  11261. }
  11262. return 0;
  11263. }
  11264. /* ============ Builtins */
  11265. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11266. /*
  11267. * Lists available builtins
  11268. */
  11269. static int FAST_FUNC
  11270. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11271. {
  11272. unsigned col;
  11273. unsigned i;
  11274. out1fmt(
  11275. "Built-in commands:\n"
  11276. "------------------\n");
  11277. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11278. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11279. builtintab[i].name + 1);
  11280. if (col > 60) {
  11281. out1fmt("\n");
  11282. col = 0;
  11283. }
  11284. }
  11285. #if ENABLE_FEATURE_SH_STANDALONE
  11286. {
  11287. const char *a = applet_names;
  11288. while (*a) {
  11289. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11290. if (col > 60) {
  11291. out1fmt("\n");
  11292. col = 0;
  11293. }
  11294. a += strlen(a) + 1;
  11295. }
  11296. }
  11297. #endif
  11298. out1fmt("\n\n");
  11299. return EXIT_SUCCESS;
  11300. }
  11301. #endif /* FEATURE_SH_EXTRA_QUIET */
  11302. /*
  11303. * The export and readonly commands.
  11304. */
  11305. static int FAST_FUNC
  11306. exportcmd(int argc UNUSED_PARAM, char **argv)
  11307. {
  11308. struct var *vp;
  11309. char *name;
  11310. const char *p;
  11311. char **aptr;
  11312. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  11313. if (nextopt("p") != 'p') {
  11314. aptr = argptr;
  11315. name = *aptr;
  11316. if (name) {
  11317. do {
  11318. p = strchr(name, '=');
  11319. if (p != NULL) {
  11320. p++;
  11321. } else {
  11322. vp = *findvar(hashvar(name), name);
  11323. if (vp) {
  11324. vp->flags |= flag;
  11325. continue;
  11326. }
  11327. }
  11328. setvar(name, p, flag);
  11329. } while ((name = *++aptr) != NULL);
  11330. return 0;
  11331. }
  11332. }
  11333. showvars(argv[0], flag, 0);
  11334. return 0;
  11335. }
  11336. /*
  11337. * Delete a function if it exists.
  11338. */
  11339. static void
  11340. unsetfunc(const char *name)
  11341. {
  11342. struct tblentry *cmdp;
  11343. cmdp = cmdlookup(name, 0);
  11344. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  11345. delete_cmd_entry();
  11346. }
  11347. /*
  11348. * The unset builtin command. We unset the function before we unset the
  11349. * variable to allow a function to be unset when there is a readonly variable
  11350. * with the same name.
  11351. */
  11352. static int FAST_FUNC
  11353. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11354. {
  11355. char **ap;
  11356. int i;
  11357. int flag = 0;
  11358. int ret = 0;
  11359. while ((i = nextopt("vf")) != '\0') {
  11360. flag = i;
  11361. }
  11362. for (ap = argptr; *ap; ap++) {
  11363. if (flag != 'f') {
  11364. i = unsetvar(*ap);
  11365. ret |= i;
  11366. if (!(i & 2))
  11367. continue;
  11368. }
  11369. if (flag != 'v')
  11370. unsetfunc(*ap);
  11371. }
  11372. return ret & 1;
  11373. }
  11374. /* setmode.c */
  11375. #include <sys/times.h>
  11376. static const unsigned char timescmd_str[] ALIGN1 = {
  11377. ' ', offsetof(struct tms, tms_utime),
  11378. '\n', offsetof(struct tms, tms_stime),
  11379. ' ', offsetof(struct tms, tms_cutime),
  11380. '\n', offsetof(struct tms, tms_cstime),
  11381. 0
  11382. };
  11383. static int FAST_FUNC
  11384. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11385. {
  11386. long clk_tck, s, t;
  11387. const unsigned char *p;
  11388. struct tms buf;
  11389. clk_tck = sysconf(_SC_CLK_TCK);
  11390. times(&buf);
  11391. p = timescmd_str;
  11392. do {
  11393. t = *(clock_t *)(((char *) &buf) + p[1]);
  11394. s = t / clk_tck;
  11395. out1fmt("%ldm%ld.%.3lds%c",
  11396. s/60, s%60,
  11397. ((t - s * clk_tck) * 1000) / clk_tck,
  11398. p[0]);
  11399. } while (*(p += 2));
  11400. return 0;
  11401. }
  11402. #if ENABLE_SH_MATH_SUPPORT
  11403. /*
  11404. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  11405. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11406. *
  11407. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11408. */
  11409. static int FAST_FUNC
  11410. letcmd(int argc UNUSED_PARAM, char **argv)
  11411. {
  11412. arith_t i;
  11413. argv++;
  11414. if (!*argv)
  11415. ash_msg_and_raise_error("expression expected");
  11416. do {
  11417. i = ash_arith(*argv);
  11418. } while (*++argv);
  11419. return !i;
  11420. }
  11421. #endif /* SH_MATH_SUPPORT */
  11422. /* ============ miscbltin.c
  11423. *
  11424. * Miscellaneous builtins.
  11425. */
  11426. #undef rflag
  11427. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11428. typedef enum __rlimit_resource rlim_t;
  11429. #endif
  11430. /*
  11431. * The read builtin. Options:
  11432. * -r Do not interpret '\' specially
  11433. * -s Turn off echo (tty only)
  11434. * -n NCHARS Read NCHARS max
  11435. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11436. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11437. * -u FD Read from given FD instead of fd 0
  11438. * This uses unbuffered input, which may be avoidable in some cases.
  11439. * TODO: bash also has:
  11440. * -a ARRAY Read into array[0],[1],etc
  11441. * -d DELIM End on DELIM char, not newline
  11442. * -e Use line editing (tty only)
  11443. */
  11444. static int FAST_FUNC
  11445. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11446. {
  11447. char *opt_n = NULL;
  11448. char *opt_p = NULL;
  11449. char *opt_t = NULL;
  11450. char *opt_u = NULL;
  11451. int read_flags = 0;
  11452. const char *r;
  11453. int i;
  11454. while ((i = nextopt("p:u:rt:n:s")) != '\0') {
  11455. switch (i) {
  11456. case 'p':
  11457. opt_p = optionarg;
  11458. break;
  11459. case 'n':
  11460. opt_n = optionarg;
  11461. break;
  11462. case 's':
  11463. read_flags |= BUILTIN_READ_SILENT;
  11464. break;
  11465. case 't':
  11466. opt_t = optionarg;
  11467. break;
  11468. case 'r':
  11469. read_flags |= BUILTIN_READ_RAW;
  11470. break;
  11471. case 'u':
  11472. opt_u = optionarg;
  11473. break;
  11474. default:
  11475. break;
  11476. }
  11477. }
  11478. r = shell_builtin_read(setvar2,
  11479. argptr,
  11480. bltinlookup("IFS"), /* can be NULL */
  11481. read_flags,
  11482. opt_n,
  11483. opt_p,
  11484. opt_t,
  11485. opt_u
  11486. );
  11487. if ((uintptr_t)r > 1)
  11488. ash_msg_and_raise_error(r);
  11489. return (uintptr_t)r;
  11490. }
  11491. static int FAST_FUNC
  11492. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11493. {
  11494. static const char permuser[3] ALIGN1 = "ugo";
  11495. static const char permmode[3] ALIGN1 = "rwx";
  11496. static const short permmask[] ALIGN2 = {
  11497. S_IRUSR, S_IWUSR, S_IXUSR,
  11498. S_IRGRP, S_IWGRP, S_IXGRP,
  11499. S_IROTH, S_IWOTH, S_IXOTH
  11500. };
  11501. /* TODO: use bb_parse_mode() instead */
  11502. char *ap;
  11503. mode_t mask;
  11504. int i;
  11505. int symbolic_mode = 0;
  11506. while (nextopt("S") != '\0') {
  11507. symbolic_mode = 1;
  11508. }
  11509. INT_OFF;
  11510. mask = umask(0);
  11511. umask(mask);
  11512. INT_ON;
  11513. ap = *argptr;
  11514. if (ap == NULL) {
  11515. if (symbolic_mode) {
  11516. char buf[18];
  11517. char *p = buf;
  11518. for (i = 0; i < 3; i++) {
  11519. int j;
  11520. *p++ = permuser[i];
  11521. *p++ = '=';
  11522. for (j = 0; j < 3; j++) {
  11523. if ((mask & permmask[3 * i + j]) == 0) {
  11524. *p++ = permmode[j];
  11525. }
  11526. }
  11527. *p++ = ',';
  11528. }
  11529. *--p = 0;
  11530. puts(buf);
  11531. } else {
  11532. out1fmt("%.4o\n", mask);
  11533. }
  11534. } else {
  11535. if (isdigit((unsigned char) *ap)) {
  11536. mask = 0;
  11537. do {
  11538. if (*ap >= '8' || *ap < '0')
  11539. ash_msg_and_raise_error(msg_illnum, argv[1]);
  11540. mask = (mask << 3) + (*ap - '0');
  11541. } while (*++ap != '\0');
  11542. umask(mask);
  11543. } else {
  11544. mask = ~mask & 0777;
  11545. if (!bb_parse_mode(ap, &mask)) {
  11546. ash_msg_and_raise_error("illegal mode: %s", ap);
  11547. }
  11548. umask(~mask & 0777);
  11549. }
  11550. }
  11551. return 0;
  11552. }
  11553. /*
  11554. * ulimit builtin
  11555. *
  11556. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11557. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11558. * ash by J.T. Conklin.
  11559. *
  11560. * Public domain.
  11561. */
  11562. struct limits {
  11563. uint8_t cmd; /* RLIMIT_xxx fit into it */
  11564. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  11565. char option;
  11566. };
  11567. static const struct limits limits_tbl[] = {
  11568. #ifdef RLIMIT_CPU
  11569. { RLIMIT_CPU, 0, 't' },
  11570. #endif
  11571. #ifdef RLIMIT_FSIZE
  11572. { RLIMIT_FSIZE, 9, 'f' },
  11573. #endif
  11574. #ifdef RLIMIT_DATA
  11575. { RLIMIT_DATA, 10, 'd' },
  11576. #endif
  11577. #ifdef RLIMIT_STACK
  11578. { RLIMIT_STACK, 10, 's' },
  11579. #endif
  11580. #ifdef RLIMIT_CORE
  11581. { RLIMIT_CORE, 9, 'c' },
  11582. #endif
  11583. #ifdef RLIMIT_RSS
  11584. { RLIMIT_RSS, 10, 'm' },
  11585. #endif
  11586. #ifdef RLIMIT_MEMLOCK
  11587. { RLIMIT_MEMLOCK, 10, 'l' },
  11588. #endif
  11589. #ifdef RLIMIT_NPROC
  11590. { RLIMIT_NPROC, 0, 'p' },
  11591. #endif
  11592. #ifdef RLIMIT_NOFILE
  11593. { RLIMIT_NOFILE, 0, 'n' },
  11594. #endif
  11595. #ifdef RLIMIT_AS
  11596. { RLIMIT_AS, 10, 'v' },
  11597. #endif
  11598. #ifdef RLIMIT_LOCKS
  11599. { RLIMIT_LOCKS, 0, 'w' },
  11600. #endif
  11601. };
  11602. static const char limits_name[] =
  11603. #ifdef RLIMIT_CPU
  11604. "time(seconds)" "\0"
  11605. #endif
  11606. #ifdef RLIMIT_FSIZE
  11607. "file(blocks)" "\0"
  11608. #endif
  11609. #ifdef RLIMIT_DATA
  11610. "data(kb)" "\0"
  11611. #endif
  11612. #ifdef RLIMIT_STACK
  11613. "stack(kb)" "\0"
  11614. #endif
  11615. #ifdef RLIMIT_CORE
  11616. "coredump(blocks)" "\0"
  11617. #endif
  11618. #ifdef RLIMIT_RSS
  11619. "memory(kb)" "\0"
  11620. #endif
  11621. #ifdef RLIMIT_MEMLOCK
  11622. "locked memory(kb)" "\0"
  11623. #endif
  11624. #ifdef RLIMIT_NPROC
  11625. "process" "\0"
  11626. #endif
  11627. #ifdef RLIMIT_NOFILE
  11628. "nofiles" "\0"
  11629. #endif
  11630. #ifdef RLIMIT_AS
  11631. "vmemory(kb)" "\0"
  11632. #endif
  11633. #ifdef RLIMIT_LOCKS
  11634. "locks" "\0"
  11635. #endif
  11636. ;
  11637. enum limtype { SOFT = 0x1, HARD = 0x2 };
  11638. static void
  11639. printlim(enum limtype how, const struct rlimit *limit,
  11640. const struct limits *l)
  11641. {
  11642. rlim_t val;
  11643. val = limit->rlim_max;
  11644. if (how & SOFT)
  11645. val = limit->rlim_cur;
  11646. if (val == RLIM_INFINITY)
  11647. out1fmt("unlimited\n");
  11648. else {
  11649. val >>= l->factor_shift;
  11650. out1fmt("%lld\n", (long long) val);
  11651. }
  11652. }
  11653. static int FAST_FUNC
  11654. ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11655. {
  11656. rlim_t val;
  11657. enum limtype how = SOFT | HARD;
  11658. const struct limits *l;
  11659. int set, all = 0;
  11660. int optc, what;
  11661. struct rlimit limit;
  11662. what = 'f';
  11663. while ((optc = nextopt("HSa"
  11664. #ifdef RLIMIT_CPU
  11665. "t"
  11666. #endif
  11667. #ifdef RLIMIT_FSIZE
  11668. "f"
  11669. #endif
  11670. #ifdef RLIMIT_DATA
  11671. "d"
  11672. #endif
  11673. #ifdef RLIMIT_STACK
  11674. "s"
  11675. #endif
  11676. #ifdef RLIMIT_CORE
  11677. "c"
  11678. #endif
  11679. #ifdef RLIMIT_RSS
  11680. "m"
  11681. #endif
  11682. #ifdef RLIMIT_MEMLOCK
  11683. "l"
  11684. #endif
  11685. #ifdef RLIMIT_NPROC
  11686. "p"
  11687. #endif
  11688. #ifdef RLIMIT_NOFILE
  11689. "n"
  11690. #endif
  11691. #ifdef RLIMIT_AS
  11692. "v"
  11693. #endif
  11694. #ifdef RLIMIT_LOCKS
  11695. "w"
  11696. #endif
  11697. )) != '\0')
  11698. switch (optc) {
  11699. case 'H':
  11700. how = HARD;
  11701. break;
  11702. case 'S':
  11703. how = SOFT;
  11704. break;
  11705. case 'a':
  11706. all = 1;
  11707. break;
  11708. default:
  11709. what = optc;
  11710. }
  11711. for (l = limits_tbl; l->option != what; l++)
  11712. continue;
  11713. set = *argptr ? 1 : 0;
  11714. val = 0;
  11715. if (set) {
  11716. char *p = *argptr;
  11717. if (all || argptr[1])
  11718. ash_msg_and_raise_error("too many arguments");
  11719. if (strncmp(p, "unlimited\n", 9) == 0)
  11720. val = RLIM_INFINITY;
  11721. else {
  11722. if (sizeof(val) == sizeof(int))
  11723. val = bb_strtou(p, NULL, 10);
  11724. else if (sizeof(val) == sizeof(long))
  11725. val = bb_strtoul(p, NULL, 10);
  11726. else
  11727. val = bb_strtoull(p, NULL, 10);
  11728. if (errno)
  11729. ash_msg_and_raise_error("bad number");
  11730. val <<= l->factor_shift;
  11731. }
  11732. }
  11733. if (all) {
  11734. const char *lname = limits_name;
  11735. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  11736. getrlimit(l->cmd, &limit);
  11737. out1fmt("%-20s ", lname);
  11738. lname += strlen(lname) + 1;
  11739. printlim(how, &limit, l);
  11740. }
  11741. return 0;
  11742. }
  11743. getrlimit(l->cmd, &limit);
  11744. if (set) {
  11745. if (how & HARD)
  11746. limit.rlim_max = val;
  11747. if (how & SOFT)
  11748. limit.rlim_cur = val;
  11749. if (setrlimit(l->cmd, &limit) < 0)
  11750. ash_msg_and_raise_error("error setting limit (%m)");
  11751. } else {
  11752. printlim(how, &limit, l);
  11753. }
  11754. return 0;
  11755. }
  11756. /* ============ main() and helpers */
  11757. /*
  11758. * Called to exit the shell.
  11759. */
  11760. static void exitshell(void) NORETURN;
  11761. static void
  11762. exitshell(void)
  11763. {
  11764. struct jmploc loc;
  11765. char *p;
  11766. int status;
  11767. status = exitstatus;
  11768. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11769. if (setjmp(loc.loc)) {
  11770. if (exception_type == EXEXIT)
  11771. /* dash bug: it just does _exit(exitstatus) here
  11772. * but we have to do setjobctl(0) first!
  11773. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11774. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11775. status = exitstatus;
  11776. goto out;
  11777. }
  11778. exception_handler = &loc;
  11779. p = trap[0];
  11780. if (p) {
  11781. trap[0] = NULL;
  11782. evalstring(p, 0);
  11783. free(p);
  11784. }
  11785. flush_stdout_stderr();
  11786. out:
  11787. setjobctl(0);
  11788. _exit(status);
  11789. /* NOTREACHED */
  11790. }
  11791. static void
  11792. init(void)
  11793. {
  11794. /* from input.c: */
  11795. basepf.next_to_pgetc = basepf.buf = basebuf;
  11796. /* from trap.c: */
  11797. signal(SIGCHLD, SIG_DFL);
  11798. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  11799. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  11800. */
  11801. signal(SIGHUP, SIG_DFL);
  11802. /* from var.c: */
  11803. {
  11804. char **envp;
  11805. const char *p;
  11806. struct stat st1, st2;
  11807. initvar();
  11808. for (envp = environ; envp && *envp; envp++) {
  11809. if (strchr(*envp, '=')) {
  11810. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11811. }
  11812. }
  11813. setvar("PPID", utoa(getppid()), 0);
  11814. p = lookupvar("PWD");
  11815. if (p)
  11816. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11817. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  11818. p = '\0';
  11819. setpwd(p, 0);
  11820. }
  11821. }
  11822. /*
  11823. * Process the shell command line arguments.
  11824. */
  11825. static void
  11826. procargs(char **argv)
  11827. {
  11828. int i;
  11829. const char *xminusc;
  11830. char **xargv;
  11831. xargv = argv;
  11832. arg0 = xargv[0];
  11833. /* if (xargv[0]) - mmm, this is always true! */
  11834. xargv++;
  11835. for (i = 0; i < NOPTS; i++)
  11836. optlist[i] = 2;
  11837. argptr = xargv;
  11838. if (options(1)) {
  11839. /* it already printed err message */
  11840. raise_exception(EXERROR);
  11841. }
  11842. xargv = argptr;
  11843. xminusc = minusc;
  11844. if (*xargv == NULL) {
  11845. if (xminusc)
  11846. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11847. sflag = 1;
  11848. }
  11849. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11850. iflag = 1;
  11851. if (mflag == 2)
  11852. mflag = iflag;
  11853. for (i = 0; i < NOPTS; i++)
  11854. if (optlist[i] == 2)
  11855. optlist[i] = 0;
  11856. #if DEBUG == 2
  11857. debug = 1;
  11858. #endif
  11859. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11860. if (xminusc) {
  11861. minusc = *xargv++;
  11862. if (*xargv)
  11863. goto setarg0;
  11864. } else if (!sflag) {
  11865. setinputfile(*xargv, 0);
  11866. setarg0:
  11867. arg0 = *xargv++;
  11868. commandname = arg0;
  11869. }
  11870. shellparam.p = xargv;
  11871. #if ENABLE_ASH_GETOPTS
  11872. shellparam.optind = 1;
  11873. shellparam.optoff = -1;
  11874. #endif
  11875. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11876. while (*xargv) {
  11877. shellparam.nparam++;
  11878. xargv++;
  11879. }
  11880. optschanged();
  11881. }
  11882. /*
  11883. * Read /etc/profile or .profile.
  11884. */
  11885. static void
  11886. read_profile(const char *name)
  11887. {
  11888. int skip;
  11889. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11890. return;
  11891. skip = cmdloop(0);
  11892. popfile();
  11893. if (skip)
  11894. exitshell();
  11895. }
  11896. /*
  11897. * This routine is called when an error or an interrupt occurs in an
  11898. * interactive shell and control is returned to the main command loop.
  11899. */
  11900. static void
  11901. reset(void)
  11902. {
  11903. /* from eval.c: */
  11904. evalskip = 0;
  11905. loopnest = 0;
  11906. /* from input.c: */
  11907. g_parsefile->left_in_buffer = 0;
  11908. g_parsefile->left_in_line = 0; /* clear input buffer */
  11909. popallfiles();
  11910. /* from parser.c: */
  11911. tokpushback = 0;
  11912. checkkwd = 0;
  11913. /* from redir.c: */
  11914. clearredir(/*drop:*/ 0);
  11915. }
  11916. #if PROFILE
  11917. static short profile_buf[16384];
  11918. extern int etext();
  11919. #endif
  11920. /*
  11921. * Main routine. We initialize things, parse the arguments, execute
  11922. * profiles if we're a login shell, and then call cmdloop to execute
  11923. * commands. The setjmp call sets up the location to jump to when an
  11924. * exception occurs. When an exception occurs the variable "state"
  11925. * is used to figure out how far we had gotten.
  11926. */
  11927. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  11928. int ash_main(int argc UNUSED_PARAM, char **argv)
  11929. {
  11930. const char *shinit;
  11931. volatile smallint state;
  11932. struct jmploc jmploc;
  11933. struct stackmark smark;
  11934. /* Initialize global data */
  11935. INIT_G_misc();
  11936. INIT_G_memstack();
  11937. INIT_G_var();
  11938. #if ENABLE_ASH_ALIAS
  11939. INIT_G_alias();
  11940. #endif
  11941. INIT_G_cmdtable();
  11942. #if PROFILE
  11943. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  11944. #endif
  11945. #if ENABLE_FEATURE_EDITING
  11946. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  11947. #endif
  11948. state = 0;
  11949. if (setjmp(jmploc.loc)) {
  11950. smallint e;
  11951. smallint s;
  11952. reset();
  11953. e = exception_type;
  11954. if (e == EXERROR)
  11955. exitstatus = 2;
  11956. s = state;
  11957. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  11958. exitshell();
  11959. if (e == EXINT)
  11960. outcslow('\n', stderr);
  11961. popstackmark(&smark);
  11962. FORCE_INT_ON; /* enable interrupts */
  11963. if (s == 1)
  11964. goto state1;
  11965. if (s == 2)
  11966. goto state2;
  11967. if (s == 3)
  11968. goto state3;
  11969. goto state4;
  11970. }
  11971. exception_handler = &jmploc;
  11972. #if DEBUG
  11973. opentrace();
  11974. TRACE(("Shell args: "));
  11975. trace_puts_args(argv);
  11976. #endif
  11977. rootpid = getpid();
  11978. init();
  11979. setstackmark(&smark);
  11980. procargs(argv);
  11981. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  11982. if (iflag) {
  11983. const char *hp = lookupvar("HISTFILE");
  11984. if (hp == NULL) {
  11985. hp = lookupvar("HOME");
  11986. if (hp != NULL) {
  11987. char *defhp = concat_path_file(hp, ".ash_history");
  11988. setvar("HISTFILE", defhp, 0);
  11989. free(defhp);
  11990. }
  11991. }
  11992. }
  11993. #endif
  11994. if (/* argv[0] && */ argv[0][0] == '-')
  11995. isloginsh = 1;
  11996. if (isloginsh) {
  11997. state = 1;
  11998. read_profile("/etc/profile");
  11999. state1:
  12000. state = 2;
  12001. read_profile(".profile");
  12002. }
  12003. state2:
  12004. state = 3;
  12005. if (
  12006. #ifndef linux
  12007. getuid() == geteuid() && getgid() == getegid() &&
  12008. #endif
  12009. iflag
  12010. ) {
  12011. shinit = lookupvar("ENV");
  12012. if (shinit != NULL && *shinit != '\0') {
  12013. read_profile(shinit);
  12014. }
  12015. }
  12016. state3:
  12017. state = 4;
  12018. if (minusc) {
  12019. /* evalstring pushes parsefile stack.
  12020. * Ensure we don't falsely claim that 0 (stdin)
  12021. * is one of stacked source fds.
  12022. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12023. if (!sflag)
  12024. g_parsefile->fd = -1;
  12025. evalstring(minusc, 0);
  12026. }
  12027. if (sflag || minusc == NULL) {
  12028. #if defined MAX_HISTORY && MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12029. if (iflag) {
  12030. const char *hp = lookupvar("HISTFILE");
  12031. if (hp)
  12032. line_input_state->hist_file = hp;
  12033. }
  12034. #endif
  12035. state4: /* XXX ??? - why isn't this before the "if" statement */
  12036. cmdloop(1);
  12037. }
  12038. #if PROFILE
  12039. monitor(0);
  12040. #endif
  12041. #ifdef GPROF
  12042. {
  12043. extern void _mcleanup(void);
  12044. _mcleanup();
  12045. }
  12046. #endif
  12047. exitshell();
  12048. /* NOTREACHED */
  12049. }
  12050. /*-
  12051. * Copyright (c) 1989, 1991, 1993, 1994
  12052. * The Regents of the University of California. All rights reserved.
  12053. *
  12054. * This code is derived from software contributed to Berkeley by
  12055. * Kenneth Almquist.
  12056. *
  12057. * Redistribution and use in source and binary forms, with or without
  12058. * modification, are permitted provided that the following conditions
  12059. * are met:
  12060. * 1. Redistributions of source code must retain the above copyright
  12061. * notice, this list of conditions and the following disclaimer.
  12062. * 2. Redistributions in binary form must reproduce the above copyright
  12063. * notice, this list of conditions and the following disclaimer in the
  12064. * documentation and/or other materials provided with the distribution.
  12065. * 3. Neither the name of the University nor the names of its contributors
  12066. * may be used to endorse or promote products derived from this software
  12067. * without specific prior written permission.
  12068. *
  12069. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12070. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12071. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12072. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12073. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12074. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12075. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12076. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12077. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12078. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12079. * SUCH DAMAGE.
  12080. */