ash.c 286 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * Copyright (c) 1989, 1991, 1993, 1994
  6. * The Regents of the University of California. All rights reserved.
  7. *
  8. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  9. * was re-ported from NetBSD and debianized.
  10. *
  11. * This code is derived from software contributed to Berkeley by
  12. * Kenneth Almquist.
  13. *
  14. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  15. *
  16. * Original BSD copyright notice is retained at the end of this file.
  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 IFS_BROKEN
  35. #define JOBS ENABLE_ASH_JOB_CONTROL
  36. #if DEBUG
  37. # ifndef _GNU_SOURCE
  38. # define _GNU_SOURCE
  39. # endif
  40. #endif
  41. #include "busybox.h" /* for applet_names */
  42. //TODO: pull in some .h and find out do we have SINGLE_APPLET_MAIN?
  43. //#include "applet_tables.h" doesn't work
  44. #include <paths.h>
  45. #include <setjmp.h>
  46. #include <fnmatch.h>
  47. #include "math.h"
  48. #if defined SINGLE_APPLET_MAIN
  49. /* STANDALONE does not make sense, and won't compile */
  50. #undef CONFIG_FEATURE_SH_STANDALONE
  51. #undef ENABLE_FEATURE_SH_STANDALONE
  52. #undef IF_FEATURE_SH_STANDALONE
  53. #undef IF_NOT_FEATURE_SH_STANDALONE(...)
  54. #define ENABLE_FEATURE_SH_STANDALONE 0
  55. #define IF_FEATURE_SH_STANDALONE(...)
  56. #define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  57. #endif
  58. #ifndef PIPE_BUF
  59. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  60. #endif
  61. #if defined(__uClinux__)
  62. # error "Do not even bother, ash will not run on NOMMU machine"
  63. #endif
  64. /* ============ Hash table sizes. Configurable. */
  65. #define VTABSIZE 39
  66. #define ATABSIZE 39
  67. #define CMDTABLESIZE 31 /* should be prime */
  68. /* ============ Shell options */
  69. static const char *const optletters_optnames[] = {
  70. "e" "errexit",
  71. "f" "noglob",
  72. "I" "ignoreeof",
  73. "i" "interactive",
  74. "m" "monitor",
  75. "n" "noexec",
  76. "s" "stdin",
  77. "x" "xtrace",
  78. "v" "verbose",
  79. "C" "noclobber",
  80. "a" "allexport",
  81. "b" "notify",
  82. "u" "nounset",
  83. "\0" "vi"
  84. #if DEBUG
  85. ,"\0" "nolog"
  86. ,"\0" "debug"
  87. #endif
  88. };
  89. #define optletters(n) optletters_optnames[(n)][0]
  90. #define optnames(n) (&optletters_optnames[(n)][1])
  91. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  92. /* ============ Misc data */
  93. static const char homestr[] ALIGN1 = "HOME";
  94. static const char snlfmt[] ALIGN1 = "%s\n";
  95. static const char illnum[] ALIGN1 = "Illegal number: %s";
  96. /*
  97. * We enclose jmp_buf in a structure so that we can declare pointers to
  98. * jump locations. The global variable handler contains the location to
  99. * jump to when an exception occurs, and the global variable exception_type
  100. * contains a code identifying the exception. To implement nested
  101. * exception handlers, the user should save the value of handler on entry
  102. * to an inner scope, set handler to point to a jmploc structure for the
  103. * inner scope, and restore handler on exit from the scope.
  104. */
  105. struct jmploc {
  106. jmp_buf loc;
  107. };
  108. struct globals_misc {
  109. /* pid of main shell */
  110. int rootpid;
  111. /* shell level: 0 for the main shell, 1 for its children, and so on */
  112. int shlvl;
  113. #define rootshell (!shlvl)
  114. char *minusc; /* argument to -c option */
  115. char *curdir; // = nullstr; /* current working directory */
  116. char *physdir; // = nullstr; /* physical working directory */
  117. char *arg0; /* value of $0 */
  118. struct jmploc *exception_handler;
  119. // disabled by vda: cannot understand how it was supposed to work -
  120. // cannot fix bugs. That's why you have to explain your non-trivial designs!
  121. // /* do we generate EXSIG events */
  122. // int exsig; /* counter */
  123. volatile int suppressint; /* counter */
  124. // TODO: rename
  125. // pendingsig -> pending_sig
  126. // intpending -> pending_int
  127. volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
  128. /* last pending signal */
  129. volatile /*sig_atomic_t*/ smallint pendingsig;
  130. smallint exception_type; /* kind of exception (0..5) */
  131. /* exceptions */
  132. #define EXINT 0 /* SIGINT received */
  133. #define EXERROR 1 /* a generic error */
  134. #define EXSHELLPROC 2 /* execute a shell procedure */
  135. #define EXEXEC 3 /* command execution failed */
  136. #define EXEXIT 4 /* exit the shell */
  137. #define EXSIG 5 /* trapped signal in wait(1) */
  138. smallint isloginsh;
  139. char nullstr[1]; /* zero length string */
  140. char optlist[NOPTS];
  141. #define eflag optlist[0]
  142. #define fflag optlist[1]
  143. #define Iflag optlist[2]
  144. #define iflag optlist[3]
  145. #define mflag optlist[4]
  146. #define nflag optlist[5]
  147. #define sflag optlist[6]
  148. #define xflag optlist[7]
  149. #define vflag optlist[8]
  150. #define Cflag optlist[9]
  151. #define aflag optlist[10]
  152. #define bflag optlist[11]
  153. #define uflag optlist[12]
  154. #define viflag optlist[13]
  155. #if DEBUG
  156. #define nolog optlist[14]
  157. #define debug optlist[15]
  158. #endif
  159. /* trap handler commands */
  160. /*
  161. * Sigmode records the current value of the signal handlers for the various
  162. * modes. A value of zero means that the current handler is not known.
  163. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  164. */
  165. char sigmode[NSIG - 1];
  166. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  167. #define S_CATCH 2 /* signal is caught */
  168. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  169. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  170. /* indicates specified signal received */
  171. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  172. char *trap[NSIG];
  173. /* Rarely referenced stuff */
  174. #if ENABLE_ASH_RANDOM_SUPPORT
  175. /* Random number generators */
  176. int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
  177. uint32_t random_LCG; /* LCG (fast but weak) */
  178. #endif
  179. pid_t backgndpid; /* pid of last background process */
  180. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  181. };
  182. extern struct globals_misc *const ash_ptr_to_globals_misc;
  183. #define G_misc (*ash_ptr_to_globals_misc)
  184. #define rootpid (G_misc.rootpid )
  185. #define shlvl (G_misc.shlvl )
  186. #define minusc (G_misc.minusc )
  187. #define curdir (G_misc.curdir )
  188. #define physdir (G_misc.physdir )
  189. #define arg0 (G_misc.arg0 )
  190. #define exception_handler (G_misc.exception_handler)
  191. #define exception_type (G_misc.exception_type )
  192. #define suppressint (G_misc.suppressint )
  193. #define intpending (G_misc.intpending )
  194. //#define exsig (G_misc.exsig )
  195. #define pendingsig (G_misc.pendingsig )
  196. #define isloginsh (G_misc.isloginsh )
  197. #define nullstr (G_misc.nullstr )
  198. #define optlist (G_misc.optlist )
  199. #define sigmode (G_misc.sigmode )
  200. #define gotsig (G_misc.gotsig )
  201. #define trap (G_misc.trap )
  202. #define random_galois_LFSR (G_misc.random_galois_LFSR)
  203. #define random_LCG (G_misc.random_LCG )
  204. #define backgndpid (G_misc.backgndpid )
  205. #define job_warning (G_misc.job_warning)
  206. #define INIT_G_misc() do { \
  207. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  208. barrier(); \
  209. curdir = nullstr; \
  210. physdir = nullstr; \
  211. } while (0)
  212. /* ============ DEBUG */
  213. #if DEBUG
  214. static void trace_printf(const char *fmt, ...);
  215. static void trace_vprintf(const char *fmt, va_list va);
  216. # define TRACE(param) trace_printf param
  217. # define TRACEV(param) trace_vprintf param
  218. # define close(fd) do { \
  219. int dfd = (fd); \
  220. if (close(dfd) < 0) \
  221. bb_error_msg("bug on %d: closing %d(0x%x)", \
  222. __LINE__, dfd, dfd); \
  223. } while (0)
  224. #else
  225. # define TRACE(param)
  226. # define TRACEV(param)
  227. #endif
  228. /* ============ Utility functions */
  229. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  230. /* C99 say: "char" declaration may be signed or unsigned by default */
  231. #define signed_char2int(sc) ((int)(signed char)(sc))
  232. static int isdigit_str9(const char *str)
  233. {
  234. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  235. while (--maxlen && isdigit(*str))
  236. str++;
  237. return (*str == '\0');
  238. }
  239. /* ============ Interrupts / exceptions */
  240. /*
  241. * These macros allow the user to suspend the handling of interrupt signals
  242. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  243. * much more efficient and portable. (But hacking the kernel is so much
  244. * more fun than worrying about efficiency and portability. :-))
  245. */
  246. #define INT_OFF do { \
  247. suppressint++; \
  248. xbarrier(); \
  249. } while (0)
  250. /*
  251. * Called to raise an exception. Since C doesn't include exceptions, we
  252. * just do a longjmp to the exception handler. The type of exception is
  253. * stored in the global variable "exception_type".
  254. */
  255. static void raise_exception(int) NORETURN;
  256. static void
  257. raise_exception(int e)
  258. {
  259. #if DEBUG
  260. if (exception_handler == NULL)
  261. abort();
  262. #endif
  263. INT_OFF;
  264. exception_type = e;
  265. longjmp(exception_handler->loc, 1);
  266. }
  267. #if DEBUG
  268. #define raise_exception(e) do { \
  269. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  270. raise_exception(e); \
  271. } while (0)
  272. #endif
  273. /*
  274. * Called from trap.c when a SIGINT is received. (If the user specifies
  275. * that SIGINT is to be trapped or ignored using the trap builtin, then
  276. * this routine is not called.) Suppressint is nonzero when interrupts
  277. * are held using the INT_OFF macro. (The test for iflag is just
  278. * defensive programming.)
  279. */
  280. static void raise_interrupt(void) NORETURN;
  281. static void
  282. raise_interrupt(void)
  283. {
  284. int ex_type;
  285. intpending = 0;
  286. /* Signal is not automatically unmasked after it is raised,
  287. * do it ourself - unmask all signals */
  288. sigprocmask_allsigs(SIG_UNBLOCK);
  289. /* pendingsig = 0; - now done in onsig() */
  290. ex_type = EXSIG;
  291. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  292. if (!(rootshell && iflag)) {
  293. /* Kill ourself with SIGINT */
  294. signal(SIGINT, SIG_DFL);
  295. raise(SIGINT);
  296. }
  297. ex_type = EXINT;
  298. }
  299. raise_exception(ex_type);
  300. /* NOTREACHED */
  301. }
  302. #if DEBUG
  303. #define raise_interrupt() do { \
  304. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  305. raise_interrupt(); \
  306. } while (0)
  307. #endif
  308. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  309. int_on(void)
  310. {
  311. xbarrier();
  312. if (--suppressint == 0 && intpending) {
  313. raise_interrupt();
  314. }
  315. }
  316. #define INT_ON int_on()
  317. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  318. force_int_on(void)
  319. {
  320. xbarrier();
  321. suppressint = 0;
  322. if (intpending)
  323. raise_interrupt();
  324. }
  325. #define FORCE_INT_ON force_int_on()
  326. #define SAVE_INT(v) ((v) = suppressint)
  327. #define RESTORE_INT(v) do { \
  328. xbarrier(); \
  329. suppressint = (v); \
  330. if (suppressint == 0 && intpending) \
  331. raise_interrupt(); \
  332. } while (0)
  333. /* ============ Stdout/stderr output */
  334. static void
  335. outstr(const char *p, FILE *file)
  336. {
  337. INT_OFF;
  338. fputs(p, file);
  339. INT_ON;
  340. }
  341. static void
  342. flush_stdout_stderr(void)
  343. {
  344. INT_OFF;
  345. fflush(stdout);
  346. fflush(stderr);
  347. INT_ON;
  348. }
  349. static void
  350. flush_stderr(void)
  351. {
  352. INT_OFF;
  353. fflush(stderr);
  354. INT_ON;
  355. }
  356. static void
  357. outcslow(int c, FILE *dest)
  358. {
  359. INT_OFF;
  360. putc(c, dest);
  361. fflush(dest);
  362. INT_ON;
  363. }
  364. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  365. static int
  366. out1fmt(const char *fmt, ...)
  367. {
  368. va_list ap;
  369. int r;
  370. INT_OFF;
  371. va_start(ap, fmt);
  372. r = vprintf(fmt, ap);
  373. va_end(ap);
  374. INT_ON;
  375. return r;
  376. }
  377. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  378. static int
  379. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  380. {
  381. va_list ap;
  382. int ret;
  383. va_start(ap, fmt);
  384. INT_OFF;
  385. ret = vsnprintf(outbuf, length, fmt, ap);
  386. va_end(ap);
  387. INT_ON;
  388. return ret;
  389. }
  390. static void
  391. out1str(const char *p)
  392. {
  393. outstr(p, stdout);
  394. }
  395. static void
  396. out2str(const char *p)
  397. {
  398. outstr(p, stderr);
  399. flush_stderr();
  400. }
  401. /* ============ Parser structures */
  402. /* control characters in argument strings */
  403. #define CTLESC '\201' /* escape next character */
  404. #define CTLVAR '\202' /* variable defn */
  405. #define CTLENDVAR '\203'
  406. #define CTLBACKQ '\204'
  407. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  408. /* CTLBACKQ | CTLQUOTE == '\205' */
  409. #define CTLARI '\206' /* arithmetic expression */
  410. #define CTLENDARI '\207'
  411. #define CTLQUOTEMARK '\210'
  412. /* variable substitution byte (follows CTLVAR) */
  413. #define VSTYPE 0x0f /* type of variable substitution */
  414. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  415. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  416. /* values of VSTYPE field */
  417. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  418. #define VSMINUS 0x2 /* ${var-text} */
  419. #define VSPLUS 0x3 /* ${var+text} */
  420. #define VSQUESTION 0x4 /* ${var?message} */
  421. #define VSASSIGN 0x5 /* ${var=text} */
  422. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  423. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  424. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  425. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  426. #define VSLENGTH 0xa /* ${#var} */
  427. #if ENABLE_ASH_BASH_COMPAT
  428. #define VSSUBSTR 0xc /* ${var:position:length} */
  429. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  430. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  431. #endif
  432. static const char dolatstr[] ALIGN1 = {
  433. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  434. };
  435. #define NCMD 0
  436. #define NPIPE 1
  437. #define NREDIR 2
  438. #define NBACKGND 3
  439. #define NSUBSHELL 4
  440. #define NAND 5
  441. #define NOR 6
  442. #define NSEMI 7
  443. #define NIF 8
  444. #define NWHILE 9
  445. #define NUNTIL 10
  446. #define NFOR 11
  447. #define NCASE 12
  448. #define NCLIST 13
  449. #define NDEFUN 14
  450. #define NARG 15
  451. #define NTO 16
  452. #if ENABLE_ASH_BASH_COMPAT
  453. #define NTO2 17
  454. #endif
  455. #define NCLOBBER 18
  456. #define NFROM 19
  457. #define NFROMTO 20
  458. #define NAPPEND 21
  459. #define NTOFD 22
  460. #define NFROMFD 23
  461. #define NHERE 24
  462. #define NXHERE 25
  463. #define NNOT 26
  464. #define N_NUMBER 27
  465. union node;
  466. struct ncmd {
  467. smallint type; /* Nxxxx */
  468. union node *assign;
  469. union node *args;
  470. union node *redirect;
  471. };
  472. struct npipe {
  473. smallint type;
  474. smallint pipe_backgnd;
  475. struct nodelist *cmdlist;
  476. };
  477. struct nredir {
  478. smallint type;
  479. union node *n;
  480. union node *redirect;
  481. };
  482. struct nbinary {
  483. smallint type;
  484. union node *ch1;
  485. union node *ch2;
  486. };
  487. struct nif {
  488. smallint type;
  489. union node *test;
  490. union node *ifpart;
  491. union node *elsepart;
  492. };
  493. struct nfor {
  494. smallint type;
  495. union node *args;
  496. union node *body;
  497. char *var;
  498. };
  499. struct ncase {
  500. smallint type;
  501. union node *expr;
  502. union node *cases;
  503. };
  504. struct nclist {
  505. smallint type;
  506. union node *next;
  507. union node *pattern;
  508. union node *body;
  509. };
  510. struct narg {
  511. smallint type;
  512. union node *next;
  513. char *text;
  514. struct nodelist *backquote;
  515. };
  516. /* nfile and ndup layout must match!
  517. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  518. * that it is actually NTO2 (>&file), and change its type.
  519. */
  520. struct nfile {
  521. smallint type;
  522. union node *next;
  523. int fd;
  524. int _unused_dupfd;
  525. union node *fname;
  526. char *expfname;
  527. };
  528. struct ndup {
  529. smallint type;
  530. union node *next;
  531. int fd;
  532. int dupfd;
  533. union node *vname;
  534. char *_unused_expfname;
  535. };
  536. struct nhere {
  537. smallint type;
  538. union node *next;
  539. int fd;
  540. union node *doc;
  541. };
  542. struct nnot {
  543. smallint type;
  544. union node *com;
  545. };
  546. union node {
  547. smallint type;
  548. struct ncmd ncmd;
  549. struct npipe npipe;
  550. struct nredir nredir;
  551. struct nbinary nbinary;
  552. struct nif nif;
  553. struct nfor nfor;
  554. struct ncase ncase;
  555. struct nclist nclist;
  556. struct narg narg;
  557. struct nfile nfile;
  558. struct ndup ndup;
  559. struct nhere nhere;
  560. struct nnot nnot;
  561. };
  562. struct nodelist {
  563. struct nodelist *next;
  564. union node *n;
  565. };
  566. struct funcnode {
  567. int count;
  568. union node n;
  569. };
  570. /*
  571. * Free a parse tree.
  572. */
  573. static void
  574. freefunc(struct funcnode *f)
  575. {
  576. if (f && --f->count < 0)
  577. free(f);
  578. }
  579. /* ============ Debugging output */
  580. #if DEBUG
  581. static FILE *tracefile;
  582. static void
  583. trace_printf(const char *fmt, ...)
  584. {
  585. va_list va;
  586. if (debug != 1)
  587. return;
  588. if (DEBUG_TIME)
  589. fprintf(tracefile, "%u ", (int) time(NULL));
  590. if (DEBUG_PID)
  591. fprintf(tracefile, "[%u] ", (int) getpid());
  592. if (DEBUG_SIG)
  593. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
  594. va_start(va, fmt);
  595. vfprintf(tracefile, fmt, va);
  596. va_end(va);
  597. }
  598. static void
  599. trace_vprintf(const char *fmt, va_list va)
  600. {
  601. if (debug != 1)
  602. return;
  603. if (DEBUG_TIME)
  604. fprintf(tracefile, "%u ", (int) time(NULL));
  605. if (DEBUG_PID)
  606. fprintf(tracefile, "[%u] ", (int) getpid());
  607. if (DEBUG_SIG)
  608. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pendingsig, intpending, suppressint);
  609. vfprintf(tracefile, fmt, va);
  610. }
  611. static void
  612. trace_puts(const char *s)
  613. {
  614. if (debug != 1)
  615. return;
  616. fputs(s, tracefile);
  617. }
  618. static void
  619. trace_puts_quoted(char *s)
  620. {
  621. char *p;
  622. char c;
  623. if (debug != 1)
  624. return;
  625. putc('"', tracefile);
  626. for (p = s; *p; p++) {
  627. switch (*p) {
  628. case '\n': c = 'n'; goto backslash;
  629. case '\t': c = 't'; goto backslash;
  630. case '\r': c = 'r'; goto backslash;
  631. case '"': c = '"'; goto backslash;
  632. case '\\': c = '\\'; goto backslash;
  633. case CTLESC: c = 'e'; goto backslash;
  634. case CTLVAR: c = 'v'; goto backslash;
  635. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  636. case CTLBACKQ: c = 'q'; goto backslash;
  637. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  638. backslash:
  639. putc('\\', tracefile);
  640. putc(c, tracefile);
  641. break;
  642. default:
  643. if (*p >= ' ' && *p <= '~')
  644. putc(*p, tracefile);
  645. else {
  646. putc('\\', tracefile);
  647. putc(*p >> 6 & 03, tracefile);
  648. putc(*p >> 3 & 07, tracefile);
  649. putc(*p & 07, tracefile);
  650. }
  651. break;
  652. }
  653. }
  654. putc('"', tracefile);
  655. }
  656. static void
  657. trace_puts_args(char **ap)
  658. {
  659. if (debug != 1)
  660. return;
  661. if (!*ap)
  662. return;
  663. while (1) {
  664. trace_puts_quoted(*ap);
  665. if (!*++ap) {
  666. putc('\n', tracefile);
  667. break;
  668. }
  669. putc(' ', tracefile);
  670. }
  671. }
  672. static void
  673. opentrace(void)
  674. {
  675. char s[100];
  676. #ifdef O_APPEND
  677. int flags;
  678. #endif
  679. if (debug != 1) {
  680. if (tracefile)
  681. fflush(tracefile);
  682. /* leave open because libedit might be using it */
  683. return;
  684. }
  685. strcpy(s, "./trace");
  686. if (tracefile) {
  687. if (!freopen(s, "a", tracefile)) {
  688. fprintf(stderr, "Can't re-open %s\n", s);
  689. debug = 0;
  690. return;
  691. }
  692. } else {
  693. tracefile = fopen(s, "a");
  694. if (tracefile == NULL) {
  695. fprintf(stderr, "Can't open %s\n", s);
  696. debug = 0;
  697. return;
  698. }
  699. }
  700. #ifdef O_APPEND
  701. flags = fcntl(fileno(tracefile), F_GETFL);
  702. if (flags >= 0)
  703. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  704. #endif
  705. setlinebuf(tracefile);
  706. fputs("\nTracing started.\n", tracefile);
  707. }
  708. static void
  709. indent(int amount, char *pfx, FILE *fp)
  710. {
  711. int i;
  712. for (i = 0; i < amount; i++) {
  713. if (pfx && i == amount - 1)
  714. fputs(pfx, fp);
  715. putc('\t', fp);
  716. }
  717. }
  718. /* little circular references here... */
  719. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  720. static void
  721. sharg(union node *arg, FILE *fp)
  722. {
  723. char *p;
  724. struct nodelist *bqlist;
  725. int subtype;
  726. if (arg->type != NARG) {
  727. out1fmt("<node type %d>\n", arg->type);
  728. abort();
  729. }
  730. bqlist = arg->narg.backquote;
  731. for (p = arg->narg.text; *p; p++) {
  732. switch (*p) {
  733. case CTLESC:
  734. putc(*++p, fp);
  735. break;
  736. case CTLVAR:
  737. putc('$', fp);
  738. putc('{', fp);
  739. subtype = *++p;
  740. if (subtype == VSLENGTH)
  741. putc('#', fp);
  742. while (*p != '=')
  743. putc(*p++, fp);
  744. if (subtype & VSNUL)
  745. putc(':', fp);
  746. switch (subtype & VSTYPE) {
  747. case VSNORMAL:
  748. putc('}', fp);
  749. break;
  750. case VSMINUS:
  751. putc('-', fp);
  752. break;
  753. case VSPLUS:
  754. putc('+', fp);
  755. break;
  756. case VSQUESTION:
  757. putc('?', fp);
  758. break;
  759. case VSASSIGN:
  760. putc('=', fp);
  761. break;
  762. case VSTRIMLEFT:
  763. putc('#', fp);
  764. break;
  765. case VSTRIMLEFTMAX:
  766. putc('#', fp);
  767. putc('#', fp);
  768. break;
  769. case VSTRIMRIGHT:
  770. putc('%', fp);
  771. break;
  772. case VSTRIMRIGHTMAX:
  773. putc('%', fp);
  774. putc('%', fp);
  775. break;
  776. case VSLENGTH:
  777. break;
  778. default:
  779. out1fmt("<subtype %d>", subtype);
  780. }
  781. break;
  782. case CTLENDVAR:
  783. putc('}', fp);
  784. break;
  785. case CTLBACKQ:
  786. case CTLBACKQ|CTLQUOTE:
  787. putc('$', fp);
  788. putc('(', fp);
  789. shtree(bqlist->n, -1, NULL, fp);
  790. putc(')', fp);
  791. break;
  792. default:
  793. putc(*p, fp);
  794. break;
  795. }
  796. }
  797. }
  798. static void
  799. shcmd(union node *cmd, FILE *fp)
  800. {
  801. union node *np;
  802. int first;
  803. const char *s;
  804. int dftfd;
  805. first = 1;
  806. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  807. if (!first)
  808. putc(' ', fp);
  809. sharg(np, fp);
  810. first = 0;
  811. }
  812. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  813. if (!first)
  814. putc(' ', fp);
  815. dftfd = 0;
  816. switch (np->nfile.type) {
  817. case NTO: s = ">>"+1; dftfd = 1; break;
  818. case NCLOBBER: s = ">|"; dftfd = 1; break;
  819. case NAPPEND: s = ">>"; dftfd = 1; break;
  820. #if ENABLE_ASH_BASH_COMPAT
  821. case NTO2:
  822. #endif
  823. case NTOFD: s = ">&"; dftfd = 1; break;
  824. case NFROM: s = "<"; break;
  825. case NFROMFD: s = "<&"; break;
  826. case NFROMTO: s = "<>"; break;
  827. default: s = "*error*"; break;
  828. }
  829. if (np->nfile.fd != dftfd)
  830. fprintf(fp, "%d", np->nfile.fd);
  831. fputs(s, fp);
  832. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  833. fprintf(fp, "%d", np->ndup.dupfd);
  834. } else {
  835. sharg(np->nfile.fname, fp);
  836. }
  837. first = 0;
  838. }
  839. }
  840. static void
  841. shtree(union node *n, int ind, char *pfx, FILE *fp)
  842. {
  843. struct nodelist *lp;
  844. const char *s;
  845. if (n == NULL)
  846. return;
  847. indent(ind, pfx, fp);
  848. switch (n->type) {
  849. case NSEMI:
  850. s = "; ";
  851. goto binop;
  852. case NAND:
  853. s = " && ";
  854. goto binop;
  855. case NOR:
  856. s = " || ";
  857. binop:
  858. shtree(n->nbinary.ch1, ind, NULL, fp);
  859. /* if (ind < 0) */
  860. fputs(s, fp);
  861. shtree(n->nbinary.ch2, ind, NULL, fp);
  862. break;
  863. case NCMD:
  864. shcmd(n, fp);
  865. if (ind >= 0)
  866. putc('\n', fp);
  867. break;
  868. case NPIPE:
  869. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  870. shcmd(lp->n, fp);
  871. if (lp->next)
  872. fputs(" | ", fp);
  873. }
  874. if (n->npipe.pipe_backgnd)
  875. fputs(" &", fp);
  876. if (ind >= 0)
  877. putc('\n', fp);
  878. break;
  879. default:
  880. fprintf(fp, "<node type %d>", n->type);
  881. if (ind >= 0)
  882. putc('\n', fp);
  883. break;
  884. }
  885. }
  886. static void
  887. showtree(union node *n)
  888. {
  889. trace_puts("showtree called\n");
  890. shtree(n, 1, NULL, stderr);
  891. }
  892. #endif /* DEBUG */
  893. /* ============ Parser data */
  894. /*
  895. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  896. */
  897. struct strlist {
  898. struct strlist *next;
  899. char *text;
  900. };
  901. struct alias;
  902. struct strpush {
  903. struct strpush *prev; /* preceding string on stack */
  904. char *prev_string;
  905. int prev_left_in_line;
  906. #if ENABLE_ASH_ALIAS
  907. struct alias *ap; /* if push was associated with an alias */
  908. #endif
  909. char *string; /* remember the string since it may change */
  910. };
  911. struct parsefile {
  912. struct parsefile *prev; /* preceding file on stack */
  913. int linno; /* current line */
  914. int fd; /* file descriptor (or -1 if string) */
  915. int left_in_line; /* number of chars left in this line */
  916. int left_in_buffer; /* number of chars left in this buffer past the line */
  917. char *next_to_pgetc; /* next char in buffer */
  918. char *buf; /* input buffer */
  919. struct strpush *strpush; /* for pushing strings at this level */
  920. struct strpush basestrpush; /* so pushing one is fast */
  921. };
  922. static struct parsefile basepf; /* top level input file */
  923. static struct parsefile *g_parsefile = &basepf; /* current input file */
  924. static int startlinno; /* line # where last token started */
  925. static char *commandname; /* currently executing command */
  926. static struct strlist *cmdenviron; /* environment for builtin command */
  927. static uint8_t exitstatus; /* exit status of last command */
  928. /* ============ Message printing */
  929. static void
  930. ash_vmsg(const char *msg, va_list ap)
  931. {
  932. fprintf(stderr, "%s: ", arg0);
  933. if (commandname) {
  934. if (strcmp(arg0, commandname))
  935. fprintf(stderr, "%s: ", commandname);
  936. if (!iflag || g_parsefile->fd)
  937. fprintf(stderr, "line %d: ", startlinno);
  938. }
  939. vfprintf(stderr, msg, ap);
  940. outcslow('\n', stderr);
  941. }
  942. /*
  943. * Exverror is called to raise the error exception. If the second argument
  944. * is not NULL then error prints an error message using printf style
  945. * formatting. It then raises the error exception.
  946. */
  947. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  948. static void
  949. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  950. {
  951. #if DEBUG
  952. if (msg) {
  953. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  954. TRACEV((msg, ap));
  955. TRACE(("\") pid=%d\n", getpid()));
  956. } else
  957. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  958. if (msg)
  959. #endif
  960. ash_vmsg(msg, ap);
  961. flush_stdout_stderr();
  962. raise_exception(cond);
  963. /* NOTREACHED */
  964. }
  965. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  966. static void
  967. ash_msg_and_raise_error(const char *msg, ...)
  968. {
  969. va_list ap;
  970. va_start(ap, msg);
  971. ash_vmsg_and_raise(EXERROR, msg, ap);
  972. /* NOTREACHED */
  973. va_end(ap);
  974. }
  975. static void raise_error_syntax(const char *) NORETURN;
  976. static void
  977. raise_error_syntax(const char *msg)
  978. {
  979. ash_msg_and_raise_error("syntax error: %s", msg);
  980. /* NOTREACHED */
  981. }
  982. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  983. static void
  984. ash_msg_and_raise(int cond, const char *msg, ...)
  985. {
  986. va_list ap;
  987. va_start(ap, msg);
  988. ash_vmsg_and_raise(cond, msg, ap);
  989. /* NOTREACHED */
  990. va_end(ap);
  991. }
  992. /*
  993. * error/warning routines for external builtins
  994. */
  995. static void
  996. ash_msg(const char *fmt, ...)
  997. {
  998. va_list ap;
  999. va_start(ap, fmt);
  1000. ash_vmsg(fmt, ap);
  1001. va_end(ap);
  1002. }
  1003. /*
  1004. * Return a string describing an error. The returned string may be a
  1005. * pointer to a static buffer that will be overwritten on the next call.
  1006. * Action describes the operation that got the error.
  1007. */
  1008. static const char *
  1009. errmsg(int e, const char *em)
  1010. {
  1011. if (e == ENOENT || e == ENOTDIR) {
  1012. return em;
  1013. }
  1014. return strerror(e);
  1015. }
  1016. /* ============ Memory allocation */
  1017. /*
  1018. * It appears that grabstackstr() will barf with such alignments
  1019. * because stalloc() will return a string allocated in a new stackblock.
  1020. */
  1021. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1022. enum {
  1023. /* Most machines require the value returned from malloc to be aligned
  1024. * in some way. The following macro will get this right
  1025. * on many machines. */
  1026. SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
  1027. /* Minimum size of a block */
  1028. MINSIZE = SHELL_ALIGN(504),
  1029. };
  1030. struct stack_block {
  1031. struct stack_block *prev;
  1032. char space[MINSIZE];
  1033. };
  1034. struct stackmark {
  1035. struct stack_block *stackp;
  1036. char *stacknxt;
  1037. size_t stacknleft;
  1038. struct stackmark *marknext;
  1039. };
  1040. struct globals_memstack {
  1041. struct stack_block *g_stackp; // = &stackbase;
  1042. struct stackmark *markp;
  1043. char *g_stacknxt; // = stackbase.space;
  1044. char *sstrend; // = stackbase.space + MINSIZE;
  1045. size_t g_stacknleft; // = MINSIZE;
  1046. int herefd; // = -1;
  1047. struct stack_block stackbase;
  1048. };
  1049. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1050. #define G_memstack (*ash_ptr_to_globals_memstack)
  1051. #define g_stackp (G_memstack.g_stackp )
  1052. #define markp (G_memstack.markp )
  1053. #define g_stacknxt (G_memstack.g_stacknxt )
  1054. #define sstrend (G_memstack.sstrend )
  1055. #define g_stacknleft (G_memstack.g_stacknleft)
  1056. #define herefd (G_memstack.herefd )
  1057. #define stackbase (G_memstack.stackbase )
  1058. #define INIT_G_memstack() do { \
  1059. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1060. barrier(); \
  1061. g_stackp = &stackbase; \
  1062. g_stacknxt = stackbase.space; \
  1063. g_stacknleft = MINSIZE; \
  1064. sstrend = stackbase.space + MINSIZE; \
  1065. herefd = -1; \
  1066. } while (0)
  1067. #define stackblock() ((void *)g_stacknxt)
  1068. #define stackblocksize() g_stacknleft
  1069. static void *
  1070. ckrealloc(void * p, size_t nbytes)
  1071. {
  1072. p = realloc(p, nbytes);
  1073. if (!p)
  1074. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1075. return p;
  1076. }
  1077. static void *
  1078. ckmalloc(size_t nbytes)
  1079. {
  1080. return ckrealloc(NULL, nbytes);
  1081. }
  1082. static void *
  1083. ckzalloc(size_t nbytes)
  1084. {
  1085. return memset(ckmalloc(nbytes), 0, nbytes);
  1086. }
  1087. /*
  1088. * Make a copy of a string in safe storage.
  1089. */
  1090. static char *
  1091. ckstrdup(const char *s)
  1092. {
  1093. char *p = strdup(s);
  1094. if (!p)
  1095. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1096. return p;
  1097. }
  1098. /*
  1099. * Parse trees for commands are allocated in lifo order, so we use a stack
  1100. * to make this more efficient, and also to avoid all sorts of exception
  1101. * handling code to handle interrupts in the middle of a parse.
  1102. *
  1103. * The size 504 was chosen because the Ultrix malloc handles that size
  1104. * well.
  1105. */
  1106. static void *
  1107. stalloc(size_t nbytes)
  1108. {
  1109. char *p;
  1110. size_t aligned;
  1111. aligned = SHELL_ALIGN(nbytes);
  1112. if (aligned > g_stacknleft) {
  1113. size_t len;
  1114. size_t blocksize;
  1115. struct stack_block *sp;
  1116. blocksize = aligned;
  1117. if (blocksize < MINSIZE)
  1118. blocksize = MINSIZE;
  1119. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1120. if (len < blocksize)
  1121. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1122. INT_OFF;
  1123. sp = ckmalloc(len);
  1124. sp->prev = g_stackp;
  1125. g_stacknxt = sp->space;
  1126. g_stacknleft = blocksize;
  1127. sstrend = g_stacknxt + blocksize;
  1128. g_stackp = sp;
  1129. INT_ON;
  1130. }
  1131. p = g_stacknxt;
  1132. g_stacknxt += aligned;
  1133. g_stacknleft -= aligned;
  1134. return p;
  1135. }
  1136. static void *
  1137. stzalloc(size_t nbytes)
  1138. {
  1139. return memset(stalloc(nbytes), 0, nbytes);
  1140. }
  1141. static void
  1142. stunalloc(void *p)
  1143. {
  1144. #if DEBUG
  1145. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1146. write(STDERR_FILENO, "stunalloc\n", 10);
  1147. abort();
  1148. }
  1149. #endif
  1150. g_stacknleft += g_stacknxt - (char *)p;
  1151. g_stacknxt = p;
  1152. }
  1153. /*
  1154. * Like strdup but works with the ash stack.
  1155. */
  1156. static char *
  1157. ststrdup(const char *p)
  1158. {
  1159. size_t len = strlen(p) + 1;
  1160. return memcpy(stalloc(len), p, len);
  1161. }
  1162. static void
  1163. setstackmark(struct stackmark *mark)
  1164. {
  1165. mark->stackp = g_stackp;
  1166. mark->stacknxt = g_stacknxt;
  1167. mark->stacknleft = g_stacknleft;
  1168. mark->marknext = markp;
  1169. markp = mark;
  1170. }
  1171. static void
  1172. popstackmark(struct stackmark *mark)
  1173. {
  1174. struct stack_block *sp;
  1175. if (!mark->stackp)
  1176. return;
  1177. INT_OFF;
  1178. markp = mark->marknext;
  1179. while (g_stackp != mark->stackp) {
  1180. sp = g_stackp;
  1181. g_stackp = sp->prev;
  1182. free(sp);
  1183. }
  1184. g_stacknxt = mark->stacknxt;
  1185. g_stacknleft = mark->stacknleft;
  1186. sstrend = mark->stacknxt + mark->stacknleft;
  1187. INT_ON;
  1188. }
  1189. /*
  1190. * When the parser reads in a string, it wants to stick the string on the
  1191. * stack and only adjust the stack pointer when it knows how big the
  1192. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1193. * of space on top of the stack and stackblocklen returns the length of
  1194. * this block. Growstackblock will grow this space by at least one byte,
  1195. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1196. * part of the block that has been used.
  1197. */
  1198. static void
  1199. growstackblock(void)
  1200. {
  1201. size_t newlen;
  1202. newlen = g_stacknleft * 2;
  1203. if (newlen < g_stacknleft)
  1204. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1205. if (newlen < 128)
  1206. newlen += 128;
  1207. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1208. struct stack_block *oldstackp;
  1209. struct stackmark *xmark;
  1210. struct stack_block *sp;
  1211. struct stack_block *prevstackp;
  1212. size_t grosslen;
  1213. INT_OFF;
  1214. oldstackp = g_stackp;
  1215. sp = g_stackp;
  1216. prevstackp = sp->prev;
  1217. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1218. sp = ckrealloc(sp, grosslen);
  1219. sp->prev = prevstackp;
  1220. g_stackp = sp;
  1221. g_stacknxt = sp->space;
  1222. g_stacknleft = newlen;
  1223. sstrend = sp->space + newlen;
  1224. /*
  1225. * Stack marks pointing to the start of the old block
  1226. * must be relocated to point to the new block
  1227. */
  1228. xmark = markp;
  1229. while (xmark != NULL && xmark->stackp == oldstackp) {
  1230. xmark->stackp = g_stackp;
  1231. xmark->stacknxt = g_stacknxt;
  1232. xmark->stacknleft = g_stacknleft;
  1233. xmark = xmark->marknext;
  1234. }
  1235. INT_ON;
  1236. } else {
  1237. char *oldspace = g_stacknxt;
  1238. size_t oldlen = g_stacknleft;
  1239. char *p = stalloc(newlen);
  1240. /* free the space we just allocated */
  1241. g_stacknxt = memcpy(p, oldspace, oldlen);
  1242. g_stacknleft += newlen;
  1243. }
  1244. }
  1245. static void
  1246. grabstackblock(size_t len)
  1247. {
  1248. len = SHELL_ALIGN(len);
  1249. g_stacknxt += len;
  1250. g_stacknleft -= len;
  1251. }
  1252. /*
  1253. * The following routines are somewhat easier to use than the above.
  1254. * The user declares a variable of type STACKSTR, which may be declared
  1255. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1256. * the user uses the macro STPUTC to add characters to the string. In
  1257. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1258. * grown as necessary. When the user is done, she can just leave the
  1259. * string there and refer to it using stackblock(). Or she can allocate
  1260. * the space for it using grabstackstr(). If it is necessary to allow
  1261. * someone else to use the stack temporarily and then continue to grow
  1262. * the string, the user should use grabstack to allocate the space, and
  1263. * then call ungrabstr(p) to return to the previous mode of operation.
  1264. *
  1265. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1266. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1267. * is space for at least one character.
  1268. */
  1269. static void *
  1270. growstackstr(void)
  1271. {
  1272. size_t len = stackblocksize();
  1273. if (herefd >= 0 && len >= 1024) {
  1274. full_write(herefd, stackblock(), len);
  1275. return stackblock();
  1276. }
  1277. growstackblock();
  1278. return (char *)stackblock() + len;
  1279. }
  1280. /*
  1281. * Called from CHECKSTRSPACE.
  1282. */
  1283. static char *
  1284. makestrspace(size_t newlen, char *p)
  1285. {
  1286. size_t len = p - g_stacknxt;
  1287. size_t size = stackblocksize();
  1288. for (;;) {
  1289. size_t nleft;
  1290. size = stackblocksize();
  1291. nleft = size - len;
  1292. if (nleft >= newlen)
  1293. break;
  1294. growstackblock();
  1295. }
  1296. return (char *)stackblock() + len;
  1297. }
  1298. static char *
  1299. stack_nputstr(const char *s, size_t n, char *p)
  1300. {
  1301. p = makestrspace(n, p);
  1302. p = (char *)memcpy(p, s, n) + n;
  1303. return p;
  1304. }
  1305. static char *
  1306. stack_putstr(const char *s, char *p)
  1307. {
  1308. return stack_nputstr(s, strlen(s), p);
  1309. }
  1310. static char *
  1311. _STPUTC(int c, char *p)
  1312. {
  1313. if (p == sstrend)
  1314. p = growstackstr();
  1315. *p++ = c;
  1316. return p;
  1317. }
  1318. #define STARTSTACKSTR(p) ((p) = stackblock())
  1319. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1320. #define CHECKSTRSPACE(n, p) do { \
  1321. char *q = (p); \
  1322. size_t l = (n); \
  1323. size_t m = sstrend - q; \
  1324. if (l > m) \
  1325. (p) = makestrspace(l, q); \
  1326. } while (0)
  1327. #define USTPUTC(c, p) (*(p)++ = (c))
  1328. #define STACKSTRNUL(p) do { \
  1329. if ((p) == sstrend) \
  1330. (p) = growstackstr(); \
  1331. *(p) = '\0'; \
  1332. } while (0)
  1333. #define STUNPUTC(p) (--(p))
  1334. #define STTOPC(p) ((p)[-1])
  1335. #define STADJUST(amount, p) ((p) += (amount))
  1336. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1337. #define ungrabstackstr(s, p) stunalloc(s)
  1338. #define stackstrend() ((void *)sstrend)
  1339. /* ============ String helpers */
  1340. /*
  1341. * prefix -- see if pfx is a prefix of string.
  1342. */
  1343. static char *
  1344. prefix(const char *string, const char *pfx)
  1345. {
  1346. while (*pfx) {
  1347. if (*pfx++ != *string++)
  1348. return NULL;
  1349. }
  1350. return (char *) string;
  1351. }
  1352. /*
  1353. * Check for a valid number. This should be elsewhere.
  1354. */
  1355. static int
  1356. is_number(const char *p)
  1357. {
  1358. do {
  1359. if (!isdigit(*p))
  1360. return 0;
  1361. } while (*++p != '\0');
  1362. return 1;
  1363. }
  1364. /*
  1365. * Convert a string of digits to an integer, printing an error message on
  1366. * failure.
  1367. */
  1368. static int
  1369. number(const char *s)
  1370. {
  1371. if (!is_number(s))
  1372. ash_msg_and_raise_error(illnum, s);
  1373. return atoi(s);
  1374. }
  1375. /*
  1376. * Produce a possibly single quoted string suitable as input to the shell.
  1377. * The return string is allocated on the stack.
  1378. */
  1379. static char *
  1380. single_quote(const char *s)
  1381. {
  1382. char *p;
  1383. STARTSTACKSTR(p);
  1384. do {
  1385. char *q;
  1386. size_t len;
  1387. len = strchrnul(s, '\'') - s;
  1388. q = p = makestrspace(len + 3, p);
  1389. *q++ = '\'';
  1390. q = (char *)memcpy(q, s, len) + len;
  1391. *q++ = '\'';
  1392. s += len;
  1393. STADJUST(q - p, p);
  1394. len = strspn(s, "'");
  1395. if (!len)
  1396. break;
  1397. q = p = makestrspace(len + 3, p);
  1398. *q++ = '"';
  1399. q = (char *)memcpy(q, s, len) + len;
  1400. *q++ = '"';
  1401. s += len;
  1402. STADJUST(q - p, p);
  1403. } while (*s);
  1404. USTPUTC(0, p);
  1405. return stackblock();
  1406. }
  1407. /* ============ nextopt */
  1408. static char **argptr; /* argument list for builtin commands */
  1409. static char *optionarg; /* set by nextopt (like getopt) */
  1410. static char *optptr; /* used by nextopt */
  1411. /*
  1412. * XXX - should get rid of. Have all builtins use getopt(3).
  1413. * The library getopt must have the BSD extension static variable
  1414. * "optreset", otherwise it can't be used within the shell safely.
  1415. *
  1416. * Standard option processing (a la getopt) for builtin routines.
  1417. * The only argument that is passed to nextopt is the option string;
  1418. * the other arguments are unnecessary. It returns the character,
  1419. * or '\0' on end of input.
  1420. */
  1421. static int
  1422. nextopt(const char *optstring)
  1423. {
  1424. char *p;
  1425. const char *q;
  1426. char c;
  1427. p = optptr;
  1428. if (p == NULL || *p == '\0') {
  1429. /* We ate entire "-param", take next one */
  1430. p = *argptr;
  1431. if (p == NULL)
  1432. return '\0';
  1433. if (*p != '-')
  1434. return '\0';
  1435. if (*++p == '\0') /* just "-" ? */
  1436. return '\0';
  1437. argptr++;
  1438. if (LONE_DASH(p)) /* "--" ? */
  1439. return '\0';
  1440. /* p => next "-param" */
  1441. }
  1442. /* p => some option char in the middle of a "-param" */
  1443. c = *p++;
  1444. for (q = optstring; *q != c;) {
  1445. if (*q == '\0')
  1446. ash_msg_and_raise_error("illegal option -%c", c);
  1447. if (*++q == ':')
  1448. q++;
  1449. }
  1450. if (*++q == ':') {
  1451. if (*p == '\0') {
  1452. p = *argptr++;
  1453. if (p == NULL)
  1454. ash_msg_and_raise_error("no arg for -%c option", c);
  1455. }
  1456. optionarg = p;
  1457. p = NULL;
  1458. }
  1459. optptr = p;
  1460. return c;
  1461. }
  1462. /* ============ Shell variables */
  1463. /*
  1464. * The parsefile structure pointed to by the global variable parsefile
  1465. * contains information about the current file being read.
  1466. */
  1467. struct shparam {
  1468. int nparam; /* # of positional parameters (without $0) */
  1469. #if ENABLE_ASH_GETOPTS
  1470. int optind; /* next parameter to be processed by getopts */
  1471. int optoff; /* used by getopts */
  1472. #endif
  1473. unsigned char malloced; /* if parameter list dynamically allocated */
  1474. char **p; /* parameter list */
  1475. };
  1476. /*
  1477. * Free the list of positional parameters.
  1478. */
  1479. static void
  1480. freeparam(volatile struct shparam *param)
  1481. {
  1482. if (param->malloced) {
  1483. char **ap, **ap1;
  1484. ap = ap1 = param->p;
  1485. while (*ap)
  1486. free(*ap++);
  1487. free(ap1);
  1488. }
  1489. }
  1490. #if ENABLE_ASH_GETOPTS
  1491. static void FAST_FUNC getoptsreset(const char *value);
  1492. #endif
  1493. struct var {
  1494. struct var *next; /* next entry in hash list */
  1495. int flags; /* flags are defined above */
  1496. const char *text; /* name=value */
  1497. void (*func)(const char *) FAST_FUNC; /* function to be called when */
  1498. /* the variable gets set/unset */
  1499. };
  1500. struct localvar {
  1501. struct localvar *next; /* next local variable in list */
  1502. struct var *vp; /* the variable that was made local */
  1503. int flags; /* saved flags */
  1504. const char *text; /* saved text */
  1505. };
  1506. /* flags */
  1507. #define VEXPORT 0x01 /* variable is exported */
  1508. #define VREADONLY 0x02 /* variable cannot be modified */
  1509. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1510. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1511. #define VSTACK 0x10 /* text is allocated on the stack */
  1512. #define VUNSET 0x20 /* the variable is not set */
  1513. #define VNOFUNC 0x40 /* don't call the callback function */
  1514. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1515. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1516. #if ENABLE_ASH_RANDOM_SUPPORT
  1517. # define VDYNAMIC 0x200 /* dynamic variable */
  1518. #else
  1519. # define VDYNAMIC 0
  1520. #endif
  1521. #ifdef IFS_BROKEN
  1522. static const char defifsvar[] ALIGN1 = "IFS= \t\n";
  1523. #define defifs (defifsvar + 4)
  1524. #else
  1525. static const char defifs[] ALIGN1 = " \t\n";
  1526. #endif
  1527. /* Need to be before varinit_data[] */
  1528. #if ENABLE_LOCALE_SUPPORT
  1529. static void FAST_FUNC
  1530. change_lc_all(const char *value)
  1531. {
  1532. if (value && *value != '\0')
  1533. setlocale(LC_ALL, value);
  1534. }
  1535. static void FAST_FUNC
  1536. change_lc_ctype(const char *value)
  1537. {
  1538. if (value && *value != '\0')
  1539. setlocale(LC_CTYPE, value);
  1540. }
  1541. #endif
  1542. #if ENABLE_ASH_MAIL
  1543. static void chkmail(void);
  1544. static void changemail(const char *) FAST_FUNC;
  1545. #endif
  1546. static void changepath(const char *) FAST_FUNC;
  1547. #if ENABLE_ASH_RANDOM_SUPPORT
  1548. static void change_random(const char *) FAST_FUNC;
  1549. #endif
  1550. static const struct {
  1551. int flags;
  1552. const char *text;
  1553. void (*func)(const char *) FAST_FUNC;
  1554. } varinit_data[] = {
  1555. #ifdef IFS_BROKEN
  1556. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1557. #else
  1558. { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
  1559. #endif
  1560. #if ENABLE_ASH_MAIL
  1561. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
  1562. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1563. #endif
  1564. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1565. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1566. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1567. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1568. #if ENABLE_ASH_GETOPTS
  1569. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1570. #endif
  1571. #if ENABLE_ASH_RANDOM_SUPPORT
  1572. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1573. #endif
  1574. #if ENABLE_LOCALE_SUPPORT
  1575. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
  1576. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1577. #endif
  1578. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1579. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
  1580. #endif
  1581. };
  1582. struct redirtab;
  1583. struct globals_var {
  1584. struct shparam shellparam; /* $@ current positional parameters */
  1585. struct redirtab *redirlist;
  1586. int g_nullredirs;
  1587. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1588. struct var *vartab[VTABSIZE];
  1589. struct var varinit[ARRAY_SIZE(varinit_data)];
  1590. };
  1591. extern struct globals_var *const ash_ptr_to_globals_var;
  1592. #define G_var (*ash_ptr_to_globals_var)
  1593. #define shellparam (G_var.shellparam )
  1594. //#define redirlist (G_var.redirlist )
  1595. #define g_nullredirs (G_var.g_nullredirs )
  1596. #define preverrout_fd (G_var.preverrout_fd)
  1597. #define vartab (G_var.vartab )
  1598. #define varinit (G_var.varinit )
  1599. #define INIT_G_var() do { \
  1600. unsigned i; \
  1601. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1602. barrier(); \
  1603. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1604. varinit[i].flags = varinit_data[i].flags; \
  1605. varinit[i].text = varinit_data[i].text; \
  1606. varinit[i].func = varinit_data[i].func; \
  1607. } \
  1608. } while (0)
  1609. #define vifs varinit[0]
  1610. #if ENABLE_ASH_MAIL
  1611. # define vmail (&vifs)[1]
  1612. # define vmpath (&vmail)[1]
  1613. # define vpath (&vmpath)[1]
  1614. #else
  1615. # define vpath (&vifs)[1]
  1616. #endif
  1617. #define vps1 (&vpath)[1]
  1618. #define vps2 (&vps1)[1]
  1619. #define vps4 (&vps2)[1]
  1620. #if ENABLE_ASH_GETOPTS
  1621. # define voptind (&vps4)[1]
  1622. # if ENABLE_ASH_RANDOM_SUPPORT
  1623. # define vrandom (&voptind)[1]
  1624. # endif
  1625. #else
  1626. # if ENABLE_ASH_RANDOM_SUPPORT
  1627. # define vrandom (&vps4)[1]
  1628. # endif
  1629. #endif
  1630. /*
  1631. * The following macros access the values of the above variables.
  1632. * They have to skip over the name. They return the null string
  1633. * for unset variables.
  1634. */
  1635. #define ifsval() (vifs.text + 4)
  1636. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1637. #if ENABLE_ASH_MAIL
  1638. # define mailval() (vmail.text + 5)
  1639. # define mpathval() (vmpath.text + 9)
  1640. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1641. #endif
  1642. #define pathval() (vpath.text + 5)
  1643. #define ps1val() (vps1.text + 4)
  1644. #define ps2val() (vps2.text + 4)
  1645. #define ps4val() (vps4.text + 4)
  1646. #if ENABLE_ASH_GETOPTS
  1647. # define optindval() (voptind.text + 7)
  1648. #endif
  1649. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1650. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1651. #if ENABLE_ASH_GETOPTS
  1652. static void FAST_FUNC
  1653. getoptsreset(const char *value)
  1654. {
  1655. shellparam.optind = number(value);
  1656. shellparam.optoff = -1;
  1657. }
  1658. #endif
  1659. /*
  1660. * Return of a legal variable name (a letter or underscore followed by zero or
  1661. * more letters, underscores, and digits).
  1662. */
  1663. static char *
  1664. endofname(const char *name)
  1665. {
  1666. char *p;
  1667. p = (char *) name;
  1668. if (!is_name(*p))
  1669. return p;
  1670. while (*++p) {
  1671. if (!is_in_name(*p))
  1672. break;
  1673. }
  1674. return p;
  1675. }
  1676. /*
  1677. * Compares two strings up to the first = or '\0'. The first
  1678. * string must be terminated by '='; the second may be terminated by
  1679. * either '=' or '\0'.
  1680. */
  1681. static int
  1682. varcmp(const char *p, const char *q)
  1683. {
  1684. int c, d;
  1685. while ((c = *p) == (d = *q)) {
  1686. if (!c || c == '=')
  1687. goto out;
  1688. p++;
  1689. q++;
  1690. }
  1691. if (c == '=')
  1692. c = '\0';
  1693. if (d == '=')
  1694. d = '\0';
  1695. out:
  1696. return c - d;
  1697. }
  1698. static int
  1699. varequal(const char *a, const char *b)
  1700. {
  1701. return !varcmp(a, b);
  1702. }
  1703. /*
  1704. * Find the appropriate entry in the hash table from the name.
  1705. */
  1706. static struct var **
  1707. hashvar(const char *p)
  1708. {
  1709. unsigned hashval;
  1710. hashval = ((unsigned char) *p) << 4;
  1711. while (*p && *p != '=')
  1712. hashval += (unsigned char) *p++;
  1713. return &vartab[hashval % VTABSIZE];
  1714. }
  1715. static int
  1716. vpcmp(const void *a, const void *b)
  1717. {
  1718. return varcmp(*(const char **)a, *(const char **)b);
  1719. }
  1720. /*
  1721. * This routine initializes the builtin variables.
  1722. */
  1723. static void
  1724. initvar(void)
  1725. {
  1726. struct var *vp;
  1727. struct var *end;
  1728. struct var **vpp;
  1729. /*
  1730. * PS1 depends on uid
  1731. */
  1732. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1733. vps1.text = "PS1=\\w \\$ ";
  1734. #else
  1735. if (!geteuid())
  1736. vps1.text = "PS1=# ";
  1737. #endif
  1738. vp = varinit;
  1739. end = vp + ARRAY_SIZE(varinit);
  1740. do {
  1741. vpp = hashvar(vp->text);
  1742. vp->next = *vpp;
  1743. *vpp = vp;
  1744. } while (++vp < end);
  1745. }
  1746. static struct var **
  1747. findvar(struct var **vpp, const char *name)
  1748. {
  1749. for (; *vpp; vpp = &(*vpp)->next) {
  1750. if (varequal((*vpp)->text, name)) {
  1751. break;
  1752. }
  1753. }
  1754. return vpp;
  1755. }
  1756. /*
  1757. * Find the value of a variable. Returns NULL if not set.
  1758. */
  1759. static const char *
  1760. lookupvar(const char *name)
  1761. {
  1762. struct var *v;
  1763. v = *findvar(hashvar(name), name);
  1764. if (v) {
  1765. #if ENABLE_ASH_RANDOM_SUPPORT
  1766. /*
  1767. * Dynamic variables are implemented roughly the same way they are
  1768. * in bash. Namely, they're "special" so long as they aren't unset.
  1769. * As soon as they're unset, they're no longer dynamic, and dynamic
  1770. * lookup will no longer happen at that point. -- PFM.
  1771. */
  1772. if ((v->flags & VDYNAMIC))
  1773. (*v->func)(NULL);
  1774. #endif
  1775. if (!(v->flags & VUNSET))
  1776. return strchrnul(v->text, '=') + 1;
  1777. }
  1778. return NULL;
  1779. }
  1780. /*
  1781. * Search the environment of a builtin command.
  1782. */
  1783. static const char *
  1784. bltinlookup(const char *name)
  1785. {
  1786. struct strlist *sp;
  1787. for (sp = cmdenviron; sp; sp = sp->next) {
  1788. if (varequal(sp->text, name))
  1789. return strchrnul(sp->text, '=') + 1;
  1790. }
  1791. return lookupvar(name);
  1792. }
  1793. /*
  1794. * Same as setvar except that the variable and value are passed in
  1795. * the first argument as name=value. Since the first argument will
  1796. * be actually stored in the table, it should not be a string that
  1797. * will go away.
  1798. * Called with interrupts off.
  1799. */
  1800. static void
  1801. setvareq(char *s, int flags)
  1802. {
  1803. struct var *vp, **vpp;
  1804. vpp = hashvar(s);
  1805. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1806. vp = *findvar(vpp, s);
  1807. if (vp) {
  1808. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1809. const char *n;
  1810. if (flags & VNOSAVE)
  1811. free(s);
  1812. n = vp->text;
  1813. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1814. }
  1815. if (flags & VNOSET)
  1816. return;
  1817. if (vp->func && (flags & VNOFUNC) == 0)
  1818. (*vp->func)(strchrnul(s, '=') + 1);
  1819. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1820. free((char*)vp->text);
  1821. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1822. } else {
  1823. if (flags & VNOSET)
  1824. return;
  1825. /* not found */
  1826. vp = ckzalloc(sizeof(*vp));
  1827. vp->next = *vpp;
  1828. /*vp->func = NULL; - ckzalloc did it */
  1829. *vpp = vp;
  1830. }
  1831. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1832. s = ckstrdup(s);
  1833. vp->text = s;
  1834. vp->flags = flags;
  1835. }
  1836. /*
  1837. * Set the value of a variable. The flags argument is ored with the
  1838. * flags of the variable. If val is NULL, the variable is unset.
  1839. */
  1840. static void
  1841. setvar(const char *name, const char *val, int flags)
  1842. {
  1843. char *p, *q;
  1844. size_t namelen;
  1845. char *nameeq;
  1846. size_t vallen;
  1847. q = endofname(name);
  1848. p = strchrnul(q, '=');
  1849. namelen = p - name;
  1850. if (!namelen || p != q)
  1851. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1852. vallen = 0;
  1853. if (val == NULL) {
  1854. flags |= VUNSET;
  1855. } else {
  1856. vallen = strlen(val);
  1857. }
  1858. INT_OFF;
  1859. nameeq = ckmalloc(namelen + vallen + 2);
  1860. p = (char *)memcpy(nameeq, name, namelen) + namelen;
  1861. if (val) {
  1862. *p++ = '=';
  1863. p = (char *)memcpy(p, val, vallen) + vallen;
  1864. }
  1865. *p = '\0';
  1866. setvareq(nameeq, flags | VNOSAVE);
  1867. INT_ON;
  1868. }
  1869. #if ENABLE_ASH_GETOPTS
  1870. /*
  1871. * Safe version of setvar, returns 1 on success 0 on failure.
  1872. */
  1873. static int
  1874. setvarsafe(const char *name, const char *val, int flags)
  1875. {
  1876. int err;
  1877. volatile int saveint;
  1878. struct jmploc *volatile savehandler = exception_handler;
  1879. struct jmploc jmploc;
  1880. SAVE_INT(saveint);
  1881. if (setjmp(jmploc.loc))
  1882. err = 1;
  1883. else {
  1884. exception_handler = &jmploc;
  1885. setvar(name, val, flags);
  1886. err = 0;
  1887. }
  1888. exception_handler = savehandler;
  1889. RESTORE_INT(saveint);
  1890. return err;
  1891. }
  1892. #endif
  1893. /*
  1894. * Unset the specified variable.
  1895. */
  1896. static int
  1897. unsetvar(const char *s)
  1898. {
  1899. struct var **vpp;
  1900. struct var *vp;
  1901. int retval;
  1902. vpp = findvar(hashvar(s), s);
  1903. vp = *vpp;
  1904. retval = 2;
  1905. if (vp) {
  1906. int flags = vp->flags;
  1907. retval = 1;
  1908. if (flags & VREADONLY)
  1909. goto out;
  1910. #if ENABLE_ASH_RANDOM_SUPPORT
  1911. vp->flags &= ~VDYNAMIC;
  1912. #endif
  1913. if (flags & VUNSET)
  1914. goto ok;
  1915. if ((flags & VSTRFIXED) == 0) {
  1916. INT_OFF;
  1917. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1918. free((char*)vp->text);
  1919. *vpp = vp->next;
  1920. free(vp);
  1921. INT_ON;
  1922. } else {
  1923. setvar(s, 0, 0);
  1924. vp->flags &= ~VEXPORT;
  1925. }
  1926. ok:
  1927. retval = 0;
  1928. }
  1929. out:
  1930. return retval;
  1931. }
  1932. /*
  1933. * Process a linked list of variable assignments.
  1934. */
  1935. static void
  1936. listsetvar(struct strlist *list_set_var, int flags)
  1937. {
  1938. struct strlist *lp = list_set_var;
  1939. if (!lp)
  1940. return;
  1941. INT_OFF;
  1942. do {
  1943. setvareq(lp->text, flags);
  1944. lp = lp->next;
  1945. } while (lp);
  1946. INT_ON;
  1947. }
  1948. /*
  1949. * Generate a list of variables satisfying the given conditions.
  1950. */
  1951. static char **
  1952. listvars(int on, int off, char ***end)
  1953. {
  1954. struct var **vpp;
  1955. struct var *vp;
  1956. char **ep;
  1957. int mask;
  1958. STARTSTACKSTR(ep);
  1959. vpp = vartab;
  1960. mask = on | off;
  1961. do {
  1962. for (vp = *vpp; vp; vp = vp->next) {
  1963. if ((vp->flags & mask) == on) {
  1964. if (ep == stackstrend())
  1965. ep = growstackstr();
  1966. *ep++ = (char *) vp->text;
  1967. }
  1968. }
  1969. } while (++vpp < vartab + VTABSIZE);
  1970. if (ep == stackstrend())
  1971. ep = growstackstr();
  1972. if (end)
  1973. *end = ep;
  1974. *ep++ = NULL;
  1975. return grabstackstr(ep);
  1976. }
  1977. /* ============ Path search helper
  1978. *
  1979. * The variable path (passed by reference) should be set to the start
  1980. * of the path before the first call; path_advance will update
  1981. * this value as it proceeds. Successive calls to path_advance will return
  1982. * the possible path expansions in sequence. If an option (indicated by
  1983. * a percent sign) appears in the path entry then the global variable
  1984. * pathopt will be set to point to it; otherwise pathopt will be set to
  1985. * NULL.
  1986. */
  1987. static const char *pathopt; /* set by path_advance */
  1988. static char *
  1989. path_advance(const char **path, const char *name)
  1990. {
  1991. const char *p;
  1992. char *q;
  1993. const char *start;
  1994. size_t len;
  1995. if (*path == NULL)
  1996. return NULL;
  1997. start = *path;
  1998. for (p = start; *p && *p != ':' && *p != '%'; p++)
  1999. continue;
  2000. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2001. while (stackblocksize() < len)
  2002. growstackblock();
  2003. q = stackblock();
  2004. if (p != start) {
  2005. memcpy(q, start, p - start);
  2006. q += p - start;
  2007. *q++ = '/';
  2008. }
  2009. strcpy(q, name);
  2010. pathopt = NULL;
  2011. if (*p == '%') {
  2012. pathopt = ++p;
  2013. while (*p && *p != ':')
  2014. p++;
  2015. }
  2016. if (*p == ':')
  2017. *path = p + 1;
  2018. else
  2019. *path = NULL;
  2020. return stalloc(len);
  2021. }
  2022. /* ============ Prompt */
  2023. static smallint doprompt; /* if set, prompt the user */
  2024. static smallint needprompt; /* true if interactive and at start of line */
  2025. #if ENABLE_FEATURE_EDITING
  2026. static line_input_t *line_input_state;
  2027. static const char *cmdedit_prompt;
  2028. static void
  2029. putprompt(const char *s)
  2030. {
  2031. if (ENABLE_ASH_EXPAND_PRMT) {
  2032. free((char*)cmdedit_prompt);
  2033. cmdedit_prompt = ckstrdup(s);
  2034. return;
  2035. }
  2036. cmdedit_prompt = s;
  2037. }
  2038. #else
  2039. static void
  2040. putprompt(const char *s)
  2041. {
  2042. out2str(s);
  2043. }
  2044. #endif
  2045. #if ENABLE_ASH_EXPAND_PRMT
  2046. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2047. static const char *expandstr(const char *ps);
  2048. #else
  2049. #define expandstr(s) s
  2050. #endif
  2051. static void
  2052. setprompt(int whichprompt)
  2053. {
  2054. const char *prompt;
  2055. #if ENABLE_ASH_EXPAND_PRMT
  2056. struct stackmark smark;
  2057. #endif
  2058. needprompt = 0;
  2059. switch (whichprompt) {
  2060. case 1:
  2061. prompt = ps1val();
  2062. break;
  2063. case 2:
  2064. prompt = ps2val();
  2065. break;
  2066. default: /* 0 */
  2067. prompt = nullstr;
  2068. }
  2069. #if ENABLE_ASH_EXPAND_PRMT
  2070. setstackmark(&smark);
  2071. stalloc(stackblocksize());
  2072. #endif
  2073. putprompt(expandstr(prompt));
  2074. #if ENABLE_ASH_EXPAND_PRMT
  2075. popstackmark(&smark);
  2076. #endif
  2077. }
  2078. /* ============ The cd and pwd commands */
  2079. #define CD_PHYSICAL 1
  2080. #define CD_PRINT 2
  2081. static int docd(const char *, int);
  2082. static int
  2083. cdopt(void)
  2084. {
  2085. int flags = 0;
  2086. int i, j;
  2087. j = 'L';
  2088. while ((i = nextopt("LP"))) {
  2089. if (i != j) {
  2090. flags ^= CD_PHYSICAL;
  2091. j = i;
  2092. }
  2093. }
  2094. return flags;
  2095. }
  2096. /*
  2097. * Update curdir (the name of the current directory) in response to a
  2098. * cd command.
  2099. */
  2100. static const char *
  2101. updatepwd(const char *dir)
  2102. {
  2103. char *new;
  2104. char *p;
  2105. char *cdcomppath;
  2106. const char *lim;
  2107. cdcomppath = ststrdup(dir);
  2108. STARTSTACKSTR(new);
  2109. if (*dir != '/') {
  2110. if (curdir == nullstr)
  2111. return 0;
  2112. new = stack_putstr(curdir, new);
  2113. }
  2114. new = makestrspace(strlen(dir) + 2, new);
  2115. lim = (char *)stackblock() + 1;
  2116. if (*dir != '/') {
  2117. if (new[-1] != '/')
  2118. USTPUTC('/', new);
  2119. if (new > lim && *lim == '/')
  2120. lim++;
  2121. } else {
  2122. USTPUTC('/', new);
  2123. cdcomppath++;
  2124. if (dir[1] == '/' && dir[2] != '/') {
  2125. USTPUTC('/', new);
  2126. cdcomppath++;
  2127. lim++;
  2128. }
  2129. }
  2130. p = strtok(cdcomppath, "/");
  2131. while (p) {
  2132. switch (*p) {
  2133. case '.':
  2134. if (p[1] == '.' && p[2] == '\0') {
  2135. while (new > lim) {
  2136. STUNPUTC(new);
  2137. if (new[-1] == '/')
  2138. break;
  2139. }
  2140. break;
  2141. }
  2142. if (p[1] == '\0')
  2143. break;
  2144. /* fall through */
  2145. default:
  2146. new = stack_putstr(p, new);
  2147. USTPUTC('/', new);
  2148. }
  2149. p = strtok(0, "/");
  2150. }
  2151. if (new > lim)
  2152. STUNPUTC(new);
  2153. *new = 0;
  2154. return stackblock();
  2155. }
  2156. /*
  2157. * Find out what the current directory is. If we already know the current
  2158. * directory, this routine returns immediately.
  2159. */
  2160. static char *
  2161. getpwd(void)
  2162. {
  2163. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2164. return dir ? dir : nullstr;
  2165. }
  2166. static void
  2167. setpwd(const char *val, int setold)
  2168. {
  2169. char *oldcur, *dir;
  2170. oldcur = dir = curdir;
  2171. if (setold) {
  2172. setvar("OLDPWD", oldcur, VEXPORT);
  2173. }
  2174. INT_OFF;
  2175. if (physdir != nullstr) {
  2176. if (physdir != oldcur)
  2177. free(physdir);
  2178. physdir = nullstr;
  2179. }
  2180. if (oldcur == val || !val) {
  2181. char *s = getpwd();
  2182. physdir = s;
  2183. if (!val)
  2184. dir = s;
  2185. } else
  2186. dir = ckstrdup(val);
  2187. if (oldcur != dir && oldcur != nullstr) {
  2188. free(oldcur);
  2189. }
  2190. curdir = dir;
  2191. INT_ON;
  2192. setvar("PWD", dir, VEXPORT);
  2193. }
  2194. static void hashcd(void);
  2195. /*
  2196. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2197. * know that the current directory has changed.
  2198. */
  2199. static int
  2200. docd(const char *dest, int flags)
  2201. {
  2202. const char *dir = 0;
  2203. int err;
  2204. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2205. INT_OFF;
  2206. if (!(flags & CD_PHYSICAL)) {
  2207. dir = updatepwd(dest);
  2208. if (dir)
  2209. dest = dir;
  2210. }
  2211. err = chdir(dest);
  2212. if (err)
  2213. goto out;
  2214. setpwd(dir, 1);
  2215. hashcd();
  2216. out:
  2217. INT_ON;
  2218. return err;
  2219. }
  2220. static int FAST_FUNC
  2221. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2222. {
  2223. const char *dest;
  2224. const char *path;
  2225. const char *p;
  2226. char c;
  2227. struct stat statb;
  2228. int flags;
  2229. flags = cdopt();
  2230. dest = *argptr;
  2231. if (!dest)
  2232. dest = bltinlookup(homestr);
  2233. else if (LONE_DASH(dest)) {
  2234. dest = bltinlookup("OLDPWD");
  2235. flags |= CD_PRINT;
  2236. }
  2237. if (!dest)
  2238. dest = nullstr;
  2239. if (*dest == '/')
  2240. goto step7;
  2241. if (*dest == '.') {
  2242. c = dest[1];
  2243. dotdot:
  2244. switch (c) {
  2245. case '\0':
  2246. case '/':
  2247. goto step6;
  2248. case '.':
  2249. c = dest[2];
  2250. if (c != '.')
  2251. goto dotdot;
  2252. }
  2253. }
  2254. if (!*dest)
  2255. dest = ".";
  2256. path = bltinlookup("CDPATH");
  2257. if (!path) {
  2258. step6:
  2259. step7:
  2260. p = dest;
  2261. goto docd;
  2262. }
  2263. do {
  2264. c = *path;
  2265. p = path_advance(&path, dest);
  2266. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2267. if (c && c != ':')
  2268. flags |= CD_PRINT;
  2269. docd:
  2270. if (!docd(p, flags))
  2271. goto out;
  2272. break;
  2273. }
  2274. } while (path);
  2275. ash_msg_and_raise_error("can't cd to %s", dest);
  2276. /* NOTREACHED */
  2277. out:
  2278. if (flags & CD_PRINT)
  2279. out1fmt(snlfmt, curdir);
  2280. return 0;
  2281. }
  2282. static int FAST_FUNC
  2283. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2284. {
  2285. int flags;
  2286. const char *dir = curdir;
  2287. flags = cdopt();
  2288. if (flags) {
  2289. if (physdir == nullstr)
  2290. setpwd(dir, 0);
  2291. dir = physdir;
  2292. }
  2293. out1fmt(snlfmt, dir);
  2294. return 0;
  2295. }
  2296. /* ============ ... */
  2297. #define IBUFSIZ COMMON_BUFSIZE
  2298. /* buffer for top level input file */
  2299. #define basebuf bb_common_bufsiz1
  2300. /* Syntax classes */
  2301. #define CWORD 0 /* character is nothing special */
  2302. #define CNL 1 /* newline character */
  2303. #define CBACK 2 /* a backslash character */
  2304. #define CSQUOTE 3 /* single quote */
  2305. #define CDQUOTE 4 /* double quote */
  2306. #define CENDQUOTE 5 /* a terminating quote */
  2307. #define CBQUOTE 6 /* backwards single quote */
  2308. #define CVAR 7 /* a dollar sign */
  2309. #define CENDVAR 8 /* a '}' character */
  2310. #define CLP 9 /* a left paren in arithmetic */
  2311. #define CRP 10 /* a right paren in arithmetic */
  2312. #define CENDFILE 11 /* end of file */
  2313. #define CCTL 12 /* like CWORD, except it must be escaped */
  2314. #define CSPCL 13 /* these terminate a word */
  2315. #define CIGN 14 /* character should be ignored */
  2316. #if ENABLE_ASH_ALIAS
  2317. #define SYNBASE 130
  2318. #define PEOF -130
  2319. #define PEOA -129
  2320. #define PEOA_OR_PEOF PEOA
  2321. #else
  2322. #define SYNBASE 129
  2323. #define PEOF -129
  2324. #define PEOA_OR_PEOF PEOF
  2325. #endif
  2326. /* number syntax index */
  2327. #define BASESYNTAX 0 /* not in quotes */
  2328. #define DQSYNTAX 1 /* in double quotes */
  2329. #define SQSYNTAX 2 /* in single quotes */
  2330. #define ARISYNTAX 3 /* in arithmetic */
  2331. #define PSSYNTAX 4 /* prompt */
  2332. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2333. #define USE_SIT_FUNCTION
  2334. #endif
  2335. #if ENABLE_SH_MATH_SUPPORT
  2336. static const char S_I_T[][4] = {
  2337. #if ENABLE_ASH_ALIAS
  2338. { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
  2339. #endif
  2340. { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
  2341. { CNL, CNL, CNL, CNL }, /* 2, \n */
  2342. { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
  2343. { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
  2344. { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
  2345. { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
  2346. { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
  2347. { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
  2348. { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
  2349. { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
  2350. { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
  2351. #ifndef USE_SIT_FUNCTION
  2352. { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2353. { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2354. { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2355. #endif
  2356. };
  2357. #else
  2358. static const char S_I_T[][3] = {
  2359. #if ENABLE_ASH_ALIAS
  2360. { CSPCL, CIGN, CIGN }, /* 0, PEOA */
  2361. #endif
  2362. { CSPCL, CWORD, CWORD }, /* 1, ' ' */
  2363. { CNL, CNL, CNL }, /* 2, \n */
  2364. { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
  2365. { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
  2366. { CVAR, CVAR, CWORD }, /* 5, $ */
  2367. { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
  2368. { CSPCL, CWORD, CWORD }, /* 7, ( */
  2369. { CSPCL, CWORD, CWORD }, /* 8, ) */
  2370. { CBACK, CBACK, CCTL }, /* 9, \ */
  2371. { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
  2372. { CENDVAR, CENDVAR, CWORD }, /* 11, } */
  2373. #ifndef USE_SIT_FUNCTION
  2374. { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2375. { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2376. { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2377. #endif
  2378. };
  2379. #endif /* SH_MATH_SUPPORT */
  2380. #ifdef USE_SIT_FUNCTION
  2381. static int
  2382. SIT(int c, int syntax)
  2383. {
  2384. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2385. #if ENABLE_ASH_ALIAS
  2386. static const char syntax_index_table[] ALIGN1 = {
  2387. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2388. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2389. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2390. 11, 3 /* "}~" */
  2391. };
  2392. #else
  2393. static const char syntax_index_table[] ALIGN1 = {
  2394. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2395. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2396. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2397. 10, 2 /* "}~" */
  2398. };
  2399. #endif
  2400. const char *s;
  2401. int indx;
  2402. if (c == PEOF) { /* 2^8+2 */
  2403. return CENDFILE;
  2404. }
  2405. #if ENABLE_ASH_ALIAS
  2406. if (c == PEOA) { /* 2^8+1 */
  2407. indx = 0;
  2408. } else
  2409. #endif
  2410. {
  2411. if ((unsigned char)c >= (unsigned char)(CTLESC)
  2412. && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
  2413. ) {
  2414. return CCTL;
  2415. }
  2416. s = strchrnul(spec_symbls, c);
  2417. if (*s == '\0') {
  2418. return CWORD;
  2419. }
  2420. indx = syntax_index_table[s - spec_symbls];
  2421. }
  2422. return S_I_T[indx][syntax];
  2423. }
  2424. #else /* !USE_SIT_FUNCTION */
  2425. #if ENABLE_ASH_ALIAS
  2426. #define CSPCL_CIGN_CIGN_CIGN 0
  2427. #define CSPCL_CWORD_CWORD_CWORD 1
  2428. #define CNL_CNL_CNL_CNL 2
  2429. #define CWORD_CCTL_CCTL_CWORD 3
  2430. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  2431. #define CVAR_CVAR_CWORD_CVAR 5
  2432. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  2433. #define CSPCL_CWORD_CWORD_CLP 7
  2434. #define CSPCL_CWORD_CWORD_CRP 8
  2435. #define CBACK_CBACK_CCTL_CBACK 9
  2436. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  2437. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  2438. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  2439. #define CWORD_CWORD_CWORD_CWORD 13
  2440. #define CCTL_CCTL_CCTL_CCTL 14
  2441. #else
  2442. #define CSPCL_CWORD_CWORD_CWORD 0
  2443. #define CNL_CNL_CNL_CNL 1
  2444. #define CWORD_CCTL_CCTL_CWORD 2
  2445. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  2446. #define CVAR_CVAR_CWORD_CVAR 4
  2447. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  2448. #define CSPCL_CWORD_CWORD_CLP 6
  2449. #define CSPCL_CWORD_CWORD_CRP 7
  2450. #define CBACK_CBACK_CCTL_CBACK 8
  2451. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  2452. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  2453. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  2454. #define CWORD_CWORD_CWORD_CWORD 12
  2455. #define CCTL_CCTL_CCTL_CCTL 13
  2456. #endif
  2457. static const char syntax_index_table[258] = {
  2458. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2459. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2460. #if ENABLE_ASH_ALIAS
  2461. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2462. #endif
  2463. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2464. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2465. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2466. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2467. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2468. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2469. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2470. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2471. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2472. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  2473. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  2474. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  2475. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  2476. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  2477. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  2478. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  2479. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  2480. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  2481. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  2482. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  2483. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  2484. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  2485. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  2486. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  2487. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  2488. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  2489. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  2490. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  2491. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  2492. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  2493. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  2495. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  2496. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  2497. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  2498. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  2499. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  2500. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  2501. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  2502. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  2507. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  2508. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  2509. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  2511. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  2513. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  2514. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  2515. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  2516. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  2517. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  2520. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  2522. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  2528. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  2529. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  2530. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  2531. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  2533. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  2534. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  2535. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  2536. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  2537. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  2538. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  2571. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  2600. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2601. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  2602. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  2603. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  2604. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  2605. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  2606. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  2609. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  2611. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  2622. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  2623. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2624. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2625. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2626. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2627. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2628. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2630. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2631. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2632. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2633. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2634. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2637. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2639. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2650. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2651. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2652. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2653. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2654. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2655. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2683. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2684. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2685. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2688. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2693. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2694. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2695. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2696. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2697. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2698. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2716. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2717. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2718. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  2719. };
  2720. #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[(int)(c) + SYNBASE]][syntax])
  2721. #endif /* USE_SIT_FUNCTION */
  2722. /* ============ Alias handling */
  2723. #if ENABLE_ASH_ALIAS
  2724. #define ALIASINUSE 1
  2725. #define ALIASDEAD 2
  2726. struct alias {
  2727. struct alias *next;
  2728. char *name;
  2729. char *val;
  2730. int flag;
  2731. };
  2732. static struct alias **atab; // [ATABSIZE];
  2733. #define INIT_G_alias() do { \
  2734. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2735. } while (0)
  2736. static struct alias **
  2737. __lookupalias(const char *name) {
  2738. unsigned int hashval;
  2739. struct alias **app;
  2740. const char *p;
  2741. unsigned int ch;
  2742. p = name;
  2743. ch = (unsigned char)*p;
  2744. hashval = ch << 4;
  2745. while (ch) {
  2746. hashval += ch;
  2747. ch = (unsigned char)*++p;
  2748. }
  2749. app = &atab[hashval % ATABSIZE];
  2750. for (; *app; app = &(*app)->next) {
  2751. if (strcmp(name, (*app)->name) == 0) {
  2752. break;
  2753. }
  2754. }
  2755. return app;
  2756. }
  2757. static struct alias *
  2758. lookupalias(const char *name, int check)
  2759. {
  2760. struct alias *ap = *__lookupalias(name);
  2761. if (check && ap && (ap->flag & ALIASINUSE))
  2762. return NULL;
  2763. return ap;
  2764. }
  2765. static struct alias *
  2766. freealias(struct alias *ap)
  2767. {
  2768. struct alias *next;
  2769. if (ap->flag & ALIASINUSE) {
  2770. ap->flag |= ALIASDEAD;
  2771. return ap;
  2772. }
  2773. next = ap->next;
  2774. free(ap->name);
  2775. free(ap->val);
  2776. free(ap);
  2777. return next;
  2778. }
  2779. static void
  2780. setalias(const char *name, const char *val)
  2781. {
  2782. struct alias *ap, **app;
  2783. app = __lookupalias(name);
  2784. ap = *app;
  2785. INT_OFF;
  2786. if (ap) {
  2787. if (!(ap->flag & ALIASINUSE)) {
  2788. free(ap->val);
  2789. }
  2790. ap->val = ckstrdup(val);
  2791. ap->flag &= ~ALIASDEAD;
  2792. } else {
  2793. /* not found */
  2794. ap = ckzalloc(sizeof(struct alias));
  2795. ap->name = ckstrdup(name);
  2796. ap->val = ckstrdup(val);
  2797. /*ap->flag = 0; - ckzalloc did it */
  2798. /*ap->next = NULL;*/
  2799. *app = ap;
  2800. }
  2801. INT_ON;
  2802. }
  2803. static int
  2804. unalias(const char *name)
  2805. {
  2806. struct alias **app;
  2807. app = __lookupalias(name);
  2808. if (*app) {
  2809. INT_OFF;
  2810. *app = freealias(*app);
  2811. INT_ON;
  2812. return 0;
  2813. }
  2814. return 1;
  2815. }
  2816. static void
  2817. rmaliases(void)
  2818. {
  2819. struct alias *ap, **app;
  2820. int i;
  2821. INT_OFF;
  2822. for (i = 0; i < ATABSIZE; i++) {
  2823. app = &atab[i];
  2824. for (ap = *app; ap; ap = *app) {
  2825. *app = freealias(*app);
  2826. if (ap == *app) {
  2827. app = &ap->next;
  2828. }
  2829. }
  2830. }
  2831. INT_ON;
  2832. }
  2833. static void
  2834. printalias(const struct alias *ap)
  2835. {
  2836. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2837. }
  2838. /*
  2839. * TODO - sort output
  2840. */
  2841. static int FAST_FUNC
  2842. aliascmd(int argc UNUSED_PARAM, char **argv)
  2843. {
  2844. char *n, *v;
  2845. int ret = 0;
  2846. struct alias *ap;
  2847. if (!argv[1]) {
  2848. int i;
  2849. for (i = 0; i < ATABSIZE; i++) {
  2850. for (ap = atab[i]; ap; ap = ap->next) {
  2851. printalias(ap);
  2852. }
  2853. }
  2854. return 0;
  2855. }
  2856. while ((n = *++argv) != NULL) {
  2857. v = strchr(n+1, '=');
  2858. if (v == NULL) { /* n+1: funny ksh stuff */
  2859. ap = *__lookupalias(n);
  2860. if (ap == NULL) {
  2861. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2862. ret = 1;
  2863. } else
  2864. printalias(ap);
  2865. } else {
  2866. *v++ = '\0';
  2867. setalias(n, v);
  2868. }
  2869. }
  2870. return ret;
  2871. }
  2872. static int FAST_FUNC
  2873. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2874. {
  2875. int i;
  2876. while ((i = nextopt("a")) != '\0') {
  2877. if (i == 'a') {
  2878. rmaliases();
  2879. return 0;
  2880. }
  2881. }
  2882. for (i = 0; *argptr; argptr++) {
  2883. if (unalias(*argptr)) {
  2884. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2885. i = 1;
  2886. }
  2887. }
  2888. return i;
  2889. }
  2890. #endif /* ASH_ALIAS */
  2891. /* ============ jobs.c */
  2892. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2893. #define FORK_FG 0
  2894. #define FORK_BG 1
  2895. #define FORK_NOJOB 2
  2896. /* mode flags for showjob(s) */
  2897. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  2898. #define SHOW_PID 0x04 /* include process pid */
  2899. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  2900. /*
  2901. * A job structure contains information about a job. A job is either a
  2902. * single process or a set of processes contained in a pipeline. In the
  2903. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2904. * array of pids.
  2905. */
  2906. struct procstat {
  2907. pid_t pid; /* process id */
  2908. int status; /* last process status from wait() */
  2909. char *cmd; /* text of command being run */
  2910. };
  2911. struct job {
  2912. struct procstat ps0; /* status of process */
  2913. struct procstat *ps; /* status or processes when more than one */
  2914. #if JOBS
  2915. int stopstatus; /* status of a stopped job */
  2916. #endif
  2917. uint32_t
  2918. nprocs: 16, /* number of processes */
  2919. state: 8,
  2920. #define JOBRUNNING 0 /* at least one proc running */
  2921. #define JOBSTOPPED 1 /* all procs are stopped */
  2922. #define JOBDONE 2 /* all procs are completed */
  2923. #if JOBS
  2924. sigint: 1, /* job was killed by SIGINT */
  2925. jobctl: 1, /* job running under job control */
  2926. #endif
  2927. waited: 1, /* true if this entry has been waited for */
  2928. used: 1, /* true if this entry is in used */
  2929. changed: 1; /* true if status has changed */
  2930. struct job *prev_job; /* previous job */
  2931. };
  2932. static struct job *makejob(/*union node *,*/ int);
  2933. #if !JOBS
  2934. #define forkshell(job, node, mode) forkshell(job, mode)
  2935. #endif
  2936. static int forkshell(struct job *, union node *, int);
  2937. static int waitforjob(struct job *);
  2938. #if !JOBS
  2939. enum { doing_jobctl = 0 };
  2940. #define setjobctl(on) do {} while (0)
  2941. #else
  2942. static smallint doing_jobctl; //references:8
  2943. static void setjobctl(int);
  2944. #endif
  2945. /*
  2946. * Ignore a signal.
  2947. */
  2948. static void
  2949. ignoresig(int signo)
  2950. {
  2951. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  2952. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  2953. /* No, need to do it */
  2954. signal(signo, SIG_IGN);
  2955. }
  2956. sigmode[signo - 1] = S_HARD_IGN;
  2957. }
  2958. /*
  2959. * Signal handler. Only one usage site - in setsignal()
  2960. */
  2961. static void
  2962. onsig(int signo)
  2963. {
  2964. gotsig[signo - 1] = 1;
  2965. if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
  2966. if (!suppressint) {
  2967. pendingsig = 0;
  2968. raise_interrupt(); /* does not return */
  2969. }
  2970. intpending = 1;
  2971. } else {
  2972. pendingsig = signo;
  2973. }
  2974. }
  2975. /*
  2976. * Set the signal handler for the specified signal. The routine figures
  2977. * out what it should be set to.
  2978. */
  2979. static void
  2980. setsignal(int signo)
  2981. {
  2982. char *t;
  2983. char cur_act, new_act;
  2984. struct sigaction act;
  2985. t = trap[signo];
  2986. new_act = S_DFL;
  2987. if (t != NULL) { /* trap for this sig is set */
  2988. new_act = S_CATCH;
  2989. if (t[0] == '\0') /* trap is "": ignore this sig */
  2990. new_act = S_IGN;
  2991. }
  2992. if (rootshell && new_act == S_DFL) {
  2993. switch (signo) {
  2994. case SIGINT:
  2995. if (iflag || minusc || sflag == 0)
  2996. new_act = S_CATCH;
  2997. break;
  2998. case SIGQUIT:
  2999. #if DEBUG
  3000. if (debug)
  3001. break;
  3002. #endif
  3003. /* man bash:
  3004. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3005. * commands run by bash have signal handlers
  3006. * set to the values inherited by the shell
  3007. * from its parent". */
  3008. new_act = S_IGN;
  3009. break;
  3010. case SIGTERM:
  3011. if (iflag)
  3012. new_act = S_IGN;
  3013. break;
  3014. #if JOBS
  3015. case SIGTSTP:
  3016. case SIGTTOU:
  3017. if (mflag)
  3018. new_act = S_IGN;
  3019. break;
  3020. #endif
  3021. }
  3022. }
  3023. //TODO: if !rootshell, we reset SIGQUIT to DFL,
  3024. //whereas we have to restore it to what shell got on entry
  3025. //from the parent. See comment above
  3026. t = &sigmode[signo - 1];
  3027. cur_act = *t;
  3028. if (cur_act == 0) {
  3029. /* current setting is not yet known */
  3030. if (sigaction(signo, NULL, &act)) {
  3031. /* pretend it worked; maybe we should give a warning,
  3032. * but other shells don't. We don't alter sigmode,
  3033. * so we retry every time.
  3034. * btw, in Linux it never fails. --vda */
  3035. return;
  3036. }
  3037. if (act.sa_handler == SIG_IGN) {
  3038. cur_act = S_HARD_IGN;
  3039. if (mflag
  3040. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3041. ) {
  3042. cur_act = S_IGN; /* don't hard ignore these */
  3043. }
  3044. }
  3045. }
  3046. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3047. return;
  3048. act.sa_handler = SIG_DFL;
  3049. switch (new_act) {
  3050. case S_CATCH:
  3051. act.sa_handler = onsig;
  3052. act.sa_flags = 0; /* matters only if !DFL and !IGN */
  3053. sigfillset(&act.sa_mask); /* ditto */
  3054. break;
  3055. case S_IGN:
  3056. act.sa_handler = SIG_IGN;
  3057. break;
  3058. }
  3059. sigaction_set(signo, &act);
  3060. *t = new_act;
  3061. }
  3062. /* mode flags for set_curjob */
  3063. #define CUR_DELETE 2
  3064. #define CUR_RUNNING 1
  3065. #define CUR_STOPPED 0
  3066. /* mode flags for dowait */
  3067. #define DOWAIT_NONBLOCK WNOHANG
  3068. #define DOWAIT_BLOCK 0
  3069. #if JOBS
  3070. /* pgrp of shell on invocation */
  3071. static int initialpgrp; //references:2
  3072. static int ttyfd = -1; //5
  3073. #endif
  3074. /* array of jobs */
  3075. static struct job *jobtab; //5
  3076. /* size of array */
  3077. static unsigned njobs; //4
  3078. /* current job */
  3079. static struct job *curjob; //lots
  3080. /* number of presumed living untracked jobs */
  3081. static int jobless; //4
  3082. static void
  3083. set_curjob(struct job *jp, unsigned mode)
  3084. {
  3085. struct job *jp1;
  3086. struct job **jpp, **curp;
  3087. /* first remove from list */
  3088. jpp = curp = &curjob;
  3089. do {
  3090. jp1 = *jpp;
  3091. if (jp1 == jp)
  3092. break;
  3093. jpp = &jp1->prev_job;
  3094. } while (1);
  3095. *jpp = jp1->prev_job;
  3096. /* Then re-insert in correct position */
  3097. jpp = curp;
  3098. switch (mode) {
  3099. default:
  3100. #if DEBUG
  3101. abort();
  3102. #endif
  3103. case CUR_DELETE:
  3104. /* job being deleted */
  3105. break;
  3106. case CUR_RUNNING:
  3107. /* newly created job or backgrounded job,
  3108. put after all stopped jobs. */
  3109. do {
  3110. jp1 = *jpp;
  3111. #if JOBS
  3112. if (!jp1 || jp1->state != JOBSTOPPED)
  3113. #endif
  3114. break;
  3115. jpp = &jp1->prev_job;
  3116. } while (1);
  3117. /* FALLTHROUGH */
  3118. #if JOBS
  3119. case CUR_STOPPED:
  3120. #endif
  3121. /* newly stopped job - becomes curjob */
  3122. jp->prev_job = *jpp;
  3123. *jpp = jp;
  3124. break;
  3125. }
  3126. }
  3127. #if JOBS || DEBUG
  3128. static int
  3129. jobno(const struct job *jp)
  3130. {
  3131. return jp - jobtab + 1;
  3132. }
  3133. #endif
  3134. /*
  3135. * Convert a job name to a job structure.
  3136. */
  3137. #if !JOBS
  3138. #define getjob(name, getctl) getjob(name)
  3139. #endif
  3140. static struct job *
  3141. getjob(const char *name, int getctl)
  3142. {
  3143. struct job *jp;
  3144. struct job *found;
  3145. const char *err_msg = "No such job: %s";
  3146. unsigned num;
  3147. int c;
  3148. const char *p;
  3149. char *(*match)(const char *, const char *);
  3150. jp = curjob;
  3151. p = name;
  3152. if (!p)
  3153. goto currentjob;
  3154. if (*p != '%')
  3155. goto err;
  3156. c = *++p;
  3157. if (!c)
  3158. goto currentjob;
  3159. if (!p[1]) {
  3160. if (c == '+' || c == '%') {
  3161. currentjob:
  3162. err_msg = "No current job";
  3163. goto check;
  3164. }
  3165. if (c == '-') {
  3166. if (jp)
  3167. jp = jp->prev_job;
  3168. err_msg = "No previous job";
  3169. check:
  3170. if (!jp)
  3171. goto err;
  3172. goto gotit;
  3173. }
  3174. }
  3175. if (is_number(p)) {
  3176. // TODO: number() instead? It does error checking...
  3177. num = atoi(p);
  3178. if (num < njobs) {
  3179. jp = jobtab + num - 1;
  3180. if (jp->used)
  3181. goto gotit;
  3182. goto err;
  3183. }
  3184. }
  3185. match = prefix;
  3186. if (*p == '?') {
  3187. match = strstr;
  3188. p++;
  3189. }
  3190. found = 0;
  3191. while (1) {
  3192. if (!jp)
  3193. goto err;
  3194. if (match(jp->ps[0].cmd, p)) {
  3195. if (found)
  3196. goto err;
  3197. found = jp;
  3198. err_msg = "%s: ambiguous";
  3199. }
  3200. jp = jp->prev_job;
  3201. }
  3202. gotit:
  3203. #if JOBS
  3204. err_msg = "job %s not created under job control";
  3205. if (getctl && jp->jobctl == 0)
  3206. goto err;
  3207. #endif
  3208. return jp;
  3209. err:
  3210. ash_msg_and_raise_error(err_msg, name);
  3211. }
  3212. /*
  3213. * Mark a job structure as unused.
  3214. */
  3215. static void
  3216. freejob(struct job *jp)
  3217. {
  3218. struct procstat *ps;
  3219. int i;
  3220. INT_OFF;
  3221. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3222. if (ps->cmd != nullstr)
  3223. free(ps->cmd);
  3224. }
  3225. if (jp->ps != &jp->ps0)
  3226. free(jp->ps);
  3227. jp->used = 0;
  3228. set_curjob(jp, CUR_DELETE);
  3229. INT_ON;
  3230. }
  3231. #if JOBS
  3232. static void
  3233. xtcsetpgrp(int fd, pid_t pgrp)
  3234. {
  3235. if (tcsetpgrp(fd, pgrp))
  3236. ash_msg_and_raise_error("can't set tty process group (%m)");
  3237. }
  3238. /*
  3239. * Turn job control on and off.
  3240. *
  3241. * Note: This code assumes that the third arg to ioctl is a character
  3242. * pointer, which is true on Berkeley systems but not System V. Since
  3243. * System V doesn't have job control yet, this isn't a problem now.
  3244. *
  3245. * Called with interrupts off.
  3246. */
  3247. static void
  3248. setjobctl(int on)
  3249. {
  3250. int fd;
  3251. int pgrp;
  3252. if (on == doing_jobctl || rootshell == 0)
  3253. return;
  3254. if (on) {
  3255. int ofd;
  3256. ofd = fd = open(_PATH_TTY, O_RDWR);
  3257. if (fd < 0) {
  3258. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3259. * That sometimes helps to acquire controlling tty.
  3260. * Obviously, a workaround for bugs when someone
  3261. * failed to provide a controlling tty to bash! :) */
  3262. fd = 2;
  3263. while (!isatty(fd))
  3264. if (--fd < 0)
  3265. goto out;
  3266. }
  3267. fd = fcntl(fd, F_DUPFD, 10);
  3268. if (ofd >= 0)
  3269. close(ofd);
  3270. if (fd < 0)
  3271. goto out;
  3272. /* fd is a tty at this point */
  3273. close_on_exec_on(fd);
  3274. do { /* while we are in the background */
  3275. pgrp = tcgetpgrp(fd);
  3276. if (pgrp < 0) {
  3277. out:
  3278. ash_msg("can't access tty; job control turned off");
  3279. mflag = on = 0;
  3280. goto close;
  3281. }
  3282. if (pgrp == getpgrp())
  3283. break;
  3284. killpg(0, SIGTTIN);
  3285. } while (1);
  3286. initialpgrp = pgrp;
  3287. setsignal(SIGTSTP);
  3288. setsignal(SIGTTOU);
  3289. setsignal(SIGTTIN);
  3290. pgrp = rootpid;
  3291. setpgid(0, pgrp);
  3292. xtcsetpgrp(fd, pgrp);
  3293. } else {
  3294. /* turning job control off */
  3295. fd = ttyfd;
  3296. pgrp = initialpgrp;
  3297. /* was xtcsetpgrp, but this can make exiting ash
  3298. * loop forever if pty is already deleted */
  3299. tcsetpgrp(fd, pgrp);
  3300. setpgid(0, pgrp);
  3301. setsignal(SIGTSTP);
  3302. setsignal(SIGTTOU);
  3303. setsignal(SIGTTIN);
  3304. close:
  3305. if (fd >= 0)
  3306. close(fd);
  3307. fd = -1;
  3308. }
  3309. ttyfd = fd;
  3310. doing_jobctl = on;
  3311. }
  3312. static int FAST_FUNC
  3313. killcmd(int argc, char **argv)
  3314. {
  3315. int i = 1;
  3316. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3317. do {
  3318. if (argv[i][0] == '%') {
  3319. struct job *jp = getjob(argv[i], 0);
  3320. unsigned pid = jp->ps[0].pid;
  3321. /* Enough space for ' -NNN<nul>' */
  3322. argv[i] = alloca(sizeof(int)*3 + 3);
  3323. /* kill_main has matching code to expect
  3324. * leading space. Needed to not confuse
  3325. * negative pids with "kill -SIGNAL_NO" syntax */
  3326. sprintf(argv[i], " -%u", pid);
  3327. }
  3328. } while (argv[++i]);
  3329. }
  3330. return kill_main(argc, argv);
  3331. }
  3332. static void
  3333. showpipe(struct job *jp, FILE *out)
  3334. {
  3335. struct procstat *sp;
  3336. struct procstat *spend;
  3337. spend = jp->ps + jp->nprocs;
  3338. for (sp = jp->ps + 1; sp < spend; sp++)
  3339. fprintf(out, " | %s", sp->cmd);
  3340. outcslow('\n', out);
  3341. flush_stdout_stderr();
  3342. }
  3343. static int
  3344. restartjob(struct job *jp, int mode)
  3345. {
  3346. struct procstat *ps;
  3347. int i;
  3348. int status;
  3349. pid_t pgid;
  3350. INT_OFF;
  3351. if (jp->state == JOBDONE)
  3352. goto out;
  3353. jp->state = JOBRUNNING;
  3354. pgid = jp->ps->pid;
  3355. if (mode == FORK_FG)
  3356. xtcsetpgrp(ttyfd, pgid);
  3357. killpg(pgid, SIGCONT);
  3358. ps = jp->ps;
  3359. i = jp->nprocs;
  3360. do {
  3361. if (WIFSTOPPED(ps->status)) {
  3362. ps->status = -1;
  3363. }
  3364. ps++;
  3365. } while (--i);
  3366. out:
  3367. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3368. INT_ON;
  3369. return status;
  3370. }
  3371. static int FAST_FUNC
  3372. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3373. {
  3374. struct job *jp;
  3375. FILE *out;
  3376. int mode;
  3377. int retval;
  3378. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3379. nextopt(nullstr);
  3380. argv = argptr;
  3381. out = stdout;
  3382. do {
  3383. jp = getjob(*argv, 1);
  3384. if (mode == FORK_BG) {
  3385. set_curjob(jp, CUR_RUNNING);
  3386. fprintf(out, "[%d] ", jobno(jp));
  3387. }
  3388. outstr(jp->ps->cmd, out);
  3389. showpipe(jp, out);
  3390. retval = restartjob(jp, mode);
  3391. } while (*argv && *++argv);
  3392. return retval;
  3393. }
  3394. #endif
  3395. static int
  3396. sprint_status(char *s, int status, int sigonly)
  3397. {
  3398. int col;
  3399. int st;
  3400. col = 0;
  3401. if (!WIFEXITED(status)) {
  3402. #if JOBS
  3403. if (WIFSTOPPED(status))
  3404. st = WSTOPSIG(status);
  3405. else
  3406. #endif
  3407. st = WTERMSIG(status);
  3408. if (sigonly) {
  3409. if (st == SIGINT || st == SIGPIPE)
  3410. goto out;
  3411. #if JOBS
  3412. if (WIFSTOPPED(status))
  3413. goto out;
  3414. #endif
  3415. }
  3416. st &= 0x7f;
  3417. col = fmtstr(s, 32, strsignal(st));
  3418. if (WCOREDUMP(status)) {
  3419. col += fmtstr(s + col, 16, " (core dumped)");
  3420. }
  3421. } else if (!sigonly) {
  3422. st = WEXITSTATUS(status);
  3423. if (st)
  3424. col = fmtstr(s, 16, "Done(%d)", st);
  3425. else
  3426. col = fmtstr(s, 16, "Done");
  3427. }
  3428. out:
  3429. return col;
  3430. }
  3431. static int
  3432. dowait(int wait_flags, struct job *job)
  3433. {
  3434. int pid;
  3435. int status;
  3436. struct job *jp;
  3437. struct job *thisjob;
  3438. int state;
  3439. TRACE(("dowait(0x%x) called\n", wait_flags));
  3440. /* Do a wait system call. If job control is compiled in, we accept
  3441. * stopped processes. wait_flags may have WNOHANG, preventing blocking.
  3442. * NB: _not_ safe_waitpid, we need to detect EINTR */
  3443. pid = waitpid(-1, &status,
  3444. (doing_jobctl ? (wait_flags | WUNTRACED) : wait_flags));
  3445. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3446. pid, status, errno, strerror(errno)));
  3447. if (pid <= 0)
  3448. return pid;
  3449. INT_OFF;
  3450. thisjob = NULL;
  3451. for (jp = curjob; jp; jp = jp->prev_job) {
  3452. struct procstat *sp;
  3453. struct procstat *spend;
  3454. if (jp->state == JOBDONE)
  3455. continue;
  3456. state = JOBDONE;
  3457. spend = jp->ps + jp->nprocs;
  3458. sp = jp->ps;
  3459. do {
  3460. if (sp->pid == pid) {
  3461. TRACE(("Job %d: changing status of proc %d "
  3462. "from 0x%x to 0x%x\n",
  3463. jobno(jp), pid, sp->status, status));
  3464. sp->status = status;
  3465. thisjob = jp;
  3466. }
  3467. if (sp->status == -1)
  3468. state = JOBRUNNING;
  3469. #if JOBS
  3470. if (state == JOBRUNNING)
  3471. continue;
  3472. if (WIFSTOPPED(sp->status)) {
  3473. jp->stopstatus = sp->status;
  3474. state = JOBSTOPPED;
  3475. }
  3476. #endif
  3477. } while (++sp < spend);
  3478. if (thisjob)
  3479. goto gotjob;
  3480. }
  3481. #if JOBS
  3482. if (!WIFSTOPPED(status))
  3483. #endif
  3484. jobless--;
  3485. goto out;
  3486. gotjob:
  3487. if (state != JOBRUNNING) {
  3488. thisjob->changed = 1;
  3489. if (thisjob->state != state) {
  3490. TRACE(("Job %d: changing state from %d to %d\n",
  3491. jobno(thisjob), thisjob->state, state));
  3492. thisjob->state = state;
  3493. #if JOBS
  3494. if (state == JOBSTOPPED) {
  3495. set_curjob(thisjob, CUR_STOPPED);
  3496. }
  3497. #endif
  3498. }
  3499. }
  3500. out:
  3501. INT_ON;
  3502. if (thisjob && thisjob == job) {
  3503. char s[48 + 1];
  3504. int len;
  3505. len = sprint_status(s, status, 1);
  3506. if (len) {
  3507. s[len] = '\n';
  3508. s[len + 1] = '\0';
  3509. out2str(s);
  3510. }
  3511. }
  3512. return pid;
  3513. }
  3514. static int
  3515. blocking_wait_with_raise_on_sig(struct job *job)
  3516. {
  3517. pid_t pid = dowait(DOWAIT_BLOCK, job);
  3518. if (pid <= 0 && pendingsig)
  3519. raise_exception(EXSIG);
  3520. return pid;
  3521. }
  3522. #if JOBS
  3523. static void
  3524. showjob(FILE *out, struct job *jp, int mode)
  3525. {
  3526. struct procstat *ps;
  3527. struct procstat *psend;
  3528. int col;
  3529. int indent_col;
  3530. char s[80];
  3531. ps = jp->ps;
  3532. if (mode & SHOW_PGID) {
  3533. /* just output process (group) id of pipeline */
  3534. fprintf(out, "%d\n", ps->pid);
  3535. return;
  3536. }
  3537. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3538. indent_col = col;
  3539. if (jp == curjob)
  3540. s[col - 2] = '+';
  3541. else if (curjob && jp == curjob->prev_job)
  3542. s[col - 2] = '-';
  3543. if (mode & SHOW_PID)
  3544. col += fmtstr(s + col, 16, "%d ", ps->pid);
  3545. psend = ps + jp->nprocs;
  3546. if (jp->state == JOBRUNNING) {
  3547. strcpy(s + col, "Running");
  3548. col += sizeof("Running") - 1;
  3549. } else {
  3550. int status = psend[-1].status;
  3551. if (jp->state == JOBSTOPPED)
  3552. status = jp->stopstatus;
  3553. col += sprint_status(s + col, status, 0);
  3554. }
  3555. goto start;
  3556. do {
  3557. /* for each process */
  3558. col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
  3559. start:
  3560. fprintf(out, "%s%*c%s",
  3561. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  3562. );
  3563. if (!(mode & SHOW_PID)) {
  3564. showpipe(jp, out);
  3565. break;
  3566. }
  3567. if (++ps == psend) {
  3568. outcslow('\n', out);
  3569. break;
  3570. }
  3571. } while (1);
  3572. jp->changed = 0;
  3573. if (jp->state == JOBDONE) {
  3574. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3575. freejob(jp);
  3576. }
  3577. }
  3578. /*
  3579. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3580. * statuses have changed since the last call to showjobs.
  3581. */
  3582. static void
  3583. showjobs(FILE *out, int mode)
  3584. {
  3585. struct job *jp;
  3586. TRACE(("showjobs(0x%x) called\n", mode));
  3587. /* Handle all finished jobs */
  3588. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3589. continue;
  3590. for (jp = curjob; jp; jp = jp->prev_job) {
  3591. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3592. showjob(out, jp, mode);
  3593. }
  3594. }
  3595. }
  3596. static int FAST_FUNC
  3597. jobscmd(int argc UNUSED_PARAM, char **argv)
  3598. {
  3599. int mode, m;
  3600. mode = 0;
  3601. while ((m = nextopt("lp"))) {
  3602. if (m == 'l')
  3603. mode = SHOW_PID;
  3604. else
  3605. mode = SHOW_PGID;
  3606. }
  3607. argv = argptr;
  3608. if (*argv) {
  3609. do
  3610. showjob(stdout, getjob(*argv,0), mode);
  3611. while (*++argv);
  3612. } else
  3613. showjobs(stdout, mode);
  3614. return 0;
  3615. }
  3616. #endif /* JOBS */
  3617. static int
  3618. getstatus(struct job *job)
  3619. {
  3620. int status;
  3621. int retval;
  3622. status = job->ps[job->nprocs - 1].status;
  3623. retval = WEXITSTATUS(status);
  3624. if (!WIFEXITED(status)) {
  3625. #if JOBS
  3626. retval = WSTOPSIG(status);
  3627. if (!WIFSTOPPED(status))
  3628. #endif
  3629. {
  3630. /* XXX: limits number of signals */
  3631. retval = WTERMSIG(status);
  3632. #if JOBS
  3633. if (retval == SIGINT)
  3634. job->sigint = 1;
  3635. #endif
  3636. }
  3637. retval += 128;
  3638. }
  3639. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  3640. jobno(job), job->nprocs, status, retval));
  3641. return retval;
  3642. }
  3643. static int FAST_FUNC
  3644. waitcmd(int argc UNUSED_PARAM, char **argv)
  3645. {
  3646. struct job *job;
  3647. int retval;
  3648. struct job *jp;
  3649. // exsig++;
  3650. // xbarrier();
  3651. if (pendingsig)
  3652. raise_exception(EXSIG);
  3653. nextopt(nullstr);
  3654. retval = 0;
  3655. argv = argptr;
  3656. if (!*argv) {
  3657. /* wait for all jobs */
  3658. for (;;) {
  3659. jp = curjob;
  3660. while (1) {
  3661. if (!jp) /* no running procs */
  3662. goto ret;
  3663. if (jp->state == JOBRUNNING)
  3664. break;
  3665. jp->waited = 1;
  3666. jp = jp->prev_job;
  3667. }
  3668. /* man bash:
  3669. * "When bash is waiting for an asynchronous command via
  3670. * the wait builtin, the reception of a signal for which a trap
  3671. * has been set will cause the wait builtin to return immediately
  3672. * with an exit status greater than 128, immediately after which
  3673. * the trap is executed."
  3674. * Do we do it that way? */
  3675. blocking_wait_with_raise_on_sig(NULL);
  3676. }
  3677. }
  3678. retval = 127;
  3679. do {
  3680. if (**argv != '%') {
  3681. pid_t pid = number(*argv);
  3682. job = curjob;
  3683. while (1) {
  3684. if (!job)
  3685. goto repeat;
  3686. if (job->ps[job->nprocs - 1].pid == pid)
  3687. break;
  3688. job = job->prev_job;
  3689. }
  3690. } else
  3691. job = getjob(*argv, 0);
  3692. /* loop until process terminated or stopped */
  3693. while (job->state == JOBRUNNING)
  3694. blocking_wait_with_raise_on_sig(NULL);
  3695. job->waited = 1;
  3696. retval = getstatus(job);
  3697. repeat: ;
  3698. } while (*++argv);
  3699. ret:
  3700. return retval;
  3701. }
  3702. static struct job *
  3703. growjobtab(void)
  3704. {
  3705. size_t len;
  3706. ptrdiff_t offset;
  3707. struct job *jp, *jq;
  3708. len = njobs * sizeof(*jp);
  3709. jq = jobtab;
  3710. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3711. offset = (char *)jp - (char *)jq;
  3712. if (offset) {
  3713. /* Relocate pointers */
  3714. size_t l = len;
  3715. jq = (struct job *)((char *)jq + l);
  3716. while (l) {
  3717. l -= sizeof(*jp);
  3718. jq--;
  3719. #define joff(p) ((struct job *)((char *)(p) + l))
  3720. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3721. if (joff(jp)->ps == &jq->ps0)
  3722. jmove(joff(jp)->ps);
  3723. if (joff(jp)->prev_job)
  3724. jmove(joff(jp)->prev_job);
  3725. }
  3726. if (curjob)
  3727. jmove(curjob);
  3728. #undef joff
  3729. #undef jmove
  3730. }
  3731. njobs += 4;
  3732. jobtab = jp;
  3733. jp = (struct job *)((char *)jp + len);
  3734. jq = jp + 3;
  3735. do {
  3736. jq->used = 0;
  3737. } while (--jq >= jp);
  3738. return jp;
  3739. }
  3740. /*
  3741. * Return a new job structure.
  3742. * Called with interrupts off.
  3743. */
  3744. static struct job *
  3745. makejob(/*union node *node,*/ int nprocs)
  3746. {
  3747. int i;
  3748. struct job *jp;
  3749. for (i = njobs, jp = jobtab; ; jp++) {
  3750. if (--i < 0) {
  3751. jp = growjobtab();
  3752. break;
  3753. }
  3754. if (jp->used == 0)
  3755. break;
  3756. if (jp->state != JOBDONE || !jp->waited)
  3757. continue;
  3758. #if JOBS
  3759. if (doing_jobctl)
  3760. continue;
  3761. #endif
  3762. freejob(jp);
  3763. break;
  3764. }
  3765. memset(jp, 0, sizeof(*jp));
  3766. #if JOBS
  3767. /* jp->jobctl is a bitfield.
  3768. * "jp->jobctl |= jobctl" likely to give awful code */
  3769. if (doing_jobctl)
  3770. jp->jobctl = 1;
  3771. #endif
  3772. jp->prev_job = curjob;
  3773. curjob = jp;
  3774. jp->used = 1;
  3775. jp->ps = &jp->ps0;
  3776. if (nprocs > 1) {
  3777. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3778. }
  3779. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3780. jobno(jp)));
  3781. return jp;
  3782. }
  3783. #if JOBS
  3784. /*
  3785. * Return a string identifying a command (to be printed by the
  3786. * jobs command).
  3787. */
  3788. static char *cmdnextc;
  3789. static void
  3790. cmdputs(const char *s)
  3791. {
  3792. static const char vstype[VSTYPE + 1][3] = {
  3793. "", "}", "-", "+", "?", "=",
  3794. "%", "%%", "#", "##"
  3795. IF_ASH_BASH_COMPAT(, ":", "/", "//")
  3796. };
  3797. const char *p, *str;
  3798. char c, cc[2] = " ";
  3799. char *nextc;
  3800. int subtype = 0;
  3801. int quoted = 0;
  3802. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3803. p = s;
  3804. while ((c = *p++) != 0) {
  3805. str = NULL;
  3806. switch (c) {
  3807. case CTLESC:
  3808. c = *p++;
  3809. break;
  3810. case CTLVAR:
  3811. subtype = *p++;
  3812. if ((subtype & VSTYPE) == VSLENGTH)
  3813. str = "${#";
  3814. else
  3815. str = "${";
  3816. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3817. goto dostr;
  3818. quoted ^= 1;
  3819. c = '"';
  3820. break;
  3821. case CTLENDVAR:
  3822. str = "\"}" + !(quoted & 1);
  3823. quoted >>= 1;
  3824. subtype = 0;
  3825. goto dostr;
  3826. case CTLBACKQ:
  3827. str = "$(...)";
  3828. goto dostr;
  3829. case CTLBACKQ+CTLQUOTE:
  3830. str = "\"$(...)\"";
  3831. goto dostr;
  3832. #if ENABLE_SH_MATH_SUPPORT
  3833. case CTLARI:
  3834. str = "$((";
  3835. goto dostr;
  3836. case CTLENDARI:
  3837. str = "))";
  3838. goto dostr;
  3839. #endif
  3840. case CTLQUOTEMARK:
  3841. quoted ^= 1;
  3842. c = '"';
  3843. break;
  3844. case '=':
  3845. if (subtype == 0)
  3846. break;
  3847. if ((subtype & VSTYPE) != VSNORMAL)
  3848. quoted <<= 1;
  3849. str = vstype[subtype & VSTYPE];
  3850. if (subtype & VSNUL)
  3851. c = ':';
  3852. else
  3853. goto checkstr;
  3854. break;
  3855. case '\'':
  3856. case '\\':
  3857. case '"':
  3858. case '$':
  3859. /* These can only happen inside quotes */
  3860. cc[0] = c;
  3861. str = cc;
  3862. c = '\\';
  3863. break;
  3864. default:
  3865. break;
  3866. }
  3867. USTPUTC(c, nextc);
  3868. checkstr:
  3869. if (!str)
  3870. continue;
  3871. dostr:
  3872. while ((c = *str++)) {
  3873. USTPUTC(c, nextc);
  3874. }
  3875. }
  3876. if (quoted & 1) {
  3877. USTPUTC('"', nextc);
  3878. }
  3879. *nextc = 0;
  3880. cmdnextc = nextc;
  3881. }
  3882. /* cmdtxt() and cmdlist() call each other */
  3883. static void cmdtxt(union node *n);
  3884. static void
  3885. cmdlist(union node *np, int sep)
  3886. {
  3887. for (; np; np = np->narg.next) {
  3888. if (!sep)
  3889. cmdputs(" ");
  3890. cmdtxt(np);
  3891. if (sep && np->narg.next)
  3892. cmdputs(" ");
  3893. }
  3894. }
  3895. static void
  3896. cmdtxt(union node *n)
  3897. {
  3898. union node *np;
  3899. struct nodelist *lp;
  3900. const char *p;
  3901. if (!n)
  3902. return;
  3903. switch (n->type) {
  3904. default:
  3905. #if DEBUG
  3906. abort();
  3907. #endif
  3908. case NPIPE:
  3909. lp = n->npipe.cmdlist;
  3910. for (;;) {
  3911. cmdtxt(lp->n);
  3912. lp = lp->next;
  3913. if (!lp)
  3914. break;
  3915. cmdputs(" | ");
  3916. }
  3917. break;
  3918. case NSEMI:
  3919. p = "; ";
  3920. goto binop;
  3921. case NAND:
  3922. p = " && ";
  3923. goto binop;
  3924. case NOR:
  3925. p = " || ";
  3926. binop:
  3927. cmdtxt(n->nbinary.ch1);
  3928. cmdputs(p);
  3929. n = n->nbinary.ch2;
  3930. goto donode;
  3931. case NREDIR:
  3932. case NBACKGND:
  3933. n = n->nredir.n;
  3934. goto donode;
  3935. case NNOT:
  3936. cmdputs("!");
  3937. n = n->nnot.com;
  3938. donode:
  3939. cmdtxt(n);
  3940. break;
  3941. case NIF:
  3942. cmdputs("if ");
  3943. cmdtxt(n->nif.test);
  3944. cmdputs("; then ");
  3945. n = n->nif.ifpart;
  3946. if (n->nif.elsepart) {
  3947. cmdtxt(n);
  3948. cmdputs("; else ");
  3949. n = n->nif.elsepart;
  3950. }
  3951. p = "; fi";
  3952. goto dotail;
  3953. case NSUBSHELL:
  3954. cmdputs("(");
  3955. n = n->nredir.n;
  3956. p = ")";
  3957. goto dotail;
  3958. case NWHILE:
  3959. p = "while ";
  3960. goto until;
  3961. case NUNTIL:
  3962. p = "until ";
  3963. until:
  3964. cmdputs(p);
  3965. cmdtxt(n->nbinary.ch1);
  3966. n = n->nbinary.ch2;
  3967. p = "; done";
  3968. dodo:
  3969. cmdputs("; do ");
  3970. dotail:
  3971. cmdtxt(n);
  3972. goto dotail2;
  3973. case NFOR:
  3974. cmdputs("for ");
  3975. cmdputs(n->nfor.var);
  3976. cmdputs(" in ");
  3977. cmdlist(n->nfor.args, 1);
  3978. n = n->nfor.body;
  3979. p = "; done";
  3980. goto dodo;
  3981. case NDEFUN:
  3982. cmdputs(n->narg.text);
  3983. p = "() { ... }";
  3984. goto dotail2;
  3985. case NCMD:
  3986. cmdlist(n->ncmd.args, 1);
  3987. cmdlist(n->ncmd.redirect, 0);
  3988. break;
  3989. case NARG:
  3990. p = n->narg.text;
  3991. dotail2:
  3992. cmdputs(p);
  3993. break;
  3994. case NHERE:
  3995. case NXHERE:
  3996. p = "<<...";
  3997. goto dotail2;
  3998. case NCASE:
  3999. cmdputs("case ");
  4000. cmdputs(n->ncase.expr->narg.text);
  4001. cmdputs(" in ");
  4002. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4003. cmdtxt(np->nclist.pattern);
  4004. cmdputs(") ");
  4005. cmdtxt(np->nclist.body);
  4006. cmdputs(";; ");
  4007. }
  4008. p = "esac";
  4009. goto dotail2;
  4010. case NTO:
  4011. p = ">";
  4012. goto redir;
  4013. case NCLOBBER:
  4014. p = ">|";
  4015. goto redir;
  4016. case NAPPEND:
  4017. p = ">>";
  4018. goto redir;
  4019. #if ENABLE_ASH_BASH_COMPAT
  4020. case NTO2:
  4021. #endif
  4022. case NTOFD:
  4023. p = ">&";
  4024. goto redir;
  4025. case NFROM:
  4026. p = "<";
  4027. goto redir;
  4028. case NFROMFD:
  4029. p = "<&";
  4030. goto redir;
  4031. case NFROMTO:
  4032. p = "<>";
  4033. redir:
  4034. cmdputs(utoa(n->nfile.fd));
  4035. cmdputs(p);
  4036. if (n->type == NTOFD || n->type == NFROMFD) {
  4037. cmdputs(utoa(n->ndup.dupfd));
  4038. break;
  4039. }
  4040. n = n->nfile.fname;
  4041. goto donode;
  4042. }
  4043. }
  4044. static char *
  4045. commandtext(union node *n)
  4046. {
  4047. char *name;
  4048. STARTSTACKSTR(cmdnextc);
  4049. cmdtxt(n);
  4050. name = stackblock();
  4051. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4052. name, cmdnextc, cmdnextc));
  4053. return ckstrdup(name);
  4054. }
  4055. #endif /* JOBS */
  4056. /*
  4057. * Fork off a subshell. If we are doing job control, give the subshell its
  4058. * own process group. Jp is a job structure that the job is to be added to.
  4059. * N is the command that will be evaluated by the child. Both jp and n may
  4060. * be NULL. The mode parameter can be one of the following:
  4061. * FORK_FG - Fork off a foreground process.
  4062. * FORK_BG - Fork off a background process.
  4063. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4064. * process group even if job control is on.
  4065. *
  4066. * When job control is turned off, background processes have their standard
  4067. * input redirected to /dev/null (except for the second and later processes
  4068. * in a pipeline).
  4069. *
  4070. * Called with interrupts off.
  4071. */
  4072. /*
  4073. * Clear traps on a fork.
  4074. */
  4075. static void
  4076. clear_traps(void)
  4077. {
  4078. char **tp;
  4079. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4080. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4081. INT_OFF;
  4082. free(*tp);
  4083. *tp = NULL;
  4084. if (tp != &trap[0])
  4085. setsignal(tp - trap);
  4086. INT_ON;
  4087. }
  4088. }
  4089. }
  4090. /* Lives far away from here, needed for forkchild */
  4091. static void closescript(void);
  4092. /* Called after fork(), in child */
  4093. static void
  4094. forkchild(struct job *jp, /*union node *n,*/ int mode)
  4095. {
  4096. int oldlvl;
  4097. TRACE(("Child shell %d\n", getpid()));
  4098. oldlvl = shlvl;
  4099. shlvl++;
  4100. /* man bash: "Non-builtin commands run by bash have signal handlers
  4101. * set to the values inherited by the shell from its parent".
  4102. * Do we do it correctly? */
  4103. closescript();
  4104. clear_traps();
  4105. #if JOBS
  4106. /* do job control only in root shell */
  4107. doing_jobctl = 0;
  4108. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  4109. pid_t pgrp;
  4110. if (jp->nprocs == 0)
  4111. pgrp = getpid();
  4112. else
  4113. pgrp = jp->ps[0].pid;
  4114. /* this can fail because we are doing it in the parent also */
  4115. setpgid(0, pgrp);
  4116. if (mode == FORK_FG)
  4117. xtcsetpgrp(ttyfd, pgrp);
  4118. setsignal(SIGTSTP);
  4119. setsignal(SIGTTOU);
  4120. } else
  4121. #endif
  4122. if (mode == FORK_BG) {
  4123. /* man bash: "When job control is not in effect,
  4124. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4125. ignoresig(SIGINT);
  4126. ignoresig(SIGQUIT);
  4127. if (jp->nprocs == 0) {
  4128. close(0);
  4129. if (open(bb_dev_null, O_RDONLY) != 0)
  4130. ash_msg_and_raise_error("can't open '%s'", bb_dev_null);
  4131. }
  4132. }
  4133. if (!oldlvl) {
  4134. if (iflag) { /* why if iflag only? */
  4135. setsignal(SIGINT);
  4136. setsignal(SIGTERM);
  4137. }
  4138. /* man bash:
  4139. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4140. * commands run by bash have signal handlers
  4141. * set to the values inherited by the shell
  4142. * from its parent".
  4143. * Take care of the second rule: */
  4144. setsignal(SIGQUIT);
  4145. }
  4146. for (jp = curjob; jp; jp = jp->prev_job)
  4147. freejob(jp);
  4148. jobless = 0;
  4149. }
  4150. /* Called after fork(), in parent */
  4151. #if !JOBS
  4152. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4153. #endif
  4154. static void
  4155. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4156. {
  4157. TRACE(("In parent shell: child = %d\n", pid));
  4158. if (!jp) {
  4159. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4160. continue;
  4161. jobless++;
  4162. return;
  4163. }
  4164. #if JOBS
  4165. if (mode != FORK_NOJOB && jp->jobctl) {
  4166. int pgrp;
  4167. if (jp->nprocs == 0)
  4168. pgrp = pid;
  4169. else
  4170. pgrp = jp->ps[0].pid;
  4171. /* This can fail because we are doing it in the child also */
  4172. setpgid(pid, pgrp);
  4173. }
  4174. #endif
  4175. if (mode == FORK_BG) {
  4176. backgndpid = pid; /* set $! */
  4177. set_curjob(jp, CUR_RUNNING);
  4178. }
  4179. if (jp) {
  4180. struct procstat *ps = &jp->ps[jp->nprocs++];
  4181. ps->pid = pid;
  4182. ps->status = -1;
  4183. ps->cmd = nullstr;
  4184. #if JOBS
  4185. if (doing_jobctl && n)
  4186. ps->cmd = commandtext(n);
  4187. #endif
  4188. }
  4189. }
  4190. static int
  4191. forkshell(struct job *jp, union node *n, int mode)
  4192. {
  4193. int pid;
  4194. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4195. pid = fork();
  4196. if (pid < 0) {
  4197. TRACE(("Fork failed, errno=%d", errno));
  4198. if (jp)
  4199. freejob(jp);
  4200. ash_msg_and_raise_error("can't fork");
  4201. }
  4202. if (pid == 0)
  4203. forkchild(jp, /*n,*/ mode);
  4204. else
  4205. forkparent(jp, n, mode, pid);
  4206. return pid;
  4207. }
  4208. /*
  4209. * Wait for job to finish.
  4210. *
  4211. * Under job control we have the problem that while a child process
  4212. * is running interrupts generated by the user are sent to the child
  4213. * but not to the shell. This means that an infinite loop started by
  4214. * an interactive user may be hard to kill. With job control turned off,
  4215. * an interactive user may place an interactive program inside a loop.
  4216. * If the interactive program catches interrupts, the user doesn't want
  4217. * these interrupts to also abort the loop. The approach we take here
  4218. * is to have the shell ignore interrupt signals while waiting for a
  4219. * foreground process to terminate, and then send itself an interrupt
  4220. * signal if the child process was terminated by an interrupt signal.
  4221. * Unfortunately, some programs want to do a bit of cleanup and then
  4222. * exit on interrupt; unless these processes terminate themselves by
  4223. * sending a signal to themselves (instead of calling exit) they will
  4224. * confuse this approach.
  4225. *
  4226. * Called with interrupts off.
  4227. */
  4228. static int
  4229. waitforjob(struct job *jp)
  4230. {
  4231. int st;
  4232. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4233. INT_OFF;
  4234. while (jp->state == JOBRUNNING) {
  4235. /* In non-interactive shells, we _can_ get
  4236. * a keyboard signal here and be EINTRed,
  4237. * but we just loop back, waiting for command to complete.
  4238. *
  4239. * man bash:
  4240. * "If bash is waiting for a command to complete and receives
  4241. * a signal for which a trap has been set, the trap
  4242. * will not be executed until the command completes."
  4243. *
  4244. * Reality is that even if trap is not set, bash
  4245. * will not act on the signal until command completes.
  4246. * Try this. sleep5intoff.c:
  4247. * #include <signal.h>
  4248. * #include <unistd.h>
  4249. * int main() {
  4250. * sigset_t set;
  4251. * sigemptyset(&set);
  4252. * sigaddset(&set, SIGINT);
  4253. * sigaddset(&set, SIGQUIT);
  4254. * sigprocmask(SIG_BLOCK, &set, NULL);
  4255. * sleep(5);
  4256. * return 0;
  4257. * }
  4258. * $ bash -c './sleep5intoff; echo hi'
  4259. * ^C^C^C^C <--- pressing ^C once a second
  4260. * $ _
  4261. * $ bash -c './sleep5intoff; echo hi'
  4262. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4263. * $ _
  4264. */
  4265. dowait(DOWAIT_BLOCK, jp);
  4266. }
  4267. INT_ON;
  4268. st = getstatus(jp);
  4269. #if JOBS
  4270. if (jp->jobctl) {
  4271. xtcsetpgrp(ttyfd, rootpid);
  4272. /*
  4273. * This is truly gross.
  4274. * If we're doing job control, then we did a TIOCSPGRP which
  4275. * caused us (the shell) to no longer be in the controlling
  4276. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4277. * intuit from the subprocess exit status whether a SIGINT
  4278. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4279. */
  4280. if (jp->sigint) /* TODO: do the same with all signals */
  4281. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4282. }
  4283. if (jp->state == JOBDONE)
  4284. #endif
  4285. freejob(jp);
  4286. return st;
  4287. }
  4288. /*
  4289. * return 1 if there are stopped jobs, otherwise 0
  4290. */
  4291. static int
  4292. stoppedjobs(void)
  4293. {
  4294. struct job *jp;
  4295. int retval;
  4296. retval = 0;
  4297. if (job_warning)
  4298. goto out;
  4299. jp = curjob;
  4300. if (jp && jp->state == JOBSTOPPED) {
  4301. out2str("You have stopped jobs.\n");
  4302. job_warning = 2;
  4303. retval++;
  4304. }
  4305. out:
  4306. return retval;
  4307. }
  4308. /* ============ redir.c
  4309. *
  4310. * Code for dealing with input/output redirection.
  4311. */
  4312. #define EMPTY -2 /* marks an unused slot in redirtab */
  4313. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4314. /*
  4315. * Open a file in noclobber mode.
  4316. * The code was copied from bash.
  4317. */
  4318. static int
  4319. noclobberopen(const char *fname)
  4320. {
  4321. int r, fd;
  4322. struct stat finfo, finfo2;
  4323. /*
  4324. * If the file exists and is a regular file, return an error
  4325. * immediately.
  4326. */
  4327. r = stat(fname, &finfo);
  4328. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4329. errno = EEXIST;
  4330. return -1;
  4331. }
  4332. /*
  4333. * If the file was not present (r != 0), make sure we open it
  4334. * exclusively so that if it is created before we open it, our open
  4335. * will fail. Make sure that we do not truncate an existing file.
  4336. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4337. * file was not a regular file, we leave O_EXCL off.
  4338. */
  4339. if (r != 0)
  4340. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4341. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4342. /* If the open failed, return the file descriptor right away. */
  4343. if (fd < 0)
  4344. return fd;
  4345. /*
  4346. * OK, the open succeeded, but the file may have been changed from a
  4347. * non-regular file to a regular file between the stat and the open.
  4348. * We are assuming that the O_EXCL open handles the case where FILENAME
  4349. * did not exist and is symlinked to an existing file between the stat
  4350. * and open.
  4351. */
  4352. /*
  4353. * If we can open it and fstat the file descriptor, and neither check
  4354. * revealed that it was a regular file, and the file has not been
  4355. * replaced, return the file descriptor.
  4356. */
  4357. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4358. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4359. return fd;
  4360. /* The file has been replaced. badness. */
  4361. close(fd);
  4362. errno = EEXIST;
  4363. return -1;
  4364. }
  4365. /*
  4366. * Handle here documents. Normally we fork off a process to write the
  4367. * data to a pipe. If the document is short, we can stuff the data in
  4368. * the pipe without forking.
  4369. */
  4370. /* openhere needs this forward reference */
  4371. static void expandhere(union node *arg, int fd);
  4372. static int
  4373. openhere(union node *redir)
  4374. {
  4375. int pip[2];
  4376. size_t len = 0;
  4377. if (pipe(pip) < 0)
  4378. ash_msg_and_raise_error("pipe call failed");
  4379. if (redir->type == NHERE) {
  4380. len = strlen(redir->nhere.doc->narg.text);
  4381. if (len <= PIPE_BUF) {
  4382. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4383. goto out;
  4384. }
  4385. }
  4386. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4387. /* child */
  4388. close(pip[0]);
  4389. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4390. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4391. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4392. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4393. signal(SIGPIPE, SIG_DFL);
  4394. if (redir->type == NHERE)
  4395. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4396. else /* NXHERE */
  4397. expandhere(redir->nhere.doc, pip[1]);
  4398. _exit(EXIT_SUCCESS);
  4399. }
  4400. out:
  4401. close(pip[1]);
  4402. return pip[0];
  4403. }
  4404. static int
  4405. openredirect(union node *redir)
  4406. {
  4407. char *fname;
  4408. int f;
  4409. switch (redir->nfile.type) {
  4410. case NFROM:
  4411. fname = redir->nfile.expfname;
  4412. f = open(fname, O_RDONLY);
  4413. if (f < 0)
  4414. goto eopen;
  4415. break;
  4416. case NFROMTO:
  4417. fname = redir->nfile.expfname;
  4418. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4419. if (f < 0)
  4420. goto ecreate;
  4421. break;
  4422. case NTO:
  4423. #if ENABLE_ASH_BASH_COMPAT
  4424. case NTO2:
  4425. #endif
  4426. /* Take care of noclobber mode. */
  4427. if (Cflag) {
  4428. fname = redir->nfile.expfname;
  4429. f = noclobberopen(fname);
  4430. if (f < 0)
  4431. goto ecreate;
  4432. break;
  4433. }
  4434. /* FALLTHROUGH */
  4435. case NCLOBBER:
  4436. fname = redir->nfile.expfname;
  4437. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4438. if (f < 0)
  4439. goto ecreate;
  4440. break;
  4441. case NAPPEND:
  4442. fname = redir->nfile.expfname;
  4443. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4444. if (f < 0)
  4445. goto ecreate;
  4446. break;
  4447. default:
  4448. #if DEBUG
  4449. abort();
  4450. #endif
  4451. /* Fall through to eliminate warning. */
  4452. /* Our single caller does this itself */
  4453. // case NTOFD:
  4454. // case NFROMFD:
  4455. // f = -1;
  4456. // break;
  4457. case NHERE:
  4458. case NXHERE:
  4459. f = openhere(redir);
  4460. break;
  4461. }
  4462. return f;
  4463. ecreate:
  4464. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4465. eopen:
  4466. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4467. }
  4468. /*
  4469. * Copy a file descriptor to be >= to. Returns -1
  4470. * if the source file descriptor is closed, EMPTY if there are no unused
  4471. * file descriptors left.
  4472. */
  4473. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4474. * old code was doing close(to) prior to copyfd() to achieve the same */
  4475. enum {
  4476. COPYFD_EXACT = (int)~(INT_MAX),
  4477. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4478. };
  4479. static int
  4480. copyfd(int from, int to)
  4481. {
  4482. int newfd;
  4483. if (to & COPYFD_EXACT) {
  4484. to &= ~COPYFD_EXACT;
  4485. /*if (from != to)*/
  4486. newfd = dup2(from, to);
  4487. } else {
  4488. newfd = fcntl(from, F_DUPFD, to);
  4489. }
  4490. if (newfd < 0) {
  4491. if (errno == EMFILE)
  4492. return EMPTY;
  4493. /* Happens when source fd is not open: try "echo >&99" */
  4494. ash_msg_and_raise_error("%d: %m", from);
  4495. }
  4496. return newfd;
  4497. }
  4498. /* Struct def and variable are moved down to the first usage site */
  4499. struct two_fd_t {
  4500. int orig, copy;
  4501. };
  4502. struct redirtab {
  4503. struct redirtab *next;
  4504. int nullredirs;
  4505. int pair_count;
  4506. struct two_fd_t two_fd[0];
  4507. };
  4508. #define redirlist (G_var.redirlist)
  4509. static int need_to_remember(struct redirtab *rp, int fd)
  4510. {
  4511. int i;
  4512. if (!rp) /* remembering was not requested */
  4513. return 0;
  4514. for (i = 0; i < rp->pair_count; i++) {
  4515. if (rp->two_fd[i].orig == fd) {
  4516. /* already remembered */
  4517. return 0;
  4518. }
  4519. }
  4520. return 1;
  4521. }
  4522. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4523. static int is_hidden_fd(struct redirtab *rp, int fd)
  4524. {
  4525. int i;
  4526. struct parsefile *pf;
  4527. if (fd == -1)
  4528. return 0;
  4529. pf = g_parsefile;
  4530. while (pf) {
  4531. if (fd == pf->fd) {
  4532. return 1;
  4533. }
  4534. pf = pf->prev;
  4535. }
  4536. if (!rp)
  4537. return 0;
  4538. fd |= COPYFD_RESTORE;
  4539. for (i = 0; i < rp->pair_count; i++) {
  4540. if (rp->two_fd[i].copy == fd) {
  4541. return 1;
  4542. }
  4543. }
  4544. return 0;
  4545. }
  4546. /*
  4547. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4548. * old file descriptors are stashed away so that the redirection can be
  4549. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4550. * standard output, and the standard error if it becomes a duplicate of
  4551. * stdout, is saved in memory.
  4552. */
  4553. /* flags passed to redirect */
  4554. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4555. #define REDIR_SAVEFD2 03 /* set preverrout */
  4556. static void
  4557. redirect(union node *redir, int flags)
  4558. {
  4559. struct redirtab *sv;
  4560. int sv_pos;
  4561. int i;
  4562. int fd;
  4563. int newfd;
  4564. int copied_fd2 = -1;
  4565. g_nullredirs++;
  4566. if (!redir) {
  4567. return;
  4568. }
  4569. sv = NULL;
  4570. sv_pos = 0;
  4571. INT_OFF;
  4572. if (flags & REDIR_PUSH) {
  4573. union node *tmp = redir;
  4574. do {
  4575. sv_pos++;
  4576. #if ENABLE_ASH_BASH_COMPAT
  4577. if (redir->nfile.type == NTO2)
  4578. sv_pos++;
  4579. #endif
  4580. tmp = tmp->nfile.next;
  4581. } while (tmp);
  4582. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4583. sv->next = redirlist;
  4584. sv->pair_count = sv_pos;
  4585. redirlist = sv;
  4586. sv->nullredirs = g_nullredirs - 1;
  4587. g_nullredirs = 0;
  4588. while (sv_pos > 0) {
  4589. sv_pos--;
  4590. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4591. }
  4592. }
  4593. do {
  4594. fd = redir->nfile.fd;
  4595. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4596. int right_fd = redir->ndup.dupfd;
  4597. /* redirect from/to same file descriptor? */
  4598. if (right_fd == fd)
  4599. continue;
  4600. /* echo >&10 and 10 is a fd opened to the sh script? */
  4601. if (is_hidden_fd(sv, right_fd)) {
  4602. errno = EBADF; /* as if it is closed */
  4603. ash_msg_and_raise_error("%d: %m", right_fd);
  4604. }
  4605. newfd = -1;
  4606. } else {
  4607. newfd = openredirect(redir); /* always >= 0 */
  4608. if (fd == newfd) {
  4609. /* Descriptor wasn't open before redirect.
  4610. * Mark it for close in the future */
  4611. if (need_to_remember(sv, fd)) {
  4612. goto remember_to_close;
  4613. }
  4614. continue;
  4615. }
  4616. }
  4617. #if ENABLE_ASH_BASH_COMPAT
  4618. redirect_more:
  4619. #endif
  4620. if (need_to_remember(sv, fd)) {
  4621. /* Copy old descriptor */
  4622. i = fcntl(fd, F_DUPFD, 10);
  4623. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4624. * are closed in popredir() in the child, preventing them from leaking
  4625. * into child. (popredir() also cleans up the mess in case of failures)
  4626. */
  4627. if (i == -1) {
  4628. i = errno;
  4629. if (i != EBADF) {
  4630. /* Strange error (e.g. "too many files" EMFILE?) */
  4631. if (newfd >= 0)
  4632. close(newfd);
  4633. errno = i;
  4634. ash_msg_and_raise_error("%d: %m", fd);
  4635. /* NOTREACHED */
  4636. }
  4637. /* EBADF: it is not open - good, remember to close it */
  4638. remember_to_close:
  4639. i = CLOSED;
  4640. } else { /* fd is open, save its copy */
  4641. /* "exec fd>&-" should not close fds
  4642. * which point to script file(s).
  4643. * Force them to be restored afterwards */
  4644. if (is_hidden_fd(sv, fd))
  4645. i |= COPYFD_RESTORE;
  4646. }
  4647. if (fd == 2)
  4648. copied_fd2 = i;
  4649. sv->two_fd[sv_pos].orig = fd;
  4650. sv->two_fd[sv_pos].copy = i;
  4651. sv_pos++;
  4652. }
  4653. if (newfd < 0) {
  4654. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4655. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4656. /* Don't want to trigger debugging */
  4657. if (fd != -1)
  4658. close(fd);
  4659. } else {
  4660. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4661. }
  4662. } else if (fd != newfd) { /* move newfd to fd */
  4663. copyfd(newfd, fd | COPYFD_EXACT);
  4664. #if ENABLE_ASH_BASH_COMPAT
  4665. if (!(redir->nfile.type == NTO2 && fd == 2))
  4666. #endif
  4667. close(newfd);
  4668. }
  4669. #if ENABLE_ASH_BASH_COMPAT
  4670. if (redir->nfile.type == NTO2 && fd == 1) {
  4671. /* We already redirected it to fd 1, now copy it to 2 */
  4672. newfd = 1;
  4673. fd = 2;
  4674. goto redirect_more;
  4675. }
  4676. #endif
  4677. } while ((redir = redir->nfile.next) != NULL);
  4678. INT_ON;
  4679. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4680. preverrout_fd = copied_fd2;
  4681. }
  4682. /*
  4683. * Undo the effects of the last redirection.
  4684. */
  4685. static void
  4686. popredir(int drop, int restore)
  4687. {
  4688. struct redirtab *rp;
  4689. int i;
  4690. if (--g_nullredirs >= 0)
  4691. return;
  4692. INT_OFF;
  4693. rp = redirlist;
  4694. for (i = 0; i < rp->pair_count; i++) {
  4695. int fd = rp->two_fd[i].orig;
  4696. int copy = rp->two_fd[i].copy;
  4697. if (copy == CLOSED) {
  4698. if (!drop)
  4699. close(fd);
  4700. continue;
  4701. }
  4702. if (copy != EMPTY) {
  4703. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4704. copy &= ~COPYFD_RESTORE;
  4705. /*close(fd);*/
  4706. copyfd(copy, fd | COPYFD_EXACT);
  4707. }
  4708. close(copy & ~COPYFD_RESTORE);
  4709. }
  4710. }
  4711. redirlist = rp->next;
  4712. g_nullredirs = rp->nullredirs;
  4713. free(rp);
  4714. INT_ON;
  4715. }
  4716. /*
  4717. * Undo all redirections. Called on error or interrupt.
  4718. */
  4719. /*
  4720. * Discard all saved file descriptors.
  4721. */
  4722. static void
  4723. clearredir(int drop)
  4724. {
  4725. for (;;) {
  4726. g_nullredirs = 0;
  4727. if (!redirlist)
  4728. break;
  4729. popredir(drop, /*restore:*/ 0);
  4730. }
  4731. }
  4732. static int
  4733. redirectsafe(union node *redir, int flags)
  4734. {
  4735. int err;
  4736. volatile int saveint;
  4737. struct jmploc *volatile savehandler = exception_handler;
  4738. struct jmploc jmploc;
  4739. SAVE_INT(saveint);
  4740. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4741. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4742. if (!err) {
  4743. exception_handler = &jmploc;
  4744. redirect(redir, flags);
  4745. }
  4746. exception_handler = savehandler;
  4747. if (err && exception_type != EXERROR)
  4748. longjmp(exception_handler->loc, 1);
  4749. RESTORE_INT(saveint);
  4750. return err;
  4751. }
  4752. /* ============ Routines to expand arguments to commands
  4753. *
  4754. * We have to deal with backquotes, shell variables, and file metacharacters.
  4755. */
  4756. #if ENABLE_SH_MATH_SUPPORT
  4757. static arith_t
  4758. ash_arith(const char *s)
  4759. {
  4760. arith_eval_hooks_t math_hooks;
  4761. arith_t result;
  4762. int errcode = 0;
  4763. math_hooks.lookupvar = lookupvar;
  4764. math_hooks.setvar = setvar;
  4765. math_hooks.endofname = endofname;
  4766. INT_OFF;
  4767. result = arith(s, &errcode, &math_hooks);
  4768. if (errcode < 0) {
  4769. if (errcode == -3)
  4770. ash_msg_and_raise_error("exponent less than 0");
  4771. if (errcode == -2)
  4772. ash_msg_and_raise_error("divide by zero");
  4773. if (errcode == -5)
  4774. ash_msg_and_raise_error("expression recursion loop detected");
  4775. raise_error_syntax(s);
  4776. }
  4777. INT_ON;
  4778. return result;
  4779. }
  4780. #endif
  4781. /*
  4782. * expandarg flags
  4783. */
  4784. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4785. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4786. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4787. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4788. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4789. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4790. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4791. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4792. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4793. /*
  4794. * _rmescape() flags
  4795. */
  4796. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4797. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4798. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4799. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4800. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4801. /*
  4802. * Structure specifying which parts of the string should be searched
  4803. * for IFS characters.
  4804. */
  4805. struct ifsregion {
  4806. struct ifsregion *next; /* next region in list */
  4807. int begoff; /* offset of start of region */
  4808. int endoff; /* offset of end of region */
  4809. int nulonly; /* search for nul bytes only */
  4810. };
  4811. struct arglist {
  4812. struct strlist *list;
  4813. struct strlist **lastp;
  4814. };
  4815. /* output of current string */
  4816. static char *expdest;
  4817. /* list of back quote expressions */
  4818. static struct nodelist *argbackq;
  4819. /* first struct in list of ifs regions */
  4820. static struct ifsregion ifsfirst;
  4821. /* last struct in list */
  4822. static struct ifsregion *ifslastp;
  4823. /* holds expanded arg list */
  4824. static struct arglist exparg;
  4825. /*
  4826. * Our own itoa().
  4827. */
  4828. static int
  4829. cvtnum(arith_t num)
  4830. {
  4831. int len;
  4832. expdest = makestrspace(32, expdest);
  4833. len = fmtstr(expdest, 32, arith_t_fmt, num);
  4834. STADJUST(len, expdest);
  4835. return len;
  4836. }
  4837. static size_t
  4838. esclen(const char *start, const char *p)
  4839. {
  4840. size_t esc = 0;
  4841. while (p > start && *--p == CTLESC) {
  4842. esc++;
  4843. }
  4844. return esc;
  4845. }
  4846. /*
  4847. * Remove any CTLESC characters from a string.
  4848. */
  4849. static char *
  4850. _rmescapes(char *str, int flag)
  4851. {
  4852. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4853. char *p, *q, *r;
  4854. unsigned inquotes;
  4855. int notescaped;
  4856. int globbing;
  4857. p = strpbrk(str, qchars);
  4858. if (!p) {
  4859. return str;
  4860. }
  4861. q = p;
  4862. r = str;
  4863. if (flag & RMESCAPE_ALLOC) {
  4864. size_t len = p - str;
  4865. size_t fulllen = len + strlen(p) + 1;
  4866. if (flag & RMESCAPE_GROW) {
  4867. r = makestrspace(fulllen, expdest);
  4868. } else if (flag & RMESCAPE_HEAP) {
  4869. r = ckmalloc(fulllen);
  4870. } else {
  4871. r = stalloc(fulllen);
  4872. }
  4873. q = r;
  4874. if (len > 0) {
  4875. q = (char *)memcpy(q, str, len) + len;
  4876. }
  4877. }
  4878. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4879. globbing = flag & RMESCAPE_GLOB;
  4880. notescaped = globbing;
  4881. while (*p) {
  4882. if (*p == CTLQUOTEMARK) {
  4883. inquotes = ~inquotes;
  4884. p++;
  4885. notescaped = globbing;
  4886. continue;
  4887. }
  4888. if (*p == '\\') {
  4889. /* naked back slash */
  4890. notescaped = 0;
  4891. goto copy;
  4892. }
  4893. if (*p == CTLESC) {
  4894. p++;
  4895. if (notescaped && inquotes && *p != '/') {
  4896. *q++ = '\\';
  4897. }
  4898. }
  4899. notescaped = globbing;
  4900. copy:
  4901. *q++ = *p++;
  4902. }
  4903. *q = '\0';
  4904. if (flag & RMESCAPE_GROW) {
  4905. expdest = r;
  4906. STADJUST(q - r + 1, expdest);
  4907. }
  4908. return r;
  4909. }
  4910. #define rmescapes(p) _rmescapes((p), 0)
  4911. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4912. /*
  4913. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4914. *
  4915. * Returns an stalloced string.
  4916. */
  4917. static char *
  4918. preglob(const char *pattern, int quoted, int flag)
  4919. {
  4920. flag |= RMESCAPE_GLOB;
  4921. if (quoted) {
  4922. flag |= RMESCAPE_QUOTED;
  4923. }
  4924. return _rmescapes((char *)pattern, flag);
  4925. }
  4926. /*
  4927. * Put a string on the stack.
  4928. */
  4929. static void
  4930. memtodest(const char *p, size_t len, int syntax, int quotes)
  4931. {
  4932. char *q = expdest;
  4933. q = makestrspace(len * 2, q);
  4934. while (len--) {
  4935. int c = signed_char2int(*p++);
  4936. if (!c)
  4937. continue;
  4938. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4939. USTPUTC(CTLESC, q);
  4940. USTPUTC(c, q);
  4941. }
  4942. expdest = q;
  4943. }
  4944. static void
  4945. strtodest(const char *p, int syntax, int quotes)
  4946. {
  4947. memtodest(p, strlen(p), syntax, quotes);
  4948. }
  4949. /*
  4950. * Record the fact that we have to scan this region of the
  4951. * string for IFS characters.
  4952. */
  4953. static void
  4954. recordregion(int start, int end, int nulonly)
  4955. {
  4956. struct ifsregion *ifsp;
  4957. if (ifslastp == NULL) {
  4958. ifsp = &ifsfirst;
  4959. } else {
  4960. INT_OFF;
  4961. ifsp = ckzalloc(sizeof(*ifsp));
  4962. /*ifsp->next = NULL; - ckzalloc did it */
  4963. ifslastp->next = ifsp;
  4964. INT_ON;
  4965. }
  4966. ifslastp = ifsp;
  4967. ifslastp->begoff = start;
  4968. ifslastp->endoff = end;
  4969. ifslastp->nulonly = nulonly;
  4970. }
  4971. static void
  4972. removerecordregions(int endoff)
  4973. {
  4974. if (ifslastp == NULL)
  4975. return;
  4976. if (ifsfirst.endoff > endoff) {
  4977. while (ifsfirst.next != NULL) {
  4978. struct ifsregion *ifsp;
  4979. INT_OFF;
  4980. ifsp = ifsfirst.next->next;
  4981. free(ifsfirst.next);
  4982. ifsfirst.next = ifsp;
  4983. INT_ON;
  4984. }
  4985. if (ifsfirst.begoff > endoff)
  4986. ifslastp = NULL;
  4987. else {
  4988. ifslastp = &ifsfirst;
  4989. ifsfirst.endoff = endoff;
  4990. }
  4991. return;
  4992. }
  4993. ifslastp = &ifsfirst;
  4994. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4995. ifslastp=ifslastp->next;
  4996. while (ifslastp->next != NULL) {
  4997. struct ifsregion *ifsp;
  4998. INT_OFF;
  4999. ifsp = ifslastp->next->next;
  5000. free(ifslastp->next);
  5001. ifslastp->next = ifsp;
  5002. INT_ON;
  5003. }
  5004. if (ifslastp->endoff > endoff)
  5005. ifslastp->endoff = endoff;
  5006. }
  5007. static char *
  5008. exptilde(char *startp, char *p, int flag)
  5009. {
  5010. char c;
  5011. char *name;
  5012. struct passwd *pw;
  5013. const char *home;
  5014. int quotes = flag & (EXP_FULL | EXP_CASE);
  5015. int startloc;
  5016. name = p + 1;
  5017. while ((c = *++p) != '\0') {
  5018. switch (c) {
  5019. case CTLESC:
  5020. return startp;
  5021. case CTLQUOTEMARK:
  5022. return startp;
  5023. case ':':
  5024. if (flag & EXP_VARTILDE)
  5025. goto done;
  5026. break;
  5027. case '/':
  5028. case CTLENDVAR:
  5029. goto done;
  5030. }
  5031. }
  5032. done:
  5033. *p = '\0';
  5034. if (*name == '\0') {
  5035. home = lookupvar(homestr);
  5036. } else {
  5037. pw = getpwnam(name);
  5038. if (pw == NULL)
  5039. goto lose;
  5040. home = pw->pw_dir;
  5041. }
  5042. if (!home || !*home)
  5043. goto lose;
  5044. *p = c;
  5045. startloc = expdest - (char *)stackblock();
  5046. strtodest(home, SQSYNTAX, quotes);
  5047. recordregion(startloc, expdest - (char *)stackblock(), 0);
  5048. return p;
  5049. lose:
  5050. *p = c;
  5051. return startp;
  5052. }
  5053. /*
  5054. * Execute a command inside back quotes. If it's a builtin command, we
  5055. * want to save its output in a block obtained from malloc. Otherwise
  5056. * we fork off a subprocess and get the output of the command via a pipe.
  5057. * Should be called with interrupts off.
  5058. */
  5059. struct backcmd { /* result of evalbackcmd */
  5060. int fd; /* file descriptor to read from */
  5061. int nleft; /* number of chars in buffer */
  5062. char *buf; /* buffer */
  5063. struct job *jp; /* job structure for command */
  5064. };
  5065. /* These forward decls are needed to use "eval" code for backticks handling: */
  5066. static uint8_t back_exitstatus; /* exit status of backquoted command */
  5067. #define EV_EXIT 01 /* exit after evaluating tree */
  5068. static void evaltree(union node *, int);
  5069. static void FAST_FUNC
  5070. evalbackcmd(union node *n, struct backcmd *result)
  5071. {
  5072. int saveherefd;
  5073. result->fd = -1;
  5074. result->buf = NULL;
  5075. result->nleft = 0;
  5076. result->jp = NULL;
  5077. if (n == NULL)
  5078. goto out;
  5079. saveherefd = herefd;
  5080. herefd = -1;
  5081. {
  5082. int pip[2];
  5083. struct job *jp;
  5084. if (pipe(pip) < 0)
  5085. ash_msg_and_raise_error("pipe call failed");
  5086. jp = makejob(/*n,*/ 1);
  5087. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5088. FORCE_INT_ON;
  5089. close(pip[0]);
  5090. if (pip[1] != 1) {
  5091. /*close(1);*/
  5092. copyfd(pip[1], 1 | COPYFD_EXACT);
  5093. close(pip[1]);
  5094. }
  5095. eflag = 0;
  5096. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  5097. /* NOTREACHED */
  5098. }
  5099. close(pip[1]);
  5100. result->fd = pip[0];
  5101. result->jp = jp;
  5102. }
  5103. herefd = saveherefd;
  5104. out:
  5105. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5106. result->fd, result->buf, result->nleft, result->jp));
  5107. }
  5108. /*
  5109. * Expand stuff in backwards quotes.
  5110. */
  5111. static void
  5112. expbackq(union node *cmd, int quoted, int quotes)
  5113. {
  5114. struct backcmd in;
  5115. int i;
  5116. char buf[128];
  5117. char *p;
  5118. char *dest;
  5119. int startloc;
  5120. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5121. struct stackmark smark;
  5122. INT_OFF;
  5123. setstackmark(&smark);
  5124. dest = expdest;
  5125. startloc = dest - (char *)stackblock();
  5126. grabstackstr(dest);
  5127. evalbackcmd(cmd, &in);
  5128. popstackmark(&smark);
  5129. p = in.buf;
  5130. i = in.nleft;
  5131. if (i == 0)
  5132. goto read;
  5133. for (;;) {
  5134. memtodest(p, i, syntax, quotes);
  5135. read:
  5136. if (in.fd < 0)
  5137. break;
  5138. i = nonblock_safe_read(in.fd, buf, sizeof(buf));
  5139. TRACE(("expbackq: read returns %d\n", i));
  5140. if (i <= 0)
  5141. break;
  5142. p = buf;
  5143. }
  5144. free(in.buf);
  5145. if (in.fd >= 0) {
  5146. close(in.fd);
  5147. back_exitstatus = waitforjob(in.jp);
  5148. }
  5149. INT_ON;
  5150. /* Eat all trailing newlines */
  5151. dest = expdest;
  5152. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5153. STUNPUTC(dest);
  5154. expdest = dest;
  5155. if (quoted == 0)
  5156. recordregion(startloc, dest - (char *)stackblock(), 0);
  5157. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  5158. (dest - (char *)stackblock()) - startloc,
  5159. (dest - (char *)stackblock()) - startloc,
  5160. stackblock() + startloc));
  5161. }
  5162. #if ENABLE_SH_MATH_SUPPORT
  5163. /*
  5164. * Expand arithmetic expression. Backup to start of expression,
  5165. * evaluate, place result in (backed up) result, adjust string position.
  5166. */
  5167. static void
  5168. expari(int quotes)
  5169. {
  5170. char *p, *start;
  5171. int begoff;
  5172. int flag;
  5173. int len;
  5174. /* ifsfree(); */
  5175. /*
  5176. * This routine is slightly over-complicated for
  5177. * efficiency. Next we scan backwards looking for the
  5178. * start of arithmetic.
  5179. */
  5180. start = stackblock();
  5181. p = expdest - 1;
  5182. *p = '\0';
  5183. p--;
  5184. do {
  5185. int esc;
  5186. while (*p != CTLARI) {
  5187. p--;
  5188. #if DEBUG
  5189. if (p < start) {
  5190. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5191. }
  5192. #endif
  5193. }
  5194. esc = esclen(start, p);
  5195. if (!(esc % 2)) {
  5196. break;
  5197. }
  5198. p -= esc + 1;
  5199. } while (1);
  5200. begoff = p - start;
  5201. removerecordregions(begoff);
  5202. flag = p[1];
  5203. expdest = p;
  5204. if (quotes)
  5205. rmescapes(p + 2);
  5206. len = cvtnum(ash_arith(p + 2));
  5207. if (flag != '"')
  5208. recordregion(begoff, begoff + len, 0);
  5209. }
  5210. #endif
  5211. /* argstr needs it */
  5212. static char *evalvar(char *p, int flag, struct strlist *var_str_list);
  5213. /*
  5214. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5215. * characters to allow for further processing. Otherwise treat
  5216. * $@ like $* since no splitting will be performed.
  5217. *
  5218. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5219. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5220. * for correct expansion of "B=$A" word.
  5221. */
  5222. static void
  5223. argstr(char *p, int flag, struct strlist *var_str_list)
  5224. {
  5225. static const char spclchars[] ALIGN1 = {
  5226. '=',
  5227. ':',
  5228. CTLQUOTEMARK,
  5229. CTLENDVAR,
  5230. CTLESC,
  5231. CTLVAR,
  5232. CTLBACKQ,
  5233. CTLBACKQ | CTLQUOTE,
  5234. #if ENABLE_SH_MATH_SUPPORT
  5235. CTLENDARI,
  5236. #endif
  5237. 0
  5238. };
  5239. const char *reject = spclchars;
  5240. int c;
  5241. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  5242. int breakall = flag & EXP_WORD;
  5243. int inquotes;
  5244. size_t length;
  5245. int startloc;
  5246. if (!(flag & EXP_VARTILDE)) {
  5247. reject += 2;
  5248. } else if (flag & EXP_VARTILDE2) {
  5249. reject++;
  5250. }
  5251. inquotes = 0;
  5252. length = 0;
  5253. if (flag & EXP_TILDE) {
  5254. char *q;
  5255. flag &= ~EXP_TILDE;
  5256. tilde:
  5257. q = p;
  5258. if (*q == CTLESC && (flag & EXP_QWORD))
  5259. q++;
  5260. if (*q == '~')
  5261. p = exptilde(p, q, flag);
  5262. }
  5263. start:
  5264. startloc = expdest - (char *)stackblock();
  5265. for (;;) {
  5266. length += strcspn(p + length, reject);
  5267. c = p[length];
  5268. if (c && (!(c & 0x80)
  5269. #if ENABLE_SH_MATH_SUPPORT
  5270. || c == CTLENDARI
  5271. #endif
  5272. )) {
  5273. /* c == '=' || c == ':' || c == CTLENDARI */
  5274. length++;
  5275. }
  5276. if (length > 0) {
  5277. int newloc;
  5278. expdest = stack_nputstr(p, length, expdest);
  5279. newloc = expdest - (char *)stackblock();
  5280. if (breakall && !inquotes && newloc > startloc) {
  5281. recordregion(startloc, newloc, 0);
  5282. }
  5283. startloc = newloc;
  5284. }
  5285. p += length + 1;
  5286. length = 0;
  5287. switch (c) {
  5288. case '\0':
  5289. goto breakloop;
  5290. case '=':
  5291. if (flag & EXP_VARTILDE2) {
  5292. p--;
  5293. continue;
  5294. }
  5295. flag |= EXP_VARTILDE2;
  5296. reject++;
  5297. /* fall through */
  5298. case ':':
  5299. /*
  5300. * sort of a hack - expand tildes in variable
  5301. * assignments (after the first '=' and after ':'s).
  5302. */
  5303. if (*--p == '~') {
  5304. goto tilde;
  5305. }
  5306. continue;
  5307. }
  5308. switch (c) {
  5309. case CTLENDVAR: /* ??? */
  5310. goto breakloop;
  5311. case CTLQUOTEMARK:
  5312. /* "$@" syntax adherence hack */
  5313. if (
  5314. !inquotes &&
  5315. !memcmp(p, dolatstr, 4) &&
  5316. (p[4] == CTLQUOTEMARK || (
  5317. p[4] == CTLENDVAR &&
  5318. p[5] == CTLQUOTEMARK
  5319. ))
  5320. ) {
  5321. p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
  5322. goto start;
  5323. }
  5324. inquotes = !inquotes;
  5325. addquote:
  5326. if (quotes) {
  5327. p--;
  5328. length++;
  5329. startloc++;
  5330. }
  5331. break;
  5332. case CTLESC:
  5333. startloc++;
  5334. length++;
  5335. goto addquote;
  5336. case CTLVAR:
  5337. p = evalvar(p, flag, var_str_list);
  5338. goto start;
  5339. case CTLBACKQ:
  5340. c = 0;
  5341. case CTLBACKQ|CTLQUOTE:
  5342. expbackq(argbackq->n, c, quotes);
  5343. argbackq = argbackq->next;
  5344. goto start;
  5345. #if ENABLE_SH_MATH_SUPPORT
  5346. case CTLENDARI:
  5347. p--;
  5348. expari(quotes);
  5349. goto start;
  5350. #endif
  5351. }
  5352. }
  5353. breakloop:
  5354. ;
  5355. }
  5356. static char *
  5357. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
  5358. int zero)
  5359. {
  5360. // This commented out code was added by James Simmons <jsimmons@infradead.org>
  5361. // as part of a larger change when he added support for ${var/a/b}.
  5362. // However, it broke # and % operators:
  5363. //
  5364. //var=ababcdcd
  5365. // ok bad
  5366. //echo ${var#ab} abcdcd abcdcd
  5367. //echo ${var##ab} abcdcd abcdcd
  5368. //echo ${var#a*b} abcdcd ababcdcd (!)
  5369. //echo ${var##a*b} cdcd cdcd
  5370. //echo ${var#?} babcdcd ababcdcd (!)
  5371. //echo ${var##?} babcdcd babcdcd
  5372. //echo ${var#*} ababcdcd babcdcd (!)
  5373. //echo ${var##*}
  5374. //echo ${var%cd} ababcd ababcd
  5375. //echo ${var%%cd} ababcd abab (!)
  5376. //echo ${var%c*d} ababcd ababcd
  5377. //echo ${var%%c*d} abab ababcdcd (!)
  5378. //echo ${var%?} ababcdc ababcdc
  5379. //echo ${var%%?} ababcdc ababcdcd (!)
  5380. //echo ${var%*} ababcdcd ababcdcd
  5381. //echo ${var%%*}
  5382. //
  5383. // Commenting it back out helped. Remove it completely if it really
  5384. // is not needed.
  5385. char *loc, *loc2; //, *full;
  5386. char c;
  5387. loc = startp;
  5388. loc2 = rmesc;
  5389. do {
  5390. int match; // = strlen(str);
  5391. const char *s = loc2;
  5392. c = *loc2;
  5393. if (zero) {
  5394. *loc2 = '\0';
  5395. s = rmesc;
  5396. }
  5397. match = pmatch(str, s); // this line was deleted
  5398. // // chop off end if its '*'
  5399. // full = strrchr(str, '*');
  5400. // if (full && full != str)
  5401. // match--;
  5402. //
  5403. // // If str starts with '*' replace with s.
  5404. // if ((*str == '*') && strlen(s) >= match) {
  5405. // full = xstrdup(s);
  5406. // strncpy(full+strlen(s)-match+1, str+1, match-1);
  5407. // } else
  5408. // full = xstrndup(str, match);
  5409. // match = strncmp(s, full, strlen(full));
  5410. // free(full);
  5411. //
  5412. *loc2 = c;
  5413. if (match) // if (!match)
  5414. return loc;
  5415. if (quotes && *loc == CTLESC)
  5416. loc++;
  5417. loc++;
  5418. loc2++;
  5419. } while (c);
  5420. return 0;
  5421. }
  5422. static char *
  5423. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5424. int zero)
  5425. {
  5426. int esc = 0;
  5427. char *loc;
  5428. char *loc2;
  5429. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5430. int match;
  5431. char c = *loc2;
  5432. const char *s = loc2;
  5433. if (zero) {
  5434. *loc2 = '\0';
  5435. s = rmesc;
  5436. }
  5437. match = pmatch(str, s);
  5438. *loc2 = c;
  5439. if (match)
  5440. return loc;
  5441. loc--;
  5442. if (quotes) {
  5443. if (--esc < 0) {
  5444. esc = esclen(startp, loc);
  5445. }
  5446. if (esc % 2) {
  5447. esc--;
  5448. loc--;
  5449. }
  5450. }
  5451. }
  5452. return 0;
  5453. }
  5454. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5455. static void
  5456. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5457. {
  5458. const char *msg;
  5459. const char *tail;
  5460. tail = nullstr;
  5461. msg = "parameter not set";
  5462. if (umsg) {
  5463. if (*end == CTLENDVAR) {
  5464. if (varflags & VSNUL)
  5465. tail = " or null";
  5466. } else {
  5467. msg = umsg;
  5468. }
  5469. }
  5470. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5471. }
  5472. #if ENABLE_ASH_BASH_COMPAT
  5473. static char *
  5474. parse_sub_pattern(char *arg, int inquotes)
  5475. {
  5476. char *idx, *repl = NULL;
  5477. unsigned char c;
  5478. idx = arg;
  5479. while (1) {
  5480. c = *arg;
  5481. if (!c)
  5482. break;
  5483. if (c == '/') {
  5484. /* Only the first '/' seen is our separator */
  5485. if (!repl) {
  5486. repl = idx + 1;
  5487. c = '\0';
  5488. }
  5489. }
  5490. *idx++ = c;
  5491. if (!inquotes && c == '\\' && arg[1] == '\\')
  5492. arg++; /* skip both \\, not just first one */
  5493. arg++;
  5494. }
  5495. *idx = c; /* NUL */
  5496. return repl;
  5497. }
  5498. #endif /* ENABLE_ASH_BASH_COMPAT */
  5499. static const char *
  5500. subevalvar(char *p, char *str, int strloc, int subtype,
  5501. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5502. {
  5503. struct nodelist *saveargbackq = argbackq;
  5504. char *startp;
  5505. char *loc;
  5506. char *rmesc, *rmescend;
  5507. IF_ASH_BASH_COMPAT(char *repl = NULL;)
  5508. IF_ASH_BASH_COMPAT(char null = '\0';)
  5509. IF_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5510. int saveherefd = herefd;
  5511. int amount, workloc, resetloc;
  5512. int zero;
  5513. char *(*scan)(char*, char*, char*, char*, int, int);
  5514. herefd = -1;
  5515. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5516. var_str_list);
  5517. STPUTC('\0', expdest);
  5518. herefd = saveherefd;
  5519. argbackq = saveargbackq;
  5520. startp = (char *)stackblock() + startloc;
  5521. switch (subtype) {
  5522. case VSASSIGN:
  5523. setvar(str, startp, 0);
  5524. amount = startp - expdest;
  5525. STADJUST(amount, expdest);
  5526. return startp;
  5527. #if ENABLE_ASH_BASH_COMPAT
  5528. case VSSUBSTR:
  5529. loc = str = stackblock() + strloc;
  5530. // TODO: number() instead? It does error checking...
  5531. pos = atoi(loc);
  5532. len = str - startp - 1;
  5533. /* *loc != '\0', guaranteed by parser */
  5534. if (quotes) {
  5535. char *ptr;
  5536. /* We must adjust the length by the number of escapes we find. */
  5537. for (ptr = startp; ptr < (str - 1); ptr++) {
  5538. if (*ptr == CTLESC) {
  5539. len--;
  5540. ptr++;
  5541. }
  5542. }
  5543. }
  5544. orig_len = len;
  5545. if (*loc++ == ':') {
  5546. // TODO: number() instead? It does error checking...
  5547. len = atoi(loc);
  5548. } else {
  5549. len = orig_len;
  5550. while (*loc && *loc != ':')
  5551. loc++;
  5552. if (*loc++ == ':')
  5553. // TODO: number() instead? It does error checking...
  5554. len = atoi(loc);
  5555. }
  5556. if (pos >= orig_len) {
  5557. pos = 0;
  5558. len = 0;
  5559. }
  5560. if (len > (orig_len - pos))
  5561. len = orig_len - pos;
  5562. for (str = startp; pos; str++, pos--) {
  5563. if (quotes && *str == CTLESC)
  5564. str++;
  5565. }
  5566. for (loc = startp; len; len--) {
  5567. if (quotes && *str == CTLESC)
  5568. *loc++ = *str++;
  5569. *loc++ = *str++;
  5570. }
  5571. *loc = '\0';
  5572. amount = loc - expdest;
  5573. STADJUST(amount, expdest);
  5574. return loc;
  5575. #endif
  5576. case VSQUESTION:
  5577. varunset(p, str, startp, varflags);
  5578. /* NOTREACHED */
  5579. }
  5580. resetloc = expdest - (char *)stackblock();
  5581. /* We'll comeback here if we grow the stack while handling
  5582. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5583. * stack will need rebasing, and we'll need to remove our work
  5584. * areas each time
  5585. */
  5586. IF_ASH_BASH_COMPAT(restart:)
  5587. amount = expdest - ((char *)stackblock() + resetloc);
  5588. STADJUST(-amount, expdest);
  5589. startp = (char *)stackblock() + startloc;
  5590. rmesc = startp;
  5591. rmescend = (char *)stackblock() + strloc;
  5592. if (quotes) {
  5593. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5594. if (rmesc != startp) {
  5595. rmescend = expdest;
  5596. startp = (char *)stackblock() + startloc;
  5597. }
  5598. }
  5599. rmescend--;
  5600. str = (char *)stackblock() + strloc;
  5601. preglob(str, varflags & VSQUOTE, 0);
  5602. workloc = expdest - (char *)stackblock();
  5603. #if ENABLE_ASH_BASH_COMPAT
  5604. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5605. char *idx, *end, *restart_detect;
  5606. if (!repl) {
  5607. repl = parse_sub_pattern(str, varflags & VSQUOTE);
  5608. if (!repl)
  5609. repl = &null;
  5610. }
  5611. /* If there's no pattern to match, return the expansion unmolested */
  5612. if (*str == '\0')
  5613. return 0;
  5614. len = 0;
  5615. idx = startp;
  5616. end = str - 1;
  5617. while (idx < end) {
  5618. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5619. if (!loc) {
  5620. /* No match, advance */
  5621. restart_detect = stackblock();
  5622. STPUTC(*idx, expdest);
  5623. if (quotes && *idx == CTLESC) {
  5624. idx++;
  5625. len++;
  5626. STPUTC(*idx, expdest);
  5627. }
  5628. if (stackblock() != restart_detect)
  5629. goto restart;
  5630. idx++;
  5631. len++;
  5632. rmesc++;
  5633. continue;
  5634. }
  5635. if (subtype == VSREPLACEALL) {
  5636. while (idx < loc) {
  5637. if (quotes && *idx == CTLESC)
  5638. idx++;
  5639. idx++;
  5640. rmesc++;
  5641. }
  5642. } else {
  5643. idx = loc;
  5644. }
  5645. for (loc = repl; *loc; loc++) {
  5646. restart_detect = stackblock();
  5647. STPUTC(*loc, expdest);
  5648. if (stackblock() != restart_detect)
  5649. goto restart;
  5650. len++;
  5651. }
  5652. if (subtype == VSREPLACE) {
  5653. while (*idx) {
  5654. restart_detect = stackblock();
  5655. STPUTC(*idx, expdest);
  5656. if (stackblock() != restart_detect)
  5657. goto restart;
  5658. len++;
  5659. idx++;
  5660. }
  5661. break;
  5662. }
  5663. }
  5664. /* We've put the replaced text into a buffer at workloc, now
  5665. * move it to the right place and adjust the stack.
  5666. */
  5667. startp = stackblock() + startloc;
  5668. STPUTC('\0', expdest);
  5669. memmove(startp, stackblock() + workloc, len);
  5670. startp[len++] = '\0';
  5671. amount = expdest - ((char *)stackblock() + startloc + len - 1);
  5672. STADJUST(-amount, expdest);
  5673. return startp;
  5674. }
  5675. #endif /* ENABLE_ASH_BASH_COMPAT */
  5676. subtype -= VSTRIMRIGHT;
  5677. #if DEBUG
  5678. if (subtype < 0 || subtype > 7)
  5679. abort();
  5680. #endif
  5681. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  5682. zero = subtype >> 1;
  5683. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5684. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5685. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5686. if (loc) {
  5687. if (zero) {
  5688. memmove(startp, loc, str - loc);
  5689. loc = startp + (str - loc) - 1;
  5690. }
  5691. *loc = '\0';
  5692. amount = loc - expdest;
  5693. STADJUST(amount, expdest);
  5694. }
  5695. return loc;
  5696. }
  5697. /*
  5698. * Add the value of a specialized variable to the stack string.
  5699. */
  5700. static ssize_t
  5701. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5702. {
  5703. int num;
  5704. const char *p;
  5705. int i;
  5706. int sep = 0;
  5707. int sepq = 0;
  5708. ssize_t len = 0;
  5709. char **ap;
  5710. int syntax;
  5711. int quoted = varflags & VSQUOTE;
  5712. int subtype = varflags & VSTYPE;
  5713. int quotes = flags & (EXP_FULL | EXP_CASE);
  5714. if (quoted && (flags & EXP_FULL))
  5715. sep = 1 << CHAR_BIT;
  5716. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5717. switch (*name) {
  5718. case '$':
  5719. num = rootpid;
  5720. goto numvar;
  5721. case '?':
  5722. num = exitstatus;
  5723. goto numvar;
  5724. case '#':
  5725. num = shellparam.nparam;
  5726. goto numvar;
  5727. case '!':
  5728. num = backgndpid;
  5729. if (num == 0)
  5730. return -1;
  5731. numvar:
  5732. len = cvtnum(num);
  5733. break;
  5734. case '-':
  5735. expdest = makestrspace(NOPTS, expdest);
  5736. for (i = NOPTS - 1; i >= 0; i--) {
  5737. if (optlist[i]) {
  5738. USTPUTC(optletters(i), expdest);
  5739. len++;
  5740. }
  5741. }
  5742. break;
  5743. case '@':
  5744. if (sep)
  5745. goto param;
  5746. /* fall through */
  5747. case '*':
  5748. sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
  5749. if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
  5750. sepq = 1;
  5751. param:
  5752. ap = shellparam.p;
  5753. if (!ap)
  5754. return -1;
  5755. while ((p = *ap++)) {
  5756. size_t partlen;
  5757. partlen = strlen(p);
  5758. len += partlen;
  5759. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5760. memtodest(p, partlen, syntax, quotes);
  5761. if (*ap && sep) {
  5762. char *q;
  5763. len++;
  5764. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5765. continue;
  5766. }
  5767. q = expdest;
  5768. if (sepq)
  5769. STPUTC(CTLESC, q);
  5770. STPUTC(sep, q);
  5771. expdest = q;
  5772. }
  5773. }
  5774. return len;
  5775. case '0':
  5776. case '1':
  5777. case '2':
  5778. case '3':
  5779. case '4':
  5780. case '5':
  5781. case '6':
  5782. case '7':
  5783. case '8':
  5784. case '9':
  5785. // TODO: number() instead? It does error checking...
  5786. num = atoi(name);
  5787. if (num < 0 || num > shellparam.nparam)
  5788. return -1;
  5789. p = num ? shellparam.p[num - 1] : arg0;
  5790. goto value;
  5791. default:
  5792. /* NB: name has form "VAR=..." */
  5793. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  5794. * which should be considered before we check variables. */
  5795. if (var_str_list) {
  5796. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  5797. p = NULL;
  5798. do {
  5799. char *str, *eq;
  5800. str = var_str_list->text;
  5801. eq = strchr(str, '=');
  5802. if (!eq) /* stop at first non-assignment */
  5803. break;
  5804. eq++;
  5805. if (name_len == (unsigned)(eq - str)
  5806. && strncmp(str, name, name_len) == 0) {
  5807. p = eq;
  5808. /* goto value; - WRONG! */
  5809. /* think "A=1 A=2 B=$A" */
  5810. }
  5811. var_str_list = var_str_list->next;
  5812. } while (var_str_list);
  5813. if (p)
  5814. goto value;
  5815. }
  5816. p = lookupvar(name);
  5817. value:
  5818. if (!p)
  5819. return -1;
  5820. len = strlen(p);
  5821. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5822. memtodest(p, len, syntax, quotes);
  5823. return len;
  5824. }
  5825. if (subtype == VSPLUS || subtype == VSLENGTH)
  5826. STADJUST(-len, expdest);
  5827. return len;
  5828. }
  5829. /*
  5830. * Expand a variable, and return a pointer to the next character in the
  5831. * input string.
  5832. */
  5833. static char *
  5834. evalvar(char *p, int flag, struct strlist *var_str_list)
  5835. {
  5836. char varflags;
  5837. char subtype;
  5838. char quoted;
  5839. char easy;
  5840. char *var;
  5841. int patloc;
  5842. int startloc;
  5843. ssize_t varlen;
  5844. varflags = *p++;
  5845. subtype = varflags & VSTYPE;
  5846. quoted = varflags & VSQUOTE;
  5847. var = p;
  5848. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5849. startloc = expdest - (char *)stackblock();
  5850. p = strchr(p, '=') + 1;
  5851. again:
  5852. varlen = varvalue(var, varflags, flag, var_str_list);
  5853. if (varflags & VSNUL)
  5854. varlen--;
  5855. if (subtype == VSPLUS) {
  5856. varlen = -1 - varlen;
  5857. goto vsplus;
  5858. }
  5859. if (subtype == VSMINUS) {
  5860. vsplus:
  5861. if (varlen < 0) {
  5862. argstr(
  5863. p, flag | EXP_TILDE |
  5864. (quoted ? EXP_QWORD : EXP_WORD),
  5865. var_str_list
  5866. );
  5867. goto end;
  5868. }
  5869. if (easy)
  5870. goto record;
  5871. goto end;
  5872. }
  5873. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  5874. if (varlen < 0) {
  5875. if (subevalvar(p, var, /* strloc: */ 0,
  5876. subtype, startloc, varflags,
  5877. /* quotes: */ 0,
  5878. var_str_list)
  5879. ) {
  5880. varflags &= ~VSNUL;
  5881. /*
  5882. * Remove any recorded regions beyond
  5883. * start of variable
  5884. */
  5885. removerecordregions(startloc);
  5886. goto again;
  5887. }
  5888. goto end;
  5889. }
  5890. if (easy)
  5891. goto record;
  5892. goto end;
  5893. }
  5894. if (varlen < 0 && uflag)
  5895. varunset(p, var, 0, 0);
  5896. if (subtype == VSLENGTH) {
  5897. cvtnum(varlen > 0 ? varlen : 0);
  5898. goto record;
  5899. }
  5900. if (subtype == VSNORMAL) {
  5901. if (easy)
  5902. goto record;
  5903. goto end;
  5904. }
  5905. #if DEBUG
  5906. switch (subtype) {
  5907. case VSTRIMLEFT:
  5908. case VSTRIMLEFTMAX:
  5909. case VSTRIMRIGHT:
  5910. case VSTRIMRIGHTMAX:
  5911. #if ENABLE_ASH_BASH_COMPAT
  5912. case VSSUBSTR:
  5913. case VSREPLACE:
  5914. case VSREPLACEALL:
  5915. #endif
  5916. break;
  5917. default:
  5918. abort();
  5919. }
  5920. #endif
  5921. if (varlen >= 0) {
  5922. /*
  5923. * Terminate the string and start recording the pattern
  5924. * right after it
  5925. */
  5926. STPUTC('\0', expdest);
  5927. patloc = expdest - (char *)stackblock();
  5928. if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
  5929. startloc, varflags,
  5930. /* quotes: */ flag & (EXP_FULL | EXP_CASE),
  5931. var_str_list)
  5932. ) {
  5933. int amount = expdest - (
  5934. (char *)stackblock() + patloc - 1
  5935. );
  5936. STADJUST(-amount, expdest);
  5937. }
  5938. /* Remove any recorded regions beyond start of variable */
  5939. removerecordregions(startloc);
  5940. record:
  5941. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  5942. }
  5943. end:
  5944. if (subtype != VSNORMAL) { /* skip to end of alternative */
  5945. int nesting = 1;
  5946. for (;;) {
  5947. char c = *p++;
  5948. if (c == CTLESC)
  5949. p++;
  5950. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  5951. if (varlen >= 0)
  5952. argbackq = argbackq->next;
  5953. } else if (c == CTLVAR) {
  5954. if ((*p++ & VSTYPE) != VSNORMAL)
  5955. nesting++;
  5956. } else if (c == CTLENDVAR) {
  5957. if (--nesting == 0)
  5958. break;
  5959. }
  5960. }
  5961. }
  5962. return p;
  5963. }
  5964. /*
  5965. * Break the argument string into pieces based upon IFS and add the
  5966. * strings to the argument list. The regions of the string to be
  5967. * searched for IFS characters have been stored by recordregion.
  5968. */
  5969. static void
  5970. ifsbreakup(char *string, struct arglist *arglist)
  5971. {
  5972. struct ifsregion *ifsp;
  5973. struct strlist *sp;
  5974. char *start;
  5975. char *p;
  5976. char *q;
  5977. const char *ifs, *realifs;
  5978. int ifsspc;
  5979. int nulonly;
  5980. start = string;
  5981. if (ifslastp != NULL) {
  5982. ifsspc = 0;
  5983. nulonly = 0;
  5984. realifs = ifsset() ? ifsval() : defifs;
  5985. ifsp = &ifsfirst;
  5986. do {
  5987. p = string + ifsp->begoff;
  5988. nulonly = ifsp->nulonly;
  5989. ifs = nulonly ? nullstr : realifs;
  5990. ifsspc = 0;
  5991. while (p < string + ifsp->endoff) {
  5992. q = p;
  5993. if (*p == CTLESC)
  5994. p++;
  5995. if (!strchr(ifs, *p)) {
  5996. p++;
  5997. continue;
  5998. }
  5999. if (!nulonly)
  6000. ifsspc = (strchr(defifs, *p) != NULL);
  6001. /* Ignore IFS whitespace at start */
  6002. if (q == start && ifsspc) {
  6003. p++;
  6004. start = p;
  6005. continue;
  6006. }
  6007. *q = '\0';
  6008. sp = stzalloc(sizeof(*sp));
  6009. sp->text = start;
  6010. *arglist->lastp = sp;
  6011. arglist->lastp = &sp->next;
  6012. p++;
  6013. if (!nulonly) {
  6014. for (;;) {
  6015. if (p >= string + ifsp->endoff) {
  6016. break;
  6017. }
  6018. q = p;
  6019. if (*p == CTLESC)
  6020. p++;
  6021. if (strchr(ifs, *p) == NULL) {
  6022. p = q;
  6023. break;
  6024. }
  6025. if (strchr(defifs, *p) == NULL) {
  6026. if (ifsspc) {
  6027. p++;
  6028. ifsspc = 0;
  6029. } else {
  6030. p = q;
  6031. break;
  6032. }
  6033. } else
  6034. p++;
  6035. }
  6036. }
  6037. start = p;
  6038. } /* while */
  6039. ifsp = ifsp->next;
  6040. } while (ifsp != NULL);
  6041. if (nulonly)
  6042. goto add;
  6043. }
  6044. if (!*start)
  6045. return;
  6046. add:
  6047. sp = stzalloc(sizeof(*sp));
  6048. sp->text = start;
  6049. *arglist->lastp = sp;
  6050. arglist->lastp = &sp->next;
  6051. }
  6052. static void
  6053. ifsfree(void)
  6054. {
  6055. struct ifsregion *p;
  6056. INT_OFF;
  6057. p = ifsfirst.next;
  6058. do {
  6059. struct ifsregion *ifsp;
  6060. ifsp = p->next;
  6061. free(p);
  6062. p = ifsp;
  6063. } while (p);
  6064. ifslastp = NULL;
  6065. ifsfirst.next = NULL;
  6066. INT_ON;
  6067. }
  6068. /*
  6069. * Add a file name to the list.
  6070. */
  6071. static void
  6072. addfname(const char *name)
  6073. {
  6074. struct strlist *sp;
  6075. sp = stzalloc(sizeof(*sp));
  6076. sp->text = ststrdup(name);
  6077. *exparg.lastp = sp;
  6078. exparg.lastp = &sp->next;
  6079. }
  6080. static char *expdir;
  6081. /*
  6082. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6083. */
  6084. static void
  6085. expmeta(char *enddir, char *name)
  6086. {
  6087. char *p;
  6088. const char *cp;
  6089. char *start;
  6090. char *endname;
  6091. int metaflag;
  6092. struct stat statb;
  6093. DIR *dirp;
  6094. struct dirent *dp;
  6095. int atend;
  6096. int matchdot;
  6097. metaflag = 0;
  6098. start = name;
  6099. for (p = name; *p; p++) {
  6100. if (*p == '*' || *p == '?')
  6101. metaflag = 1;
  6102. else if (*p == '[') {
  6103. char *q = p + 1;
  6104. if (*q == '!')
  6105. q++;
  6106. for (;;) {
  6107. if (*q == '\\')
  6108. q++;
  6109. if (*q == '/' || *q == '\0')
  6110. break;
  6111. if (*++q == ']') {
  6112. metaflag = 1;
  6113. break;
  6114. }
  6115. }
  6116. } else if (*p == '\\')
  6117. p++;
  6118. else if (*p == '/') {
  6119. if (metaflag)
  6120. goto out;
  6121. start = p + 1;
  6122. }
  6123. }
  6124. out:
  6125. if (metaflag == 0) { /* we've reached the end of the file name */
  6126. if (enddir != expdir)
  6127. metaflag++;
  6128. p = name;
  6129. do {
  6130. if (*p == '\\')
  6131. p++;
  6132. *enddir++ = *p;
  6133. } while (*p++);
  6134. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6135. addfname(expdir);
  6136. return;
  6137. }
  6138. endname = p;
  6139. if (name < start) {
  6140. p = name;
  6141. do {
  6142. if (*p == '\\')
  6143. p++;
  6144. *enddir++ = *p++;
  6145. } while (p < start);
  6146. }
  6147. if (enddir == expdir) {
  6148. cp = ".";
  6149. } else if (enddir == expdir + 1 && *expdir == '/') {
  6150. cp = "/";
  6151. } else {
  6152. cp = expdir;
  6153. enddir[-1] = '\0';
  6154. }
  6155. dirp = opendir(cp);
  6156. if (dirp == NULL)
  6157. return;
  6158. if (enddir != expdir)
  6159. enddir[-1] = '/';
  6160. if (*endname == 0) {
  6161. atend = 1;
  6162. } else {
  6163. atend = 0;
  6164. *endname++ = '\0';
  6165. }
  6166. matchdot = 0;
  6167. p = start;
  6168. if (*p == '\\')
  6169. p++;
  6170. if (*p == '.')
  6171. matchdot++;
  6172. while (!intpending && (dp = readdir(dirp)) != NULL) {
  6173. if (dp->d_name[0] == '.' && !matchdot)
  6174. continue;
  6175. if (pmatch(start, dp->d_name)) {
  6176. if (atend) {
  6177. strcpy(enddir, dp->d_name);
  6178. addfname(expdir);
  6179. } else {
  6180. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6181. continue;
  6182. p[-1] = '/';
  6183. expmeta(p, endname);
  6184. }
  6185. }
  6186. }
  6187. closedir(dirp);
  6188. if (!atend)
  6189. endname[-1] = '/';
  6190. }
  6191. static struct strlist *
  6192. msort(struct strlist *list, int len)
  6193. {
  6194. struct strlist *p, *q = NULL;
  6195. struct strlist **lpp;
  6196. int half;
  6197. int n;
  6198. if (len <= 1)
  6199. return list;
  6200. half = len >> 1;
  6201. p = list;
  6202. for (n = half; --n >= 0;) {
  6203. q = p;
  6204. p = p->next;
  6205. }
  6206. q->next = NULL; /* terminate first half of list */
  6207. q = msort(list, half); /* sort first half of list */
  6208. p = msort(p, len - half); /* sort second half */
  6209. lpp = &list;
  6210. for (;;) {
  6211. #if ENABLE_LOCALE_SUPPORT
  6212. if (strcoll(p->text, q->text) < 0)
  6213. #else
  6214. if (strcmp(p->text, q->text) < 0)
  6215. #endif
  6216. {
  6217. *lpp = p;
  6218. lpp = &p->next;
  6219. p = *lpp;
  6220. if (p == NULL) {
  6221. *lpp = q;
  6222. break;
  6223. }
  6224. } else {
  6225. *lpp = q;
  6226. lpp = &q->next;
  6227. q = *lpp;
  6228. if (q == NULL) {
  6229. *lpp = p;
  6230. break;
  6231. }
  6232. }
  6233. }
  6234. return list;
  6235. }
  6236. /*
  6237. * Sort the results of file name expansion. It calculates the number of
  6238. * strings to sort and then calls msort (short for merge sort) to do the
  6239. * work.
  6240. */
  6241. static struct strlist *
  6242. expsort(struct strlist *str)
  6243. {
  6244. int len;
  6245. struct strlist *sp;
  6246. len = 0;
  6247. for (sp = str; sp; sp = sp->next)
  6248. len++;
  6249. return msort(str, len);
  6250. }
  6251. static void
  6252. expandmeta(struct strlist *str /*, int flag*/)
  6253. {
  6254. static const char metachars[] ALIGN1 = {
  6255. '*', '?', '[', 0
  6256. };
  6257. /* TODO - EXP_REDIR */
  6258. while (str) {
  6259. struct strlist **savelastp;
  6260. struct strlist *sp;
  6261. char *p;
  6262. if (fflag)
  6263. goto nometa;
  6264. if (!strpbrk(str->text, metachars))
  6265. goto nometa;
  6266. savelastp = exparg.lastp;
  6267. INT_OFF;
  6268. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6269. {
  6270. int i = strlen(str->text);
  6271. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6272. }
  6273. expmeta(expdir, p);
  6274. free(expdir);
  6275. if (p != str->text)
  6276. free(p);
  6277. INT_ON;
  6278. if (exparg.lastp == savelastp) {
  6279. /*
  6280. * no matches
  6281. */
  6282. nometa:
  6283. *exparg.lastp = str;
  6284. rmescapes(str->text);
  6285. exparg.lastp = &str->next;
  6286. } else {
  6287. *exparg.lastp = NULL;
  6288. *savelastp = sp = expsort(*savelastp);
  6289. while (sp->next != NULL)
  6290. sp = sp->next;
  6291. exparg.lastp = &sp->next;
  6292. }
  6293. str = str->next;
  6294. }
  6295. }
  6296. /*
  6297. * Perform variable substitution and command substitution on an argument,
  6298. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6299. * perform splitting and file name expansion. When arglist is NULL, perform
  6300. * here document expansion.
  6301. */
  6302. static void
  6303. expandarg(union node *arg, struct arglist *arglist, int flag)
  6304. {
  6305. struct strlist *sp;
  6306. char *p;
  6307. argbackq = arg->narg.backquote;
  6308. STARTSTACKSTR(expdest);
  6309. ifsfirst.next = NULL;
  6310. ifslastp = NULL;
  6311. argstr(arg->narg.text, flag,
  6312. /* var_str_list: */ arglist ? arglist->list : NULL);
  6313. p = _STPUTC('\0', expdest);
  6314. expdest = p - 1;
  6315. if (arglist == NULL) {
  6316. return; /* here document expanded */
  6317. }
  6318. p = grabstackstr(p);
  6319. exparg.lastp = &exparg.list;
  6320. /*
  6321. * TODO - EXP_REDIR
  6322. */
  6323. if (flag & EXP_FULL) {
  6324. ifsbreakup(p, &exparg);
  6325. *exparg.lastp = NULL;
  6326. exparg.lastp = &exparg.list;
  6327. expandmeta(exparg.list /*, flag*/);
  6328. } else {
  6329. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6330. rmescapes(p);
  6331. sp = stzalloc(sizeof(*sp));
  6332. sp->text = p;
  6333. *exparg.lastp = sp;
  6334. exparg.lastp = &sp->next;
  6335. }
  6336. if (ifsfirst.next)
  6337. ifsfree();
  6338. *exparg.lastp = NULL;
  6339. if (exparg.list) {
  6340. *arglist->lastp = exparg.list;
  6341. arglist->lastp = exparg.lastp;
  6342. }
  6343. }
  6344. /*
  6345. * Expand shell variables and backquotes inside a here document.
  6346. */
  6347. static void
  6348. expandhere(union node *arg, int fd)
  6349. {
  6350. herefd = fd;
  6351. expandarg(arg, (struct arglist *)NULL, 0);
  6352. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6353. }
  6354. /*
  6355. * Returns true if the pattern matches the string.
  6356. */
  6357. static int
  6358. patmatch(char *pattern, const char *string)
  6359. {
  6360. return pmatch(preglob(pattern, 0, 0), string);
  6361. }
  6362. /*
  6363. * See if a pattern matches in a case statement.
  6364. */
  6365. static int
  6366. casematch(union node *pattern, char *val)
  6367. {
  6368. struct stackmark smark;
  6369. int result;
  6370. setstackmark(&smark);
  6371. argbackq = pattern->narg.backquote;
  6372. STARTSTACKSTR(expdest);
  6373. ifslastp = NULL;
  6374. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6375. /* var_str_list: */ NULL);
  6376. STACKSTRNUL(expdest);
  6377. result = patmatch(stackblock(), val);
  6378. popstackmark(&smark);
  6379. return result;
  6380. }
  6381. /* ============ find_command */
  6382. struct builtincmd {
  6383. const char *name;
  6384. int (*builtin)(int, char **) FAST_FUNC;
  6385. /* unsigned flags; */
  6386. };
  6387. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6388. /* "regular" builtins always take precedence over commands,
  6389. * regardless of PATH=....%builtin... position */
  6390. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6391. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6392. struct cmdentry {
  6393. smallint cmdtype; /* CMDxxx */
  6394. union param {
  6395. int index;
  6396. /* index >= 0 for commands without path (slashes) */
  6397. /* (TODO: what exactly does the value mean? PATH position?) */
  6398. /* index == -1 for commands with slashes */
  6399. /* index == (-2 - applet_no) for NOFORK applets */
  6400. const struct builtincmd *cmd;
  6401. struct funcnode *func;
  6402. } u;
  6403. };
  6404. /* values of cmdtype */
  6405. #define CMDUNKNOWN -1 /* no entry in table for command */
  6406. #define CMDNORMAL 0 /* command is an executable program */
  6407. #define CMDFUNCTION 1 /* command is a shell function */
  6408. #define CMDBUILTIN 2 /* command is a shell builtin */
  6409. /* action to find_command() */
  6410. #define DO_ERR 0x01 /* prints errors */
  6411. #define DO_ABS 0x02 /* checks absolute paths */
  6412. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6413. #define DO_ALTPATH 0x08 /* using alternate path */
  6414. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6415. static void find_command(char *, struct cmdentry *, int, const char *);
  6416. /* ============ Hashing commands */
  6417. /*
  6418. * When commands are first encountered, they are entered in a hash table.
  6419. * This ensures that a full path search will not have to be done for them
  6420. * on each invocation.
  6421. *
  6422. * We should investigate converting to a linear search, even though that
  6423. * would make the command name "hash" a misnomer.
  6424. */
  6425. struct tblentry {
  6426. struct tblentry *next; /* next entry in hash chain */
  6427. union param param; /* definition of builtin function */
  6428. smallint cmdtype; /* CMDxxx */
  6429. char rehash; /* if set, cd done since entry created */
  6430. char cmdname[1]; /* name of command */
  6431. };
  6432. static struct tblentry **cmdtable;
  6433. #define INIT_G_cmdtable() do { \
  6434. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6435. } while (0)
  6436. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6437. static void
  6438. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6439. {
  6440. int repeated = 0;
  6441. #if ENABLE_FEATURE_SH_STANDALONE
  6442. if (applet_no >= 0) {
  6443. if (APPLET_IS_NOEXEC(applet_no)) {
  6444. while (*envp)
  6445. putenv(*envp++);
  6446. run_applet_no_and_exit(applet_no, argv);
  6447. }
  6448. /* re-exec ourselves with the new arguments */
  6449. execve(bb_busybox_exec_path, argv, envp);
  6450. /* If they called chroot or otherwise made the binary no longer
  6451. * executable, fall through */
  6452. }
  6453. #endif
  6454. repeat:
  6455. #ifdef SYSV
  6456. do {
  6457. execve(cmd, argv, envp);
  6458. } while (errno == EINTR);
  6459. #else
  6460. execve(cmd, argv, envp);
  6461. #endif
  6462. if (repeated) {
  6463. free(argv);
  6464. return;
  6465. }
  6466. if (errno == ENOEXEC) {
  6467. char **ap;
  6468. char **new;
  6469. for (ap = argv; *ap; ap++)
  6470. continue;
  6471. ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
  6472. ap[1] = cmd;
  6473. ap[0] = cmd = (char *)DEFAULT_SHELL;
  6474. ap += 2;
  6475. argv++;
  6476. while ((*ap++ = *argv++) != NULL)
  6477. continue;
  6478. argv = new;
  6479. repeated++;
  6480. goto repeat;
  6481. }
  6482. }
  6483. /*
  6484. * Exec a program. Never returns. If you change this routine, you may
  6485. * have to change the find_command routine as well.
  6486. */
  6487. static void shellexec(char **, const char *, int) NORETURN;
  6488. static void
  6489. shellexec(char **argv, const char *path, int idx)
  6490. {
  6491. char *cmdname;
  6492. int e;
  6493. char **envp;
  6494. int exerrno;
  6495. #if ENABLE_FEATURE_SH_STANDALONE
  6496. int applet_no = -1;
  6497. #endif
  6498. clearredir(/*drop:*/ 1);
  6499. envp = listvars(VEXPORT, VUNSET, 0);
  6500. if (strchr(argv[0], '/') != NULL
  6501. #if ENABLE_FEATURE_SH_STANDALONE
  6502. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6503. #endif
  6504. ) {
  6505. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6506. e = errno;
  6507. } else {
  6508. e = ENOENT;
  6509. while ((cmdname = path_advance(&path, argv[0])) != NULL) {
  6510. if (--idx < 0 && pathopt == NULL) {
  6511. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6512. if (errno != ENOENT && errno != ENOTDIR)
  6513. e = errno;
  6514. }
  6515. stunalloc(cmdname);
  6516. }
  6517. }
  6518. /* Map to POSIX errors */
  6519. switch (e) {
  6520. case EACCES:
  6521. exerrno = 126;
  6522. break;
  6523. case ENOENT:
  6524. exerrno = 127;
  6525. break;
  6526. default:
  6527. exerrno = 2;
  6528. break;
  6529. }
  6530. exitstatus = exerrno;
  6531. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  6532. argv[0], e, suppressint));
  6533. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6534. /* NOTREACHED */
  6535. }
  6536. static void
  6537. printentry(struct tblentry *cmdp)
  6538. {
  6539. int idx;
  6540. const char *path;
  6541. char *name;
  6542. idx = cmdp->param.index;
  6543. path = pathval();
  6544. do {
  6545. name = path_advance(&path, cmdp->cmdname);
  6546. stunalloc(name);
  6547. } while (--idx >= 0);
  6548. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6549. }
  6550. /*
  6551. * Clear out command entries. The argument specifies the first entry in
  6552. * PATH which has changed.
  6553. */
  6554. static void
  6555. clearcmdentry(int firstchange)
  6556. {
  6557. struct tblentry **tblp;
  6558. struct tblentry **pp;
  6559. struct tblentry *cmdp;
  6560. INT_OFF;
  6561. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6562. pp = tblp;
  6563. while ((cmdp = *pp) != NULL) {
  6564. if ((cmdp->cmdtype == CMDNORMAL &&
  6565. cmdp->param.index >= firstchange)
  6566. || (cmdp->cmdtype == CMDBUILTIN &&
  6567. builtinloc >= firstchange)
  6568. ) {
  6569. *pp = cmdp->next;
  6570. free(cmdp);
  6571. } else {
  6572. pp = &cmdp->next;
  6573. }
  6574. }
  6575. }
  6576. INT_ON;
  6577. }
  6578. /*
  6579. * Locate a command in the command hash table. If "add" is nonzero,
  6580. * add the command to the table if it is not already present. The
  6581. * variable "lastcmdentry" is set to point to the address of the link
  6582. * pointing to the entry, so that delete_cmd_entry can delete the
  6583. * entry.
  6584. *
  6585. * Interrupts must be off if called with add != 0.
  6586. */
  6587. static struct tblentry **lastcmdentry;
  6588. static struct tblentry *
  6589. cmdlookup(const char *name, int add)
  6590. {
  6591. unsigned int hashval;
  6592. const char *p;
  6593. struct tblentry *cmdp;
  6594. struct tblentry **pp;
  6595. p = name;
  6596. hashval = (unsigned char)*p << 4;
  6597. while (*p)
  6598. hashval += (unsigned char)*p++;
  6599. hashval &= 0x7FFF;
  6600. pp = &cmdtable[hashval % CMDTABLESIZE];
  6601. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6602. if (strcmp(cmdp->cmdname, name) == 0)
  6603. break;
  6604. pp = &cmdp->next;
  6605. }
  6606. if (add && cmdp == NULL) {
  6607. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6608. + strlen(name)
  6609. /* + 1 - already done because
  6610. * tblentry::cmdname is char[1] */);
  6611. /*cmdp->next = NULL; - ckzalloc did it */
  6612. cmdp->cmdtype = CMDUNKNOWN;
  6613. strcpy(cmdp->cmdname, name);
  6614. }
  6615. lastcmdentry = pp;
  6616. return cmdp;
  6617. }
  6618. /*
  6619. * Delete the command entry returned on the last lookup.
  6620. */
  6621. static void
  6622. delete_cmd_entry(void)
  6623. {
  6624. struct tblentry *cmdp;
  6625. INT_OFF;
  6626. cmdp = *lastcmdentry;
  6627. *lastcmdentry = cmdp->next;
  6628. if (cmdp->cmdtype == CMDFUNCTION)
  6629. freefunc(cmdp->param.func);
  6630. free(cmdp);
  6631. INT_ON;
  6632. }
  6633. /*
  6634. * Add a new command entry, replacing any existing command entry for
  6635. * the same name - except special builtins.
  6636. */
  6637. static void
  6638. addcmdentry(char *name, struct cmdentry *entry)
  6639. {
  6640. struct tblentry *cmdp;
  6641. cmdp = cmdlookup(name, 1);
  6642. if (cmdp->cmdtype == CMDFUNCTION) {
  6643. freefunc(cmdp->param.func);
  6644. }
  6645. cmdp->cmdtype = entry->cmdtype;
  6646. cmdp->param = entry->u;
  6647. cmdp->rehash = 0;
  6648. }
  6649. static int FAST_FUNC
  6650. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6651. {
  6652. struct tblentry **pp;
  6653. struct tblentry *cmdp;
  6654. int c;
  6655. struct cmdentry entry;
  6656. char *name;
  6657. if (nextopt("r") != '\0') {
  6658. clearcmdentry(0);
  6659. return 0;
  6660. }
  6661. if (*argptr == NULL) {
  6662. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6663. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6664. if (cmdp->cmdtype == CMDNORMAL)
  6665. printentry(cmdp);
  6666. }
  6667. }
  6668. return 0;
  6669. }
  6670. c = 0;
  6671. while ((name = *argptr) != NULL) {
  6672. cmdp = cmdlookup(name, 0);
  6673. if (cmdp != NULL
  6674. && (cmdp->cmdtype == CMDNORMAL
  6675. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6676. ) {
  6677. delete_cmd_entry();
  6678. }
  6679. find_command(name, &entry, DO_ERR, pathval());
  6680. if (entry.cmdtype == CMDUNKNOWN)
  6681. c = 1;
  6682. argptr++;
  6683. }
  6684. return c;
  6685. }
  6686. /*
  6687. * Called when a cd is done. Marks all commands so the next time they
  6688. * are executed they will be rehashed.
  6689. */
  6690. static void
  6691. hashcd(void)
  6692. {
  6693. struct tblentry **pp;
  6694. struct tblentry *cmdp;
  6695. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6696. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6697. if (cmdp->cmdtype == CMDNORMAL
  6698. || (cmdp->cmdtype == CMDBUILTIN
  6699. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  6700. && builtinloc > 0)
  6701. ) {
  6702. cmdp->rehash = 1;
  6703. }
  6704. }
  6705. }
  6706. }
  6707. /*
  6708. * Fix command hash table when PATH changed.
  6709. * Called before PATH is changed. The argument is the new value of PATH;
  6710. * pathval() still returns the old value at this point.
  6711. * Called with interrupts off.
  6712. */
  6713. static void FAST_FUNC
  6714. changepath(const char *new)
  6715. {
  6716. const char *old;
  6717. int firstchange;
  6718. int idx;
  6719. int idx_bltin;
  6720. old = pathval();
  6721. firstchange = 9999; /* assume no change */
  6722. idx = 0;
  6723. idx_bltin = -1;
  6724. for (;;) {
  6725. if (*old != *new) {
  6726. firstchange = idx;
  6727. if ((*old == '\0' && *new == ':')
  6728. || (*old == ':' && *new == '\0'))
  6729. firstchange++;
  6730. old = new; /* ignore subsequent differences */
  6731. }
  6732. if (*new == '\0')
  6733. break;
  6734. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6735. idx_bltin = idx;
  6736. if (*new == ':')
  6737. idx++;
  6738. new++, old++;
  6739. }
  6740. if (builtinloc < 0 && idx_bltin >= 0)
  6741. builtinloc = idx_bltin; /* zap builtins */
  6742. if (builtinloc >= 0 && idx_bltin < 0)
  6743. firstchange = 0;
  6744. clearcmdentry(firstchange);
  6745. builtinloc = idx_bltin;
  6746. }
  6747. #define TEOF 0
  6748. #define TNL 1
  6749. #define TREDIR 2
  6750. #define TWORD 3
  6751. #define TSEMI 4
  6752. #define TBACKGND 5
  6753. #define TAND 6
  6754. #define TOR 7
  6755. #define TPIPE 8
  6756. #define TLP 9
  6757. #define TRP 10
  6758. #define TENDCASE 11
  6759. #define TENDBQUOTE 12
  6760. #define TNOT 13
  6761. #define TCASE 14
  6762. #define TDO 15
  6763. #define TDONE 16
  6764. #define TELIF 17
  6765. #define TELSE 18
  6766. #define TESAC 19
  6767. #define TFI 20
  6768. #define TFOR 21
  6769. #define TIF 22
  6770. #define TIN 23
  6771. #define TTHEN 24
  6772. #define TUNTIL 25
  6773. #define TWHILE 26
  6774. #define TBEGIN 27
  6775. #define TEND 28
  6776. typedef smallint token_id_t;
  6777. /* first char is indicating which tokens mark the end of a list */
  6778. static const char *const tokname_array[] = {
  6779. "\1end of file",
  6780. "\0newline",
  6781. "\0redirection",
  6782. "\0word",
  6783. "\0;",
  6784. "\0&",
  6785. "\0&&",
  6786. "\0||",
  6787. "\0|",
  6788. "\0(",
  6789. "\1)",
  6790. "\1;;",
  6791. "\1`",
  6792. #define KWDOFFSET 13
  6793. /* the following are keywords */
  6794. "\0!",
  6795. "\0case",
  6796. "\1do",
  6797. "\1done",
  6798. "\1elif",
  6799. "\1else",
  6800. "\1esac",
  6801. "\1fi",
  6802. "\0for",
  6803. "\0if",
  6804. "\0in",
  6805. "\1then",
  6806. "\0until",
  6807. "\0while",
  6808. "\0{",
  6809. "\1}",
  6810. };
  6811. static const char *
  6812. tokname(int tok)
  6813. {
  6814. static char buf[16];
  6815. //try this:
  6816. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6817. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6818. //return buf;
  6819. if (tok >= TSEMI)
  6820. buf[0] = '"';
  6821. sprintf(buf + (tok >= TSEMI), "%s%c",
  6822. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6823. return buf;
  6824. }
  6825. /* Wrapper around strcmp for qsort/bsearch/... */
  6826. static int
  6827. pstrcmp(const void *a, const void *b)
  6828. {
  6829. return strcmp((char*) a, (*(char**) b) + 1);
  6830. }
  6831. static const char *const *
  6832. findkwd(const char *s)
  6833. {
  6834. return bsearch(s, tokname_array + KWDOFFSET,
  6835. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6836. sizeof(tokname_array[0]), pstrcmp);
  6837. }
  6838. /*
  6839. * Locate and print what a word is...
  6840. */
  6841. static int
  6842. describe_command(char *command, int describe_command_verbose)
  6843. {
  6844. struct cmdentry entry;
  6845. struct tblentry *cmdp;
  6846. #if ENABLE_ASH_ALIAS
  6847. const struct alias *ap;
  6848. #endif
  6849. const char *path = pathval();
  6850. if (describe_command_verbose) {
  6851. out1str(command);
  6852. }
  6853. /* First look at the keywords */
  6854. if (findkwd(command)) {
  6855. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6856. goto out;
  6857. }
  6858. #if ENABLE_ASH_ALIAS
  6859. /* Then look at the aliases */
  6860. ap = lookupalias(command, 0);
  6861. if (ap != NULL) {
  6862. if (!describe_command_verbose) {
  6863. out1str("alias ");
  6864. printalias(ap);
  6865. return 0;
  6866. }
  6867. out1fmt(" is an alias for %s", ap->val);
  6868. goto out;
  6869. }
  6870. #endif
  6871. /* Then check if it is a tracked alias */
  6872. cmdp = cmdlookup(command, 0);
  6873. if (cmdp != NULL) {
  6874. entry.cmdtype = cmdp->cmdtype;
  6875. entry.u = cmdp->param;
  6876. } else {
  6877. /* Finally use brute force */
  6878. find_command(command, &entry, DO_ABS, path);
  6879. }
  6880. switch (entry.cmdtype) {
  6881. case CMDNORMAL: {
  6882. int j = entry.u.index;
  6883. char *p;
  6884. if (j < 0) {
  6885. p = command;
  6886. } else {
  6887. do {
  6888. p = path_advance(&path, command);
  6889. stunalloc(p);
  6890. } while (--j >= 0);
  6891. }
  6892. if (describe_command_verbose) {
  6893. out1fmt(" is%s %s",
  6894. (cmdp ? " a tracked alias for" : nullstr), p
  6895. );
  6896. } else {
  6897. out1str(p);
  6898. }
  6899. break;
  6900. }
  6901. case CMDFUNCTION:
  6902. if (describe_command_verbose) {
  6903. out1str(" is a shell function");
  6904. } else {
  6905. out1str(command);
  6906. }
  6907. break;
  6908. case CMDBUILTIN:
  6909. if (describe_command_verbose) {
  6910. out1fmt(" is a %sshell builtin",
  6911. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  6912. "special " : nullstr
  6913. );
  6914. } else {
  6915. out1str(command);
  6916. }
  6917. break;
  6918. default:
  6919. if (describe_command_verbose) {
  6920. out1str(": not found\n");
  6921. }
  6922. return 127;
  6923. }
  6924. out:
  6925. outstr("\n", stdout);
  6926. return 0;
  6927. }
  6928. static int FAST_FUNC
  6929. typecmd(int argc UNUSED_PARAM, char **argv)
  6930. {
  6931. int i = 1;
  6932. int err = 0;
  6933. int verbose = 1;
  6934. /* type -p ... ? (we don't bother checking for 'p') */
  6935. if (argv[1] && argv[1][0] == '-') {
  6936. i++;
  6937. verbose = 0;
  6938. }
  6939. while (argv[i]) {
  6940. err |= describe_command(argv[i++], verbose);
  6941. }
  6942. return err;
  6943. }
  6944. #if ENABLE_ASH_CMDCMD
  6945. static int FAST_FUNC
  6946. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6947. {
  6948. int c;
  6949. enum {
  6950. VERIFY_BRIEF = 1,
  6951. VERIFY_VERBOSE = 2,
  6952. } verify = 0;
  6953. while ((c = nextopt("pvV")) != '\0')
  6954. if (c == 'V')
  6955. verify |= VERIFY_VERBOSE;
  6956. else if (c == 'v')
  6957. verify |= VERIFY_BRIEF;
  6958. #if DEBUG
  6959. else if (c != 'p')
  6960. abort();
  6961. #endif
  6962. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  6963. if (verify && (*argptr != NULL)) {
  6964. return describe_command(*argptr, verify - VERIFY_BRIEF);
  6965. }
  6966. return 0;
  6967. }
  6968. #endif
  6969. /* ============ eval.c */
  6970. static int funcblocksize; /* size of structures in function */
  6971. static int funcstringsize; /* size of strings in node */
  6972. static void *funcblock; /* block to allocate function from */
  6973. static char *funcstring; /* block to allocate strings from */
  6974. /* flags in argument to evaltree */
  6975. #define EV_EXIT 01 /* exit after evaluating tree */
  6976. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  6977. #define EV_BACKCMD 04 /* command executing within back quotes */
  6978. static const short nodesize[N_NUMBER] = {
  6979. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  6980. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  6981. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  6982. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  6983. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  6984. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6985. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6986. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6987. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  6988. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6989. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  6990. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  6991. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  6992. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  6993. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  6994. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  6995. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  6996. #if ENABLE_ASH_BASH_COMPAT
  6997. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  6998. #endif
  6999. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7000. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7001. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7002. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7003. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7004. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7005. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7006. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7007. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7008. };
  7009. static void calcsize(union node *n);
  7010. static void
  7011. sizenodelist(struct nodelist *lp)
  7012. {
  7013. while (lp) {
  7014. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7015. calcsize(lp->n);
  7016. lp = lp->next;
  7017. }
  7018. }
  7019. static void
  7020. calcsize(union node *n)
  7021. {
  7022. if (n == NULL)
  7023. return;
  7024. funcblocksize += nodesize[n->type];
  7025. switch (n->type) {
  7026. case NCMD:
  7027. calcsize(n->ncmd.redirect);
  7028. calcsize(n->ncmd.args);
  7029. calcsize(n->ncmd.assign);
  7030. break;
  7031. case NPIPE:
  7032. sizenodelist(n->npipe.cmdlist);
  7033. break;
  7034. case NREDIR:
  7035. case NBACKGND:
  7036. case NSUBSHELL:
  7037. calcsize(n->nredir.redirect);
  7038. calcsize(n->nredir.n);
  7039. break;
  7040. case NAND:
  7041. case NOR:
  7042. case NSEMI:
  7043. case NWHILE:
  7044. case NUNTIL:
  7045. calcsize(n->nbinary.ch2);
  7046. calcsize(n->nbinary.ch1);
  7047. break;
  7048. case NIF:
  7049. calcsize(n->nif.elsepart);
  7050. calcsize(n->nif.ifpart);
  7051. calcsize(n->nif.test);
  7052. break;
  7053. case NFOR:
  7054. funcstringsize += strlen(n->nfor.var) + 1;
  7055. calcsize(n->nfor.body);
  7056. calcsize(n->nfor.args);
  7057. break;
  7058. case NCASE:
  7059. calcsize(n->ncase.cases);
  7060. calcsize(n->ncase.expr);
  7061. break;
  7062. case NCLIST:
  7063. calcsize(n->nclist.body);
  7064. calcsize(n->nclist.pattern);
  7065. calcsize(n->nclist.next);
  7066. break;
  7067. case NDEFUN:
  7068. case NARG:
  7069. sizenodelist(n->narg.backquote);
  7070. funcstringsize += strlen(n->narg.text) + 1;
  7071. calcsize(n->narg.next);
  7072. break;
  7073. case NTO:
  7074. #if ENABLE_ASH_BASH_COMPAT
  7075. case NTO2:
  7076. #endif
  7077. case NCLOBBER:
  7078. case NFROM:
  7079. case NFROMTO:
  7080. case NAPPEND:
  7081. calcsize(n->nfile.fname);
  7082. calcsize(n->nfile.next);
  7083. break;
  7084. case NTOFD:
  7085. case NFROMFD:
  7086. calcsize(n->ndup.vname);
  7087. calcsize(n->ndup.next);
  7088. break;
  7089. case NHERE:
  7090. case NXHERE:
  7091. calcsize(n->nhere.doc);
  7092. calcsize(n->nhere.next);
  7093. break;
  7094. case NNOT:
  7095. calcsize(n->nnot.com);
  7096. break;
  7097. };
  7098. }
  7099. static char *
  7100. nodeckstrdup(char *s)
  7101. {
  7102. char *rtn = funcstring;
  7103. strcpy(funcstring, s);
  7104. funcstring += strlen(s) + 1;
  7105. return rtn;
  7106. }
  7107. static union node *copynode(union node *);
  7108. static struct nodelist *
  7109. copynodelist(struct nodelist *lp)
  7110. {
  7111. struct nodelist *start;
  7112. struct nodelist **lpp;
  7113. lpp = &start;
  7114. while (lp) {
  7115. *lpp = funcblock;
  7116. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7117. (*lpp)->n = copynode(lp->n);
  7118. lp = lp->next;
  7119. lpp = &(*lpp)->next;
  7120. }
  7121. *lpp = NULL;
  7122. return start;
  7123. }
  7124. static union node *
  7125. copynode(union node *n)
  7126. {
  7127. union node *new;
  7128. if (n == NULL)
  7129. return NULL;
  7130. new = funcblock;
  7131. funcblock = (char *) funcblock + nodesize[n->type];
  7132. switch (n->type) {
  7133. case NCMD:
  7134. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7135. new->ncmd.args = copynode(n->ncmd.args);
  7136. new->ncmd.assign = copynode(n->ncmd.assign);
  7137. break;
  7138. case NPIPE:
  7139. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7140. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7141. break;
  7142. case NREDIR:
  7143. case NBACKGND:
  7144. case NSUBSHELL:
  7145. new->nredir.redirect = copynode(n->nredir.redirect);
  7146. new->nredir.n = copynode(n->nredir.n);
  7147. break;
  7148. case NAND:
  7149. case NOR:
  7150. case NSEMI:
  7151. case NWHILE:
  7152. case NUNTIL:
  7153. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7154. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7155. break;
  7156. case NIF:
  7157. new->nif.elsepart = copynode(n->nif.elsepart);
  7158. new->nif.ifpart = copynode(n->nif.ifpart);
  7159. new->nif.test = copynode(n->nif.test);
  7160. break;
  7161. case NFOR:
  7162. new->nfor.var = nodeckstrdup(n->nfor.var);
  7163. new->nfor.body = copynode(n->nfor.body);
  7164. new->nfor.args = copynode(n->nfor.args);
  7165. break;
  7166. case NCASE:
  7167. new->ncase.cases = copynode(n->ncase.cases);
  7168. new->ncase.expr = copynode(n->ncase.expr);
  7169. break;
  7170. case NCLIST:
  7171. new->nclist.body = copynode(n->nclist.body);
  7172. new->nclist.pattern = copynode(n->nclist.pattern);
  7173. new->nclist.next = copynode(n->nclist.next);
  7174. break;
  7175. case NDEFUN:
  7176. case NARG:
  7177. new->narg.backquote = copynodelist(n->narg.backquote);
  7178. new->narg.text = nodeckstrdup(n->narg.text);
  7179. new->narg.next = copynode(n->narg.next);
  7180. break;
  7181. case NTO:
  7182. #if ENABLE_ASH_BASH_COMPAT
  7183. case NTO2:
  7184. #endif
  7185. case NCLOBBER:
  7186. case NFROM:
  7187. case NFROMTO:
  7188. case NAPPEND:
  7189. new->nfile.fname = copynode(n->nfile.fname);
  7190. new->nfile.fd = n->nfile.fd;
  7191. new->nfile.next = copynode(n->nfile.next);
  7192. break;
  7193. case NTOFD:
  7194. case NFROMFD:
  7195. new->ndup.vname = copynode(n->ndup.vname);
  7196. new->ndup.dupfd = n->ndup.dupfd;
  7197. new->ndup.fd = n->ndup.fd;
  7198. new->ndup.next = copynode(n->ndup.next);
  7199. break;
  7200. case NHERE:
  7201. case NXHERE:
  7202. new->nhere.doc = copynode(n->nhere.doc);
  7203. new->nhere.fd = n->nhere.fd;
  7204. new->nhere.next = copynode(n->nhere.next);
  7205. break;
  7206. case NNOT:
  7207. new->nnot.com = copynode(n->nnot.com);
  7208. break;
  7209. };
  7210. new->type = n->type;
  7211. return new;
  7212. }
  7213. /*
  7214. * Make a copy of a parse tree.
  7215. */
  7216. static struct funcnode *
  7217. copyfunc(union node *n)
  7218. {
  7219. struct funcnode *f;
  7220. size_t blocksize;
  7221. funcblocksize = offsetof(struct funcnode, n);
  7222. funcstringsize = 0;
  7223. calcsize(n);
  7224. blocksize = funcblocksize;
  7225. f = ckmalloc(blocksize + funcstringsize);
  7226. funcblock = (char *) f + offsetof(struct funcnode, n);
  7227. funcstring = (char *) f + blocksize;
  7228. copynode(n);
  7229. f->count = 0;
  7230. return f;
  7231. }
  7232. /*
  7233. * Define a shell function.
  7234. */
  7235. static void
  7236. defun(char *name, union node *func)
  7237. {
  7238. struct cmdentry entry;
  7239. INT_OFF;
  7240. entry.cmdtype = CMDFUNCTION;
  7241. entry.u.func = copyfunc(func);
  7242. addcmdentry(name, &entry);
  7243. INT_ON;
  7244. }
  7245. /* Reasons for skipping commands (see comment on breakcmd routine) */
  7246. #define SKIPBREAK (1 << 0)
  7247. #define SKIPCONT (1 << 1)
  7248. #define SKIPFUNC (1 << 2)
  7249. #define SKIPFILE (1 << 3)
  7250. #define SKIPEVAL (1 << 4)
  7251. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  7252. static int skipcount; /* number of levels to skip */
  7253. static int funcnest; /* depth of function calls */
  7254. static int loopnest; /* current loop nesting level */
  7255. /* Forward decl way out to parsing code - dotrap needs it */
  7256. static int evalstring(char *s, int mask);
  7257. /* Called to execute a trap.
  7258. * Single callsite - at the end of evaltree().
  7259. * If we return non-zero, exaltree raises EXEXIT exception.
  7260. *
  7261. * Perhaps we should avoid entering new trap handlers
  7262. * while we are executing a trap handler. [is it a TODO?]
  7263. */
  7264. static int
  7265. dotrap(void)
  7266. {
  7267. uint8_t *g;
  7268. int sig;
  7269. uint8_t savestatus;
  7270. savestatus = exitstatus;
  7271. pendingsig = 0;
  7272. xbarrier();
  7273. TRACE(("dotrap entered\n"));
  7274. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  7275. int want_exexit;
  7276. char *t;
  7277. if (*g == 0)
  7278. continue;
  7279. t = trap[sig];
  7280. /* non-trapped SIGINT is handled separately by raise_interrupt,
  7281. * don't upset it by resetting gotsig[SIGINT-1] */
  7282. if (sig == SIGINT && !t)
  7283. continue;
  7284. TRACE(("sig %d is active, will run handler '%s'\n", sig, t));
  7285. *g = 0;
  7286. if (!t)
  7287. continue;
  7288. want_exexit = evalstring(t, SKIPEVAL);
  7289. exitstatus = savestatus;
  7290. if (want_exexit) {
  7291. TRACE(("dotrap returns %d\n", want_exexit));
  7292. return want_exexit;
  7293. }
  7294. }
  7295. TRACE(("dotrap returns 0\n"));
  7296. return 0;
  7297. }
  7298. /* forward declarations - evaluation is fairly recursive business... */
  7299. static void evalloop(union node *, int);
  7300. static void evalfor(union node *, int);
  7301. static void evalcase(union node *, int);
  7302. static void evalsubshell(union node *, int);
  7303. static void expredir(union node *);
  7304. static void evalpipe(union node *, int);
  7305. static void evalcommand(union node *, int);
  7306. static int evalbltin(const struct builtincmd *, int, char **);
  7307. static void prehash(union node *);
  7308. /*
  7309. * Evaluate a parse tree. The value is left in the global variable
  7310. * exitstatus.
  7311. */
  7312. static void
  7313. evaltree(union node *n, int flags)
  7314. {
  7315. struct jmploc *volatile savehandler = exception_handler;
  7316. struct jmploc jmploc;
  7317. int checkexit = 0;
  7318. void (*evalfn)(union node *, int);
  7319. int status;
  7320. int int_level;
  7321. SAVE_INT(int_level);
  7322. if (n == NULL) {
  7323. TRACE(("evaltree(NULL) called\n"));
  7324. goto out1;
  7325. }
  7326. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  7327. exception_handler = &jmploc;
  7328. {
  7329. int err = setjmp(jmploc.loc);
  7330. if (err) {
  7331. /* if it was a signal, check for trap handlers */
  7332. if (exception_type == EXSIG) {
  7333. TRACE(("exception %d (EXSIG) in evaltree, err=%d\n",
  7334. exception_type, err));
  7335. goto out;
  7336. }
  7337. /* continue on the way out */
  7338. TRACE(("exception %d in evaltree, propagating err=%d\n",
  7339. exception_type, err));
  7340. exception_handler = savehandler;
  7341. longjmp(exception_handler->loc, err);
  7342. }
  7343. }
  7344. switch (n->type) {
  7345. default:
  7346. #if DEBUG
  7347. out1fmt("Node type = %d\n", n->type);
  7348. fflush(stdout);
  7349. break;
  7350. #endif
  7351. case NNOT:
  7352. evaltree(n->nnot.com, EV_TESTED);
  7353. status = !exitstatus;
  7354. goto setstatus;
  7355. case NREDIR:
  7356. expredir(n->nredir.redirect);
  7357. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7358. if (!status) {
  7359. evaltree(n->nredir.n, flags & EV_TESTED);
  7360. status = exitstatus;
  7361. }
  7362. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7363. goto setstatus;
  7364. case NCMD:
  7365. evalfn = evalcommand;
  7366. checkexit:
  7367. if (eflag && !(flags & EV_TESTED))
  7368. checkexit = ~0;
  7369. goto calleval;
  7370. case NFOR:
  7371. evalfn = evalfor;
  7372. goto calleval;
  7373. case NWHILE:
  7374. case NUNTIL:
  7375. evalfn = evalloop;
  7376. goto calleval;
  7377. case NSUBSHELL:
  7378. case NBACKGND:
  7379. evalfn = evalsubshell;
  7380. goto calleval;
  7381. case NPIPE:
  7382. evalfn = evalpipe;
  7383. goto checkexit;
  7384. case NCASE:
  7385. evalfn = evalcase;
  7386. goto calleval;
  7387. case NAND:
  7388. case NOR:
  7389. case NSEMI: {
  7390. #if NAND + 1 != NOR
  7391. #error NAND + 1 != NOR
  7392. #endif
  7393. #if NOR + 1 != NSEMI
  7394. #error NOR + 1 != NSEMI
  7395. #endif
  7396. unsigned is_or = n->type - NAND;
  7397. evaltree(
  7398. n->nbinary.ch1,
  7399. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7400. );
  7401. if (!exitstatus == is_or)
  7402. break;
  7403. if (!evalskip) {
  7404. n = n->nbinary.ch2;
  7405. evaln:
  7406. evalfn = evaltree;
  7407. calleval:
  7408. evalfn(n, flags);
  7409. break;
  7410. }
  7411. break;
  7412. }
  7413. case NIF:
  7414. evaltree(n->nif.test, EV_TESTED);
  7415. if (evalskip)
  7416. break;
  7417. if (exitstatus == 0) {
  7418. n = n->nif.ifpart;
  7419. goto evaln;
  7420. }
  7421. if (n->nif.elsepart) {
  7422. n = n->nif.elsepart;
  7423. goto evaln;
  7424. }
  7425. goto success;
  7426. case NDEFUN:
  7427. defun(n->narg.text, n->narg.next);
  7428. success:
  7429. status = 0;
  7430. setstatus:
  7431. exitstatus = status;
  7432. break;
  7433. }
  7434. out:
  7435. exception_handler = savehandler;
  7436. out1:
  7437. if (checkexit & exitstatus)
  7438. evalskip |= SKIPEVAL;
  7439. else if (pendingsig && dotrap())
  7440. goto exexit;
  7441. if (flags & EV_EXIT) {
  7442. exexit:
  7443. raise_exception(EXEXIT);
  7444. }
  7445. RESTORE_INT(int_level);
  7446. TRACE(("leaving evaltree (no interrupts)\n"));
  7447. }
  7448. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7449. static
  7450. #endif
  7451. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7452. static void
  7453. evalloop(union node *n, int flags)
  7454. {
  7455. int status;
  7456. loopnest++;
  7457. status = 0;
  7458. flags &= EV_TESTED;
  7459. for (;;) {
  7460. int i;
  7461. evaltree(n->nbinary.ch1, EV_TESTED);
  7462. if (evalskip) {
  7463. skipping:
  7464. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7465. evalskip = 0;
  7466. continue;
  7467. }
  7468. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7469. evalskip = 0;
  7470. break;
  7471. }
  7472. i = exitstatus;
  7473. if (n->type != NWHILE)
  7474. i = !i;
  7475. if (i != 0)
  7476. break;
  7477. evaltree(n->nbinary.ch2, flags);
  7478. status = exitstatus;
  7479. if (evalskip)
  7480. goto skipping;
  7481. }
  7482. loopnest--;
  7483. exitstatus = status;
  7484. }
  7485. static void
  7486. evalfor(union node *n, int flags)
  7487. {
  7488. struct arglist arglist;
  7489. union node *argp;
  7490. struct strlist *sp;
  7491. struct stackmark smark;
  7492. setstackmark(&smark);
  7493. arglist.list = NULL;
  7494. arglist.lastp = &arglist.list;
  7495. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7496. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7497. /* XXX */
  7498. if (evalskip)
  7499. goto out;
  7500. }
  7501. *arglist.lastp = NULL;
  7502. exitstatus = 0;
  7503. loopnest++;
  7504. flags &= EV_TESTED;
  7505. for (sp = arglist.list; sp; sp = sp->next) {
  7506. setvar(n->nfor.var, sp->text, 0);
  7507. evaltree(n->nfor.body, flags);
  7508. if (evalskip) {
  7509. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7510. evalskip = 0;
  7511. continue;
  7512. }
  7513. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7514. evalskip = 0;
  7515. break;
  7516. }
  7517. }
  7518. loopnest--;
  7519. out:
  7520. popstackmark(&smark);
  7521. }
  7522. static void
  7523. evalcase(union node *n, int flags)
  7524. {
  7525. union node *cp;
  7526. union node *patp;
  7527. struct arglist arglist;
  7528. struct stackmark smark;
  7529. setstackmark(&smark);
  7530. arglist.list = NULL;
  7531. arglist.lastp = &arglist.list;
  7532. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7533. exitstatus = 0;
  7534. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7535. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7536. if (casematch(patp, arglist.list->text)) {
  7537. if (evalskip == 0) {
  7538. evaltree(cp->nclist.body, flags);
  7539. }
  7540. goto out;
  7541. }
  7542. }
  7543. }
  7544. out:
  7545. popstackmark(&smark);
  7546. }
  7547. /*
  7548. * Kick off a subshell to evaluate a tree.
  7549. */
  7550. static void
  7551. evalsubshell(union node *n, int flags)
  7552. {
  7553. struct job *jp;
  7554. int backgnd = (n->type == NBACKGND);
  7555. int status;
  7556. expredir(n->nredir.redirect);
  7557. if (!backgnd && flags & EV_EXIT && !trap[0])
  7558. goto nofork;
  7559. INT_OFF;
  7560. jp = makejob(/*n,*/ 1);
  7561. if (forkshell(jp, n, backgnd) == 0) {
  7562. INT_ON;
  7563. flags |= EV_EXIT;
  7564. if (backgnd)
  7565. flags &=~ EV_TESTED;
  7566. nofork:
  7567. redirect(n->nredir.redirect, 0);
  7568. evaltreenr(n->nredir.n, flags);
  7569. /* never returns */
  7570. }
  7571. status = 0;
  7572. if (!backgnd)
  7573. status = waitforjob(jp);
  7574. exitstatus = status;
  7575. INT_ON;
  7576. }
  7577. /*
  7578. * Compute the names of the files in a redirection list.
  7579. */
  7580. static void fixredir(union node *, const char *, int);
  7581. static void
  7582. expredir(union node *n)
  7583. {
  7584. union node *redir;
  7585. for (redir = n; redir; redir = redir->nfile.next) {
  7586. struct arglist fn;
  7587. fn.list = NULL;
  7588. fn.lastp = &fn.list;
  7589. switch (redir->type) {
  7590. case NFROMTO:
  7591. case NFROM:
  7592. case NTO:
  7593. #if ENABLE_ASH_BASH_COMPAT
  7594. case NTO2:
  7595. #endif
  7596. case NCLOBBER:
  7597. case NAPPEND:
  7598. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7599. #if ENABLE_ASH_BASH_COMPAT
  7600. store_expfname:
  7601. #endif
  7602. redir->nfile.expfname = fn.list->text;
  7603. break;
  7604. case NFROMFD:
  7605. case NTOFD: /* >& */
  7606. if (redir->ndup.vname) {
  7607. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7608. if (fn.list == NULL)
  7609. ash_msg_and_raise_error("redir error");
  7610. #if ENABLE_ASH_BASH_COMPAT
  7611. //FIXME: we used expandarg with different args!
  7612. if (!isdigit_str9(fn.list->text)) {
  7613. /* >&file, not >&fd */
  7614. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  7615. ash_msg_and_raise_error("redir error");
  7616. redir->type = NTO2;
  7617. goto store_expfname;
  7618. }
  7619. #endif
  7620. fixredir(redir, fn.list->text, 1);
  7621. }
  7622. break;
  7623. }
  7624. }
  7625. }
  7626. /*
  7627. * Evaluate a pipeline. All the processes in the pipeline are children
  7628. * of the process creating the pipeline. (This differs from some versions
  7629. * of the shell, which make the last process in a pipeline the parent
  7630. * of all the rest.)
  7631. */
  7632. static void
  7633. evalpipe(union node *n, int flags)
  7634. {
  7635. struct job *jp;
  7636. struct nodelist *lp;
  7637. int pipelen;
  7638. int prevfd;
  7639. int pip[2];
  7640. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7641. pipelen = 0;
  7642. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7643. pipelen++;
  7644. flags |= EV_EXIT;
  7645. INT_OFF;
  7646. jp = makejob(/*n,*/ pipelen);
  7647. prevfd = -1;
  7648. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7649. prehash(lp->n);
  7650. pip[1] = -1;
  7651. if (lp->next) {
  7652. if (pipe(pip) < 0) {
  7653. close(prevfd);
  7654. ash_msg_and_raise_error("pipe call failed");
  7655. }
  7656. }
  7657. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7658. INT_ON;
  7659. if (pip[1] >= 0) {
  7660. close(pip[0]);
  7661. }
  7662. if (prevfd > 0) {
  7663. dup2(prevfd, 0);
  7664. close(prevfd);
  7665. }
  7666. if (pip[1] > 1) {
  7667. dup2(pip[1], 1);
  7668. close(pip[1]);
  7669. }
  7670. evaltreenr(lp->n, flags);
  7671. /* never returns */
  7672. }
  7673. if (prevfd >= 0)
  7674. close(prevfd);
  7675. prevfd = pip[0];
  7676. /* Don't want to trigger debugging */
  7677. if (pip[1] != -1)
  7678. close(pip[1]);
  7679. }
  7680. if (n->npipe.pipe_backgnd == 0) {
  7681. exitstatus = waitforjob(jp);
  7682. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7683. }
  7684. INT_ON;
  7685. }
  7686. /*
  7687. * Controls whether the shell is interactive or not.
  7688. */
  7689. static void
  7690. setinteractive(int on)
  7691. {
  7692. static smallint is_interactive;
  7693. if (++on == is_interactive)
  7694. return;
  7695. is_interactive = on;
  7696. setsignal(SIGINT);
  7697. setsignal(SIGQUIT);
  7698. setsignal(SIGTERM);
  7699. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7700. if (is_interactive > 1) {
  7701. /* Looks like they want an interactive shell */
  7702. static smallint did_banner;
  7703. if (!did_banner) {
  7704. out1fmt(
  7705. "\n\n"
  7706. "%s built-in shell (ash)\n"
  7707. "Enter 'help' for a list of built-in commands."
  7708. "\n\n",
  7709. bb_banner);
  7710. did_banner = 1;
  7711. }
  7712. }
  7713. #endif
  7714. }
  7715. static void
  7716. optschanged(void)
  7717. {
  7718. #if DEBUG
  7719. opentrace();
  7720. #endif
  7721. setinteractive(iflag);
  7722. setjobctl(mflag);
  7723. #if ENABLE_FEATURE_EDITING_VI
  7724. if (viflag)
  7725. line_input_state->flags |= VI_MODE;
  7726. else
  7727. line_input_state->flags &= ~VI_MODE;
  7728. #else
  7729. viflag = 0; /* forcibly keep the option off */
  7730. #endif
  7731. }
  7732. static struct localvar *localvars;
  7733. /*
  7734. * Called after a function returns.
  7735. * Interrupts must be off.
  7736. */
  7737. static void
  7738. poplocalvars(void)
  7739. {
  7740. struct localvar *lvp;
  7741. struct var *vp;
  7742. while ((lvp = localvars) != NULL) {
  7743. localvars = lvp->next;
  7744. vp = lvp->vp;
  7745. TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
  7746. if (vp == NULL) { /* $- saved */
  7747. memcpy(optlist, lvp->text, sizeof(optlist));
  7748. free((char*)lvp->text);
  7749. optschanged();
  7750. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7751. unsetvar(vp->text);
  7752. } else {
  7753. if (vp->func)
  7754. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7755. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7756. free((char*)vp->text);
  7757. vp->flags = lvp->flags;
  7758. vp->text = lvp->text;
  7759. }
  7760. free(lvp);
  7761. }
  7762. }
  7763. static int
  7764. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7765. {
  7766. volatile struct shparam saveparam;
  7767. struct localvar *volatile savelocalvars;
  7768. struct jmploc *volatile savehandler;
  7769. struct jmploc jmploc;
  7770. int e;
  7771. saveparam = shellparam;
  7772. savelocalvars = localvars;
  7773. e = setjmp(jmploc.loc);
  7774. if (e) {
  7775. goto funcdone;
  7776. }
  7777. INT_OFF;
  7778. savehandler = exception_handler;
  7779. exception_handler = &jmploc;
  7780. localvars = NULL;
  7781. shellparam.malloced = 0;
  7782. func->count++;
  7783. funcnest++;
  7784. INT_ON;
  7785. shellparam.nparam = argc - 1;
  7786. shellparam.p = argv + 1;
  7787. #if ENABLE_ASH_GETOPTS
  7788. shellparam.optind = 1;
  7789. shellparam.optoff = -1;
  7790. #endif
  7791. evaltree(&func->n, flags & EV_TESTED);
  7792. funcdone:
  7793. INT_OFF;
  7794. funcnest--;
  7795. freefunc(func);
  7796. poplocalvars();
  7797. localvars = savelocalvars;
  7798. freeparam(&shellparam);
  7799. shellparam = saveparam;
  7800. exception_handler = savehandler;
  7801. INT_ON;
  7802. evalskip &= ~SKIPFUNC;
  7803. return e;
  7804. }
  7805. #if ENABLE_ASH_CMDCMD
  7806. static char **
  7807. parse_command_args(char **argv, const char **path)
  7808. {
  7809. char *cp, c;
  7810. for (;;) {
  7811. cp = *++argv;
  7812. if (!cp)
  7813. return 0;
  7814. if (*cp++ != '-')
  7815. break;
  7816. c = *cp++;
  7817. if (!c)
  7818. break;
  7819. if (c == '-' && !*cp) {
  7820. argv++;
  7821. break;
  7822. }
  7823. do {
  7824. switch (c) {
  7825. case 'p':
  7826. *path = bb_default_path;
  7827. break;
  7828. default:
  7829. /* run 'typecmd' for other options */
  7830. return 0;
  7831. }
  7832. c = *cp++;
  7833. } while (c);
  7834. }
  7835. return argv;
  7836. }
  7837. #endif
  7838. /*
  7839. * Make a variable a local variable. When a variable is made local, it's
  7840. * value and flags are saved in a localvar structure. The saved values
  7841. * will be restored when the shell function returns. We handle the name
  7842. * "-" as a special case.
  7843. */
  7844. static void
  7845. mklocal(char *name)
  7846. {
  7847. struct localvar *lvp;
  7848. struct var **vpp;
  7849. struct var *vp;
  7850. INT_OFF;
  7851. lvp = ckzalloc(sizeof(struct localvar));
  7852. if (LONE_DASH(name)) {
  7853. char *p;
  7854. p = ckmalloc(sizeof(optlist));
  7855. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7856. vp = NULL;
  7857. } else {
  7858. char *eq;
  7859. vpp = hashvar(name);
  7860. vp = *findvar(vpp, name);
  7861. eq = strchr(name, '=');
  7862. if (vp == NULL) {
  7863. if (eq)
  7864. setvareq(name, VSTRFIXED);
  7865. else
  7866. setvar(name, NULL, VSTRFIXED);
  7867. vp = *vpp; /* the new variable */
  7868. lvp->flags = VUNSET;
  7869. } else {
  7870. lvp->text = vp->text;
  7871. lvp->flags = vp->flags;
  7872. vp->flags |= VSTRFIXED|VTEXTFIXED;
  7873. if (eq)
  7874. setvareq(name, 0);
  7875. }
  7876. }
  7877. lvp->vp = vp;
  7878. lvp->next = localvars;
  7879. localvars = lvp;
  7880. INT_ON;
  7881. }
  7882. /*
  7883. * The "local" command.
  7884. */
  7885. static int FAST_FUNC
  7886. localcmd(int argc UNUSED_PARAM, char **argv)
  7887. {
  7888. char *name;
  7889. argv = argptr;
  7890. while ((name = *argv++) != NULL) {
  7891. mklocal(name);
  7892. }
  7893. return 0;
  7894. }
  7895. static int FAST_FUNC
  7896. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7897. {
  7898. return 1;
  7899. }
  7900. static int FAST_FUNC
  7901. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7902. {
  7903. return 0;
  7904. }
  7905. static int FAST_FUNC
  7906. execcmd(int argc UNUSED_PARAM, char **argv)
  7907. {
  7908. if (argv[1]) {
  7909. iflag = 0; /* exit on error */
  7910. mflag = 0;
  7911. optschanged();
  7912. shellexec(argv + 1, pathval(), 0);
  7913. }
  7914. return 0;
  7915. }
  7916. /*
  7917. * The return command.
  7918. */
  7919. static int FAST_FUNC
  7920. returncmd(int argc UNUSED_PARAM, char **argv)
  7921. {
  7922. /*
  7923. * If called outside a function, do what ksh does;
  7924. * skip the rest of the file.
  7925. */
  7926. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  7927. return argv[1] ? number(argv[1]) : exitstatus;
  7928. }
  7929. /* Forward declarations for builtintab[] */
  7930. static int breakcmd(int, char **) FAST_FUNC;
  7931. static int dotcmd(int, char **) FAST_FUNC;
  7932. static int evalcmd(int, char **) FAST_FUNC;
  7933. static int exitcmd(int, char **) FAST_FUNC;
  7934. static int exportcmd(int, char **) FAST_FUNC;
  7935. #if ENABLE_ASH_GETOPTS
  7936. static int getoptscmd(int, char **) FAST_FUNC;
  7937. #endif
  7938. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7939. static int helpcmd(int, char **) FAST_FUNC;
  7940. #endif
  7941. #if ENABLE_SH_MATH_SUPPORT
  7942. static int letcmd(int, char **) FAST_FUNC;
  7943. #endif
  7944. static int readcmd(int, char **) FAST_FUNC;
  7945. static int setcmd(int, char **) FAST_FUNC;
  7946. static int shiftcmd(int, char **) FAST_FUNC;
  7947. static int timescmd(int, char **) FAST_FUNC;
  7948. static int trapcmd(int, char **) FAST_FUNC;
  7949. static int umaskcmd(int, char **) FAST_FUNC;
  7950. static int unsetcmd(int, char **) FAST_FUNC;
  7951. static int ulimitcmd(int, char **) FAST_FUNC;
  7952. #define BUILTIN_NOSPEC "0"
  7953. #define BUILTIN_SPECIAL "1"
  7954. #define BUILTIN_REGULAR "2"
  7955. #define BUILTIN_SPEC_REG "3"
  7956. #define BUILTIN_ASSIGN "4"
  7957. #define BUILTIN_SPEC_ASSG "5"
  7958. #define BUILTIN_REG_ASSG "6"
  7959. #define BUILTIN_SPEC_REG_ASSG "7"
  7960. /* Stubs for calling non-FAST_FUNC's */
  7961. #if ENABLE_ASH_BUILTIN_ECHO
  7962. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  7963. #endif
  7964. #if ENABLE_ASH_BUILTIN_PRINTF
  7965. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  7966. #endif
  7967. #if ENABLE_ASH_BUILTIN_TEST
  7968. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  7969. #endif
  7970. /* Keep these in proper order since it is searched via bsearch() */
  7971. static const struct builtincmd builtintab[] = {
  7972. { BUILTIN_SPEC_REG ".", dotcmd },
  7973. { BUILTIN_SPEC_REG ":", truecmd },
  7974. #if ENABLE_ASH_BUILTIN_TEST
  7975. { BUILTIN_REGULAR "[", testcmd },
  7976. #if ENABLE_ASH_BASH_COMPAT
  7977. { BUILTIN_REGULAR "[[", testcmd },
  7978. #endif
  7979. #endif
  7980. #if ENABLE_ASH_ALIAS
  7981. { BUILTIN_REG_ASSG "alias", aliascmd },
  7982. #endif
  7983. #if JOBS
  7984. { BUILTIN_REGULAR "bg", fg_bgcmd },
  7985. #endif
  7986. { BUILTIN_SPEC_REG "break", breakcmd },
  7987. { BUILTIN_REGULAR "cd", cdcmd },
  7988. { BUILTIN_NOSPEC "chdir", cdcmd },
  7989. #if ENABLE_ASH_CMDCMD
  7990. { BUILTIN_REGULAR "command", commandcmd },
  7991. #endif
  7992. { BUILTIN_SPEC_REG "continue", breakcmd },
  7993. #if ENABLE_ASH_BUILTIN_ECHO
  7994. { BUILTIN_REGULAR "echo", echocmd },
  7995. #endif
  7996. { BUILTIN_SPEC_REG "eval", evalcmd },
  7997. { BUILTIN_SPEC_REG "exec", execcmd },
  7998. { BUILTIN_SPEC_REG "exit", exitcmd },
  7999. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  8000. { BUILTIN_REGULAR "false", falsecmd },
  8001. #if JOBS
  8002. { BUILTIN_REGULAR "fg", fg_bgcmd },
  8003. #endif
  8004. #if ENABLE_ASH_GETOPTS
  8005. { BUILTIN_REGULAR "getopts", getoptscmd },
  8006. #endif
  8007. { BUILTIN_NOSPEC "hash", hashcmd },
  8008. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8009. { BUILTIN_NOSPEC "help", helpcmd },
  8010. #endif
  8011. #if JOBS
  8012. { BUILTIN_REGULAR "jobs", jobscmd },
  8013. { BUILTIN_REGULAR "kill", killcmd },
  8014. #endif
  8015. #if ENABLE_SH_MATH_SUPPORT
  8016. { BUILTIN_NOSPEC "let", letcmd },
  8017. #endif
  8018. { BUILTIN_ASSIGN "local", localcmd },
  8019. #if ENABLE_ASH_BUILTIN_PRINTF
  8020. { BUILTIN_REGULAR "printf", printfcmd },
  8021. #endif
  8022. { BUILTIN_NOSPEC "pwd", pwdcmd },
  8023. { BUILTIN_REGULAR "read", readcmd },
  8024. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8025. { BUILTIN_SPEC_REG "return", returncmd },
  8026. { BUILTIN_SPEC_REG "set", setcmd },
  8027. { BUILTIN_SPEC_REG "shift", shiftcmd },
  8028. { BUILTIN_SPEC_REG "source", dotcmd },
  8029. #if ENABLE_ASH_BUILTIN_TEST
  8030. { BUILTIN_REGULAR "test", testcmd },
  8031. #endif
  8032. { BUILTIN_SPEC_REG "times", timescmd },
  8033. { BUILTIN_SPEC_REG "trap", trapcmd },
  8034. { BUILTIN_REGULAR "true", truecmd },
  8035. { BUILTIN_NOSPEC "type", typecmd },
  8036. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  8037. { BUILTIN_REGULAR "umask", umaskcmd },
  8038. #if ENABLE_ASH_ALIAS
  8039. { BUILTIN_REGULAR "unalias", unaliascmd },
  8040. #endif
  8041. { BUILTIN_SPEC_REG "unset", unsetcmd },
  8042. { BUILTIN_REGULAR "wait", waitcmd },
  8043. };
  8044. /* Should match the above table! */
  8045. #define COMMANDCMD (builtintab + \
  8046. 2 + \
  8047. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8048. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8049. 1 * ENABLE_ASH_ALIAS + \
  8050. 1 * ENABLE_ASH_JOB_CONTROL + \
  8051. 3)
  8052. #define EXECCMD (builtintab + \
  8053. 2 + \
  8054. 1 * ENABLE_ASH_BUILTIN_TEST + \
  8055. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  8056. 1 * ENABLE_ASH_ALIAS + \
  8057. 1 * ENABLE_ASH_JOB_CONTROL + \
  8058. 3 + \
  8059. 1 * ENABLE_ASH_CMDCMD + \
  8060. 1 + \
  8061. ENABLE_ASH_BUILTIN_ECHO + \
  8062. 1)
  8063. /*
  8064. * Search the table of builtin commands.
  8065. */
  8066. static struct builtincmd *
  8067. find_builtin(const char *name)
  8068. {
  8069. struct builtincmd *bp;
  8070. bp = bsearch(
  8071. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8072. pstrcmp
  8073. );
  8074. return bp;
  8075. }
  8076. /*
  8077. * Execute a simple command.
  8078. */
  8079. static int
  8080. isassignment(const char *p)
  8081. {
  8082. const char *q = endofname(p);
  8083. if (p == q)
  8084. return 0;
  8085. return *q == '=';
  8086. }
  8087. static int FAST_FUNC
  8088. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8089. {
  8090. /* Preserve exitstatus of a previous possible redirection
  8091. * as POSIX mandates */
  8092. return back_exitstatus;
  8093. }
  8094. static void
  8095. evalcommand(union node *cmd, int flags)
  8096. {
  8097. static const struct builtincmd null_bltin = {
  8098. "\0\0", bltincmd /* why three NULs? */
  8099. };
  8100. struct stackmark smark;
  8101. union node *argp;
  8102. struct arglist arglist;
  8103. struct arglist varlist;
  8104. char **argv;
  8105. int argc;
  8106. const struct strlist *sp;
  8107. struct cmdentry cmdentry;
  8108. struct job *jp;
  8109. char *lastarg;
  8110. const char *path;
  8111. int spclbltin;
  8112. int status;
  8113. char **nargv;
  8114. struct builtincmd *bcmd;
  8115. smallint cmd_is_exec;
  8116. smallint pseudovarflag = 0;
  8117. /* First expand the arguments. */
  8118. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8119. setstackmark(&smark);
  8120. back_exitstatus = 0;
  8121. cmdentry.cmdtype = CMDBUILTIN;
  8122. cmdentry.u.cmd = &null_bltin;
  8123. varlist.lastp = &varlist.list;
  8124. *varlist.lastp = NULL;
  8125. arglist.lastp = &arglist.list;
  8126. *arglist.lastp = NULL;
  8127. argc = 0;
  8128. if (cmd->ncmd.args) {
  8129. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8130. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8131. }
  8132. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8133. struct strlist **spp;
  8134. spp = arglist.lastp;
  8135. if (pseudovarflag && isassignment(argp->narg.text))
  8136. expandarg(argp, &arglist, EXP_VARTILDE);
  8137. else
  8138. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8139. for (sp = *spp; sp; sp = sp->next)
  8140. argc++;
  8141. }
  8142. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  8143. for (sp = arglist.list; sp; sp = sp->next) {
  8144. TRACE(("evalcommand arg: %s\n", sp->text));
  8145. *nargv++ = sp->text;
  8146. }
  8147. *nargv = NULL;
  8148. lastarg = NULL;
  8149. if (iflag && funcnest == 0 && argc > 0)
  8150. lastarg = nargv[-1];
  8151. preverrout_fd = 2;
  8152. expredir(cmd->ncmd.redirect);
  8153. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8154. path = vpath.text;
  8155. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8156. struct strlist **spp;
  8157. char *p;
  8158. spp = varlist.lastp;
  8159. expandarg(argp, &varlist, EXP_VARTILDE);
  8160. /*
  8161. * Modify the command lookup path, if a PATH= assignment
  8162. * is present
  8163. */
  8164. p = (*spp)->text;
  8165. if (varequal(p, path))
  8166. path = p;
  8167. }
  8168. /* Print the command if xflag is set. */
  8169. if (xflag) {
  8170. int n;
  8171. const char *p = " %s";
  8172. p++;
  8173. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8174. sp = varlist.list;
  8175. for (n = 0; n < 2; n++) {
  8176. while (sp) {
  8177. fdprintf(preverrout_fd, p, sp->text);
  8178. sp = sp->next;
  8179. if (*p == '%') {
  8180. p--;
  8181. }
  8182. }
  8183. sp = arglist.list;
  8184. }
  8185. safe_write(preverrout_fd, "\n", 1);
  8186. }
  8187. cmd_is_exec = 0;
  8188. spclbltin = -1;
  8189. /* Now locate the command. */
  8190. if (argc) {
  8191. const char *oldpath;
  8192. int cmd_flag = DO_ERR;
  8193. path += 5;
  8194. oldpath = path;
  8195. for (;;) {
  8196. find_command(argv[0], &cmdentry, cmd_flag, path);
  8197. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8198. flush_stderr();
  8199. status = 127;
  8200. goto bail;
  8201. }
  8202. /* implement bltin and command here */
  8203. if (cmdentry.cmdtype != CMDBUILTIN)
  8204. break;
  8205. if (spclbltin < 0)
  8206. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8207. if (cmdentry.u.cmd == EXECCMD)
  8208. cmd_is_exec = 1;
  8209. #if ENABLE_ASH_CMDCMD
  8210. if (cmdentry.u.cmd == COMMANDCMD) {
  8211. path = oldpath;
  8212. nargv = parse_command_args(argv, &path);
  8213. if (!nargv)
  8214. break;
  8215. argc -= nargv - argv;
  8216. argv = nargv;
  8217. cmd_flag |= DO_NOFUNC;
  8218. } else
  8219. #endif
  8220. break;
  8221. }
  8222. }
  8223. if (status) {
  8224. /* We have a redirection error. */
  8225. if (spclbltin > 0)
  8226. raise_exception(EXERROR);
  8227. bail:
  8228. exitstatus = status;
  8229. goto out;
  8230. }
  8231. /* Execute the command. */
  8232. switch (cmdentry.cmdtype) {
  8233. default:
  8234. #if ENABLE_FEATURE_SH_NOFORK
  8235. /* Hmmm... shouldn't it happen somewhere in forkshell() instead?
  8236. * Why "fork off a child process if necessary" doesn't apply to NOFORK? */
  8237. {
  8238. /* find_command() encodes applet_no as (-2 - applet_no) */
  8239. int applet_no = (- cmdentry.u.index - 2);
  8240. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8241. listsetvar(varlist.list, VEXPORT|VSTACK);
  8242. /* run <applet>_main() */
  8243. exitstatus = run_nofork_applet(applet_no, argv);
  8244. break;
  8245. }
  8246. }
  8247. #endif
  8248. /* Fork off a child process if necessary. */
  8249. if (!(flags & EV_EXIT) || trap[0]) {
  8250. INT_OFF;
  8251. jp = makejob(/*cmd,*/ 1);
  8252. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8253. exitstatus = waitforjob(jp);
  8254. INT_ON;
  8255. TRACE(("forked child exited with %d\n", exitstatus));
  8256. break;
  8257. }
  8258. FORCE_INT_ON;
  8259. }
  8260. listsetvar(varlist.list, VEXPORT|VSTACK);
  8261. shellexec(argv, path, cmdentry.u.index);
  8262. /* NOTREACHED */
  8263. case CMDBUILTIN:
  8264. cmdenviron = varlist.list;
  8265. if (cmdenviron) {
  8266. struct strlist *list = cmdenviron;
  8267. int i = VNOSET;
  8268. if (spclbltin > 0 || argc == 0) {
  8269. i = 0;
  8270. if (cmd_is_exec && argc > 1)
  8271. i = VEXPORT;
  8272. }
  8273. listsetvar(list, i);
  8274. }
  8275. /* Tight loop with builtins only:
  8276. * "while kill -0 $child; do true; done"
  8277. * will never exit even if $child died, unless we do this
  8278. * to reap the zombie and make kill detect that it's gone: */
  8279. dowait(DOWAIT_NONBLOCK, NULL);
  8280. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8281. int exit_status;
  8282. int i = exception_type;
  8283. if (i == EXEXIT)
  8284. goto raise;
  8285. exit_status = 2;
  8286. if (i == EXINT)
  8287. exit_status = 128 + SIGINT;
  8288. if (i == EXSIG)
  8289. exit_status = 128 + pendingsig;
  8290. exitstatus = exit_status;
  8291. if (i == EXINT || spclbltin > 0) {
  8292. raise:
  8293. longjmp(exception_handler->loc, 1);
  8294. }
  8295. FORCE_INT_ON;
  8296. }
  8297. break;
  8298. case CMDFUNCTION:
  8299. listsetvar(varlist.list, 0);
  8300. /* See above for the rationale */
  8301. dowait(DOWAIT_NONBLOCK, NULL);
  8302. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8303. goto raise;
  8304. break;
  8305. }
  8306. out:
  8307. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8308. if (lastarg) {
  8309. /* dsl: I think this is intended to be used to support
  8310. * '_' in 'vi' command mode during line editing...
  8311. * However I implemented that within libedit itself.
  8312. */
  8313. setvar("_", lastarg, 0);
  8314. }
  8315. popstackmark(&smark);
  8316. }
  8317. static int
  8318. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8319. {
  8320. char *volatile savecmdname;
  8321. struct jmploc *volatile savehandler;
  8322. struct jmploc jmploc;
  8323. int i;
  8324. savecmdname = commandname;
  8325. i = setjmp(jmploc.loc);
  8326. if (i)
  8327. goto cmddone;
  8328. savehandler = exception_handler;
  8329. exception_handler = &jmploc;
  8330. commandname = argv[0];
  8331. argptr = argv + 1;
  8332. optptr = NULL; /* initialize nextopt */
  8333. exitstatus = (*cmd->builtin)(argc, argv);
  8334. flush_stdout_stderr();
  8335. cmddone:
  8336. exitstatus |= ferror(stdout);
  8337. clearerr(stdout);
  8338. commandname = savecmdname;
  8339. // exsig = 0;
  8340. exception_handler = savehandler;
  8341. return i;
  8342. }
  8343. static int
  8344. goodname(const char *p)
  8345. {
  8346. return !*endofname(p);
  8347. }
  8348. /*
  8349. * Search for a command. This is called before we fork so that the
  8350. * location of the command will be available in the parent as well as
  8351. * the child. The check for "goodname" is an overly conservative
  8352. * check that the name will not be subject to expansion.
  8353. */
  8354. static void
  8355. prehash(union node *n)
  8356. {
  8357. struct cmdentry entry;
  8358. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8359. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8360. }
  8361. /* ============ Builtin commands
  8362. *
  8363. * Builtin commands whose functions are closely tied to evaluation
  8364. * are implemented here.
  8365. */
  8366. /*
  8367. * Handle break and continue commands. Break, continue, and return are
  8368. * all handled by setting the evalskip flag. The evaluation routines
  8369. * above all check this flag, and if it is set they start skipping
  8370. * commands rather than executing them. The variable skipcount is
  8371. * the number of loops to break/continue, or the number of function
  8372. * levels to return. (The latter is always 1.) It should probably
  8373. * be an error to break out of more loops than exist, but it isn't
  8374. * in the standard shell so we don't make it one here.
  8375. */
  8376. static int FAST_FUNC
  8377. breakcmd(int argc UNUSED_PARAM, char **argv)
  8378. {
  8379. int n = argv[1] ? number(argv[1]) : 1;
  8380. if (n <= 0)
  8381. ash_msg_and_raise_error(illnum, argv[1]);
  8382. if (n > loopnest)
  8383. n = loopnest;
  8384. if (n > 0) {
  8385. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8386. skipcount = n;
  8387. }
  8388. return 0;
  8389. }
  8390. /* ============ input.c
  8391. *
  8392. * This implements the input routines used by the parser.
  8393. */
  8394. enum {
  8395. INPUT_PUSH_FILE = 1,
  8396. INPUT_NOFILE_OK = 2,
  8397. };
  8398. static smallint checkkwd;
  8399. /* values of checkkwd variable */
  8400. #define CHKALIAS 0x1
  8401. #define CHKKWD 0x2
  8402. #define CHKNL 0x4
  8403. /*
  8404. * Push a string back onto the input at this current parsefile level.
  8405. * We handle aliases this way.
  8406. */
  8407. #if !ENABLE_ASH_ALIAS
  8408. #define pushstring(s, ap) pushstring(s)
  8409. #endif
  8410. static void
  8411. pushstring(char *s, struct alias *ap)
  8412. {
  8413. struct strpush *sp;
  8414. int len;
  8415. len = strlen(s);
  8416. INT_OFF;
  8417. if (g_parsefile->strpush) {
  8418. sp = ckzalloc(sizeof(*sp));
  8419. sp->prev = g_parsefile->strpush;
  8420. } else {
  8421. sp = &(g_parsefile->basestrpush);
  8422. }
  8423. g_parsefile->strpush = sp;
  8424. sp->prev_string = g_parsefile->next_to_pgetc;
  8425. sp->prev_left_in_line = g_parsefile->left_in_line;
  8426. #if ENABLE_ASH_ALIAS
  8427. sp->ap = ap;
  8428. if (ap) {
  8429. ap->flag |= ALIASINUSE;
  8430. sp->string = s;
  8431. }
  8432. #endif
  8433. g_parsefile->next_to_pgetc = s;
  8434. g_parsefile->left_in_line = len;
  8435. INT_ON;
  8436. }
  8437. static void
  8438. popstring(void)
  8439. {
  8440. struct strpush *sp = g_parsefile->strpush;
  8441. INT_OFF;
  8442. #if ENABLE_ASH_ALIAS
  8443. if (sp->ap) {
  8444. if (g_parsefile->next_to_pgetc[-1] == ' '
  8445. || g_parsefile->next_to_pgetc[-1] == '\t'
  8446. ) {
  8447. checkkwd |= CHKALIAS;
  8448. }
  8449. if (sp->string != sp->ap->val) {
  8450. free(sp->string);
  8451. }
  8452. sp->ap->flag &= ~ALIASINUSE;
  8453. if (sp->ap->flag & ALIASDEAD) {
  8454. unalias(sp->ap->name);
  8455. }
  8456. }
  8457. #endif
  8458. g_parsefile->next_to_pgetc = sp->prev_string;
  8459. g_parsefile->left_in_line = sp->prev_left_in_line;
  8460. g_parsefile->strpush = sp->prev;
  8461. if (sp != &(g_parsefile->basestrpush))
  8462. free(sp);
  8463. INT_ON;
  8464. }
  8465. //FIXME: BASH_COMPAT with "...&" does TWO pungetc():
  8466. //it peeks whether it is &>, and then pushes back both chars.
  8467. //This function needs to save last *next_to_pgetc to buf[0]
  8468. //to make two pungetc() reliable. Currently,
  8469. // pgetc (out of buf: does preadfd), pgetc, pungetc, pungetc won't work...
  8470. static int
  8471. preadfd(void)
  8472. {
  8473. int nr;
  8474. char *buf = g_parsefile->buf;
  8475. g_parsefile->next_to_pgetc = buf;
  8476. #if ENABLE_FEATURE_EDITING
  8477. retry:
  8478. if (!iflag || g_parsefile->fd != STDIN_FILENO)
  8479. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8480. else {
  8481. #if ENABLE_FEATURE_TAB_COMPLETION
  8482. line_input_state->path_lookup = pathval();
  8483. #endif
  8484. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  8485. if (nr == 0) {
  8486. /* Ctrl+C pressed */
  8487. if (trap[SIGINT]) {
  8488. buf[0] = '\n';
  8489. buf[1] = '\0';
  8490. raise(SIGINT);
  8491. return 1;
  8492. }
  8493. goto retry;
  8494. }
  8495. if (nr < 0 && errno == 0) {
  8496. /* Ctrl+D pressed */
  8497. nr = 0;
  8498. }
  8499. }
  8500. #else
  8501. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8502. #endif
  8503. #if 0
  8504. /* nonblock_safe_read() handles this problem */
  8505. if (nr < 0) {
  8506. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8507. int flags = fcntl(0, F_GETFL);
  8508. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8509. flags &= ~O_NONBLOCK;
  8510. if (fcntl(0, F_SETFL, flags) >= 0) {
  8511. out2str("sh: turning off NDELAY mode\n");
  8512. goto retry;
  8513. }
  8514. }
  8515. }
  8516. }
  8517. #endif
  8518. return nr;
  8519. }
  8520. /*
  8521. * Refill the input buffer and return the next input character:
  8522. *
  8523. * 1) If a string was pushed back on the input, pop it;
  8524. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  8525. * or we are reading from a string so we can't refill the buffer,
  8526. * return EOF.
  8527. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  8528. * 4) Process input up to the next newline, deleting nul characters.
  8529. */
  8530. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  8531. #define pgetc_debug(...) ((void)0)
  8532. /*
  8533. * NB: due to SIT(c) internals (syntax_index_table[] vector),
  8534. * pgetc() and related functions must return chars SIGN-EXTENDED into ints,
  8535. * not zero-extended. Seems fragile to me. Affects only !USE_SIT_FUNCTION case,
  8536. * so we can fix it by ditching !USE_SIT_FUNCTION if Unicode requires that.
  8537. */
  8538. static int
  8539. preadbuffer(void)
  8540. {
  8541. char *q;
  8542. int more;
  8543. while (g_parsefile->strpush) {
  8544. #if ENABLE_ASH_ALIAS
  8545. if (g_parsefile->left_in_line == -1
  8546. && g_parsefile->strpush->ap
  8547. && g_parsefile->next_to_pgetc[-1] != ' '
  8548. && g_parsefile->next_to_pgetc[-1] != '\t'
  8549. ) {
  8550. pgetc_debug("preadbuffer PEOA");
  8551. return PEOA;
  8552. }
  8553. #endif
  8554. popstring();
  8555. /* try "pgetc" now: */
  8556. pgetc_debug("preadbuffer internal pgetc at %d:%p'%s'",
  8557. g_parsefile->left_in_line,
  8558. g_parsefile->next_to_pgetc,
  8559. g_parsefile->next_to_pgetc);
  8560. if (--g_parsefile->left_in_line >= 0)
  8561. return (unsigned char)(*g_parsefile->next_to_pgetc++);
  8562. }
  8563. /* on both branches above g_parsefile->left_in_line < 0.
  8564. * "pgetc" needs refilling.
  8565. */
  8566. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  8567. * pungetc() may increment it a few times.
  8568. * Assuming it won't increment it to less than -90.
  8569. */
  8570. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  8571. pgetc_debug("preadbuffer PEOF1");
  8572. /* even in failure keep left_in_line and next_to_pgetc
  8573. * in lock step, for correct multi-layer pungetc.
  8574. * left_in_line was decremented before preadbuffer(),
  8575. * must inc next_to_pgetc: */
  8576. g_parsefile->next_to_pgetc++;
  8577. return PEOF;
  8578. }
  8579. more = g_parsefile->left_in_buffer;
  8580. if (more <= 0) {
  8581. flush_stdout_stderr();
  8582. again:
  8583. more = preadfd();
  8584. if (more <= 0) {
  8585. /* don't try reading again */
  8586. g_parsefile->left_in_line = -99;
  8587. pgetc_debug("preadbuffer PEOF2");
  8588. g_parsefile->next_to_pgetc++;
  8589. return PEOF;
  8590. }
  8591. }
  8592. /* Find out where's the end of line.
  8593. * Set g_parsefile->left_in_line
  8594. * and g_parsefile->left_in_buffer acordingly.
  8595. * NUL chars are deleted.
  8596. */
  8597. q = g_parsefile->next_to_pgetc;
  8598. for (;;) {
  8599. char c;
  8600. more--;
  8601. c = *q;
  8602. if (c == '\0') {
  8603. memmove(q, q + 1, more);
  8604. } else {
  8605. q++;
  8606. if (c == '\n') {
  8607. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8608. break;
  8609. }
  8610. }
  8611. if (more <= 0) {
  8612. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  8613. if (g_parsefile->left_in_line < 0)
  8614. goto again;
  8615. break;
  8616. }
  8617. }
  8618. g_parsefile->left_in_buffer = more;
  8619. if (vflag) {
  8620. char save = *q;
  8621. *q = '\0';
  8622. out2str(g_parsefile->next_to_pgetc);
  8623. *q = save;
  8624. }
  8625. pgetc_debug("preadbuffer at %d:%p'%s'",
  8626. g_parsefile->left_in_line,
  8627. g_parsefile->next_to_pgetc,
  8628. g_parsefile->next_to_pgetc);
  8629. return signed_char2int(*g_parsefile->next_to_pgetc++);
  8630. }
  8631. #define pgetc_as_macro() \
  8632. (--g_parsefile->left_in_line >= 0 \
  8633. ? signed_char2int(*g_parsefile->next_to_pgetc++) \
  8634. : preadbuffer() \
  8635. )
  8636. static int
  8637. pgetc(void)
  8638. {
  8639. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8640. g_parsefile->left_in_line,
  8641. g_parsefile->next_to_pgetc,
  8642. g_parsefile->next_to_pgetc);
  8643. return pgetc_as_macro();
  8644. }
  8645. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8646. #define pgetc_fast() pgetc()
  8647. #else
  8648. #define pgetc_fast() pgetc_as_macro()
  8649. #endif
  8650. /*
  8651. * Same as pgetc(), but ignores PEOA.
  8652. */
  8653. #if ENABLE_ASH_ALIAS
  8654. static int
  8655. pgetc2(void)
  8656. {
  8657. int c;
  8658. do {
  8659. pgetc_debug("pgetc_fast at %d:%p'%s'",
  8660. g_parsefile->left_in_line,
  8661. g_parsefile->next_to_pgetc,
  8662. g_parsefile->next_to_pgetc);
  8663. c = pgetc_fast();
  8664. } while (c == PEOA);
  8665. return c;
  8666. }
  8667. #else
  8668. #define pgetc2() pgetc()
  8669. #endif
  8670. /*
  8671. * Read a line from the script.
  8672. */
  8673. static char *
  8674. pfgets(char *line, int len)
  8675. {
  8676. char *p = line;
  8677. int nleft = len;
  8678. int c;
  8679. while (--nleft > 0) {
  8680. c = pgetc2();
  8681. if (c == PEOF) {
  8682. if (p == line)
  8683. return NULL;
  8684. break;
  8685. }
  8686. *p++ = c;
  8687. if (c == '\n')
  8688. break;
  8689. }
  8690. *p = '\0';
  8691. return line;
  8692. }
  8693. /*
  8694. * Undo the last call to pgetc. Only one character may be pushed back.
  8695. * PEOF may be pushed back.
  8696. */
  8697. static void
  8698. pungetc(void)
  8699. {
  8700. g_parsefile->left_in_line++;
  8701. g_parsefile->next_to_pgetc--;
  8702. pgetc_debug("pushed back to %d:%p'%s'",
  8703. g_parsefile->left_in_line,
  8704. g_parsefile->next_to_pgetc,
  8705. g_parsefile->next_to_pgetc);
  8706. }
  8707. /*
  8708. * To handle the "." command, a stack of input files is used. Pushfile
  8709. * adds a new entry to the stack and popfile restores the previous level.
  8710. */
  8711. static void
  8712. pushfile(void)
  8713. {
  8714. struct parsefile *pf;
  8715. pf = ckzalloc(sizeof(*pf));
  8716. pf->prev = g_parsefile;
  8717. pf->fd = -1;
  8718. /*pf->strpush = NULL; - ckzalloc did it */
  8719. /*pf->basestrpush.prev = NULL;*/
  8720. g_parsefile = pf;
  8721. }
  8722. static void
  8723. popfile(void)
  8724. {
  8725. struct parsefile *pf = g_parsefile;
  8726. INT_OFF;
  8727. if (pf->fd >= 0)
  8728. close(pf->fd);
  8729. free(pf->buf);
  8730. while (pf->strpush)
  8731. popstring();
  8732. g_parsefile = pf->prev;
  8733. free(pf);
  8734. INT_ON;
  8735. }
  8736. /*
  8737. * Return to top level.
  8738. */
  8739. static void
  8740. popallfiles(void)
  8741. {
  8742. while (g_parsefile != &basepf)
  8743. popfile();
  8744. }
  8745. /*
  8746. * Close the file(s) that the shell is reading commands from. Called
  8747. * after a fork is done.
  8748. */
  8749. static void
  8750. closescript(void)
  8751. {
  8752. popallfiles();
  8753. if (g_parsefile->fd > 0) {
  8754. close(g_parsefile->fd);
  8755. g_parsefile->fd = 0;
  8756. }
  8757. }
  8758. /*
  8759. * Like setinputfile, but takes an open file descriptor. Call this with
  8760. * interrupts off.
  8761. */
  8762. static void
  8763. setinputfd(int fd, int push)
  8764. {
  8765. close_on_exec_on(fd);
  8766. if (push) {
  8767. pushfile();
  8768. g_parsefile->buf = NULL;
  8769. }
  8770. g_parsefile->fd = fd;
  8771. if (g_parsefile->buf == NULL)
  8772. g_parsefile->buf = ckmalloc(IBUFSIZ);
  8773. g_parsefile->left_in_buffer = 0;
  8774. g_parsefile->left_in_line = 0;
  8775. g_parsefile->linno = 1;
  8776. }
  8777. /*
  8778. * Set the input to take input from a file. If push is set, push the
  8779. * old input onto the stack first.
  8780. */
  8781. static int
  8782. setinputfile(const char *fname, int flags)
  8783. {
  8784. int fd;
  8785. int fd2;
  8786. INT_OFF;
  8787. fd = open(fname, O_RDONLY);
  8788. if (fd < 0) {
  8789. if (flags & INPUT_NOFILE_OK)
  8790. goto out;
  8791. ash_msg_and_raise_error("can't open '%s'", fname);
  8792. }
  8793. if (fd < 10) {
  8794. fd2 = copyfd(fd, 10);
  8795. close(fd);
  8796. if (fd2 < 0)
  8797. ash_msg_and_raise_error("out of file descriptors");
  8798. fd = fd2;
  8799. }
  8800. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8801. out:
  8802. INT_ON;
  8803. return fd;
  8804. }
  8805. /*
  8806. * Like setinputfile, but takes input from a string.
  8807. */
  8808. static void
  8809. setinputstring(char *string)
  8810. {
  8811. INT_OFF;
  8812. pushfile();
  8813. g_parsefile->next_to_pgetc = string;
  8814. g_parsefile->left_in_line = strlen(string);
  8815. g_parsefile->buf = NULL;
  8816. g_parsefile->linno = 1;
  8817. INT_ON;
  8818. }
  8819. /* ============ mail.c
  8820. *
  8821. * Routines to check for mail.
  8822. */
  8823. #if ENABLE_ASH_MAIL
  8824. #define MAXMBOXES 10
  8825. /* times of mailboxes */
  8826. static time_t mailtime[MAXMBOXES];
  8827. /* Set if MAIL or MAILPATH is changed. */
  8828. static smallint mail_var_path_changed;
  8829. /*
  8830. * Print appropriate message(s) if mail has arrived.
  8831. * If mail_var_path_changed is set,
  8832. * then the value of MAIL has mail_var_path_changed,
  8833. * so we just update the values.
  8834. */
  8835. static void
  8836. chkmail(void)
  8837. {
  8838. const char *mpath;
  8839. char *p;
  8840. char *q;
  8841. time_t *mtp;
  8842. struct stackmark smark;
  8843. struct stat statb;
  8844. setstackmark(&smark);
  8845. mpath = mpathset() ? mpathval() : mailval();
  8846. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8847. p = path_advance(&mpath, nullstr);
  8848. if (p == NULL)
  8849. break;
  8850. if (*p == '\0')
  8851. continue;
  8852. for (q = p; *q; q++)
  8853. continue;
  8854. #if DEBUG
  8855. if (q[-1] != '/')
  8856. abort();
  8857. #endif
  8858. q[-1] = '\0'; /* delete trailing '/' */
  8859. if (stat(p, &statb) < 0) {
  8860. *mtp = 0;
  8861. continue;
  8862. }
  8863. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8864. fprintf(
  8865. stderr, snlfmt,
  8866. pathopt ? pathopt : "you have mail"
  8867. );
  8868. }
  8869. *mtp = statb.st_mtime;
  8870. }
  8871. mail_var_path_changed = 0;
  8872. popstackmark(&smark);
  8873. }
  8874. static void FAST_FUNC
  8875. changemail(const char *val UNUSED_PARAM)
  8876. {
  8877. mail_var_path_changed = 1;
  8878. }
  8879. #endif /* ASH_MAIL */
  8880. /* ============ ??? */
  8881. /*
  8882. * Set the shell parameters.
  8883. */
  8884. static void
  8885. setparam(char **argv)
  8886. {
  8887. char **newparam;
  8888. char **ap;
  8889. int nparam;
  8890. for (nparam = 0; argv[nparam]; nparam++)
  8891. continue;
  8892. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  8893. while (*argv) {
  8894. *ap++ = ckstrdup(*argv++);
  8895. }
  8896. *ap = NULL;
  8897. freeparam(&shellparam);
  8898. shellparam.malloced = 1;
  8899. shellparam.nparam = nparam;
  8900. shellparam.p = newparam;
  8901. #if ENABLE_ASH_GETOPTS
  8902. shellparam.optind = 1;
  8903. shellparam.optoff = -1;
  8904. #endif
  8905. }
  8906. /*
  8907. * Process shell options. The global variable argptr contains a pointer
  8908. * to the argument list; we advance it past the options.
  8909. *
  8910. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  8911. * For a non-interactive shell, an error condition encountered
  8912. * by a special built-in ... shall cause the shell to write a diagnostic message
  8913. * to standard error and exit as shown in the following table:
  8914. * Error Special Built-In
  8915. * ...
  8916. * Utility syntax error (option or operand error) Shall exit
  8917. * ...
  8918. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  8919. * we see that bash does not do that (set "finishes" with error code 1 instead,
  8920. * and shell continues), and people rely on this behavior!
  8921. * Testcase:
  8922. * set -o barfoo 2>/dev/null
  8923. * echo $?
  8924. *
  8925. * Oh well. Let's mimic that.
  8926. */
  8927. static int
  8928. plus_minus_o(char *name, int val)
  8929. {
  8930. int i;
  8931. if (name) {
  8932. for (i = 0; i < NOPTS; i++) {
  8933. if (strcmp(name, optnames(i)) == 0) {
  8934. optlist[i] = val;
  8935. return 0;
  8936. }
  8937. }
  8938. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  8939. return 1;
  8940. }
  8941. for (i = 0; i < NOPTS; i++) {
  8942. if (val) {
  8943. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  8944. } else {
  8945. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  8946. }
  8947. }
  8948. return 0;
  8949. }
  8950. static void
  8951. setoption(int flag, int val)
  8952. {
  8953. int i;
  8954. for (i = 0; i < NOPTS; i++) {
  8955. if (optletters(i) == flag) {
  8956. optlist[i] = val;
  8957. return;
  8958. }
  8959. }
  8960. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  8961. /* NOTREACHED */
  8962. }
  8963. static int
  8964. options(int cmdline)
  8965. {
  8966. char *p;
  8967. int val;
  8968. int c;
  8969. if (cmdline)
  8970. minusc = NULL;
  8971. while ((p = *argptr) != NULL) {
  8972. c = *p++;
  8973. if (c != '-' && c != '+')
  8974. break;
  8975. argptr++;
  8976. val = 0; /* val = 0 if c == '+' */
  8977. if (c == '-') {
  8978. val = 1;
  8979. if (p[0] == '\0' || LONE_DASH(p)) {
  8980. if (!cmdline) {
  8981. /* "-" means turn off -x and -v */
  8982. if (p[0] == '\0')
  8983. xflag = vflag = 0;
  8984. /* "--" means reset params */
  8985. else if (*argptr == NULL)
  8986. setparam(argptr);
  8987. }
  8988. break; /* "-" or "--" terminates options */
  8989. }
  8990. }
  8991. /* first char was + or - */
  8992. while ((c = *p++) != '\0') {
  8993. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  8994. if (c == 'c' && cmdline) {
  8995. minusc = p; /* command is after shell args */
  8996. } else if (c == 'o') {
  8997. if (plus_minus_o(*argptr, val)) {
  8998. /* it already printed err message */
  8999. return 1; /* error */
  9000. }
  9001. if (*argptr)
  9002. argptr++;
  9003. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9004. isloginsh = 1;
  9005. /* bash does not accept +-login, we also won't */
  9006. } else if (cmdline && val && (c == '-')) { /* long options */
  9007. if (strcmp(p, "login") == 0)
  9008. isloginsh = 1;
  9009. break;
  9010. } else {
  9011. setoption(c, val);
  9012. }
  9013. }
  9014. }
  9015. return 0;
  9016. }
  9017. /*
  9018. * The shift builtin command.
  9019. */
  9020. static int FAST_FUNC
  9021. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9022. {
  9023. int n;
  9024. char **ap1, **ap2;
  9025. n = 1;
  9026. if (argv[1])
  9027. n = number(argv[1]);
  9028. if (n > shellparam.nparam)
  9029. n = 0; /* bash compat, was = shellparam.nparam; */
  9030. INT_OFF;
  9031. shellparam.nparam -= n;
  9032. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9033. if (shellparam.malloced)
  9034. free(*ap1);
  9035. }
  9036. ap2 = shellparam.p;
  9037. while ((*ap2++ = *ap1++) != NULL)
  9038. continue;
  9039. #if ENABLE_ASH_GETOPTS
  9040. shellparam.optind = 1;
  9041. shellparam.optoff = -1;
  9042. #endif
  9043. INT_ON;
  9044. return 0;
  9045. }
  9046. /*
  9047. * POSIX requires that 'set' (but not export or readonly) output the
  9048. * variables in lexicographic order - by the locale's collating order (sigh).
  9049. * Maybe we could keep them in an ordered balanced binary tree
  9050. * instead of hashed lists.
  9051. * For now just roll 'em through qsort for printing...
  9052. */
  9053. static int
  9054. showvars(const char *sep_prefix, int on, int off)
  9055. {
  9056. const char *sep;
  9057. char **ep, **epend;
  9058. ep = listvars(on, off, &epend);
  9059. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9060. sep = *sep_prefix ? " " : sep_prefix;
  9061. for (; ep < epend; ep++) {
  9062. const char *p;
  9063. const char *q;
  9064. p = strchrnul(*ep, '=');
  9065. q = nullstr;
  9066. if (*p)
  9067. q = single_quote(++p);
  9068. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9069. }
  9070. return 0;
  9071. }
  9072. /*
  9073. * The set command builtin.
  9074. */
  9075. static int FAST_FUNC
  9076. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9077. {
  9078. int retval;
  9079. if (!argv[1])
  9080. return showvars(nullstr, 0, VUNSET);
  9081. INT_OFF;
  9082. retval = 1;
  9083. if (!options(0)) { /* if no parse error... */
  9084. retval = 0;
  9085. optschanged();
  9086. if (*argptr != NULL) {
  9087. setparam(argptr);
  9088. }
  9089. }
  9090. INT_ON;
  9091. return retval;
  9092. }
  9093. #if ENABLE_ASH_RANDOM_SUPPORT
  9094. static void FAST_FUNC
  9095. change_random(const char *value)
  9096. {
  9097. /* Galois LFSR parameter */
  9098. /* Taps at 32 31 29 1: */
  9099. enum { MASK = 0x8000000b };
  9100. /* Another example - taps at 32 31 30 10: */
  9101. /* MASK = 0x00400007 */
  9102. if (value == NULL) {
  9103. /* "get", generate */
  9104. uint32_t t;
  9105. /* LCG has period of 2^32 and alternating lowest bit */
  9106. random_LCG = 1664525 * random_LCG + 1013904223;
  9107. /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
  9108. t = (random_galois_LFSR << 1);
  9109. if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
  9110. t ^= MASK;
  9111. random_galois_LFSR = t;
  9112. /* Both are weak, combining them gives better randomness
  9113. * and ~2^64 period. & 0x7fff is probably bash compat
  9114. * for $RANDOM range. Combining with subtraction is
  9115. * just for fun. + and ^ would work equally well. */
  9116. t = (t - random_LCG) & 0x7fff;
  9117. /* set without recursion */
  9118. setvar(vrandom.text, utoa(t), VNOFUNC);
  9119. vrandom.flags &= ~VNOFUNC;
  9120. } else {
  9121. /* set/reset */
  9122. random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
  9123. }
  9124. }
  9125. #endif
  9126. #if ENABLE_ASH_GETOPTS
  9127. static int
  9128. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  9129. {
  9130. char *p, *q;
  9131. char c = '?';
  9132. int done = 0;
  9133. int err = 0;
  9134. char s[12];
  9135. char **optnext;
  9136. if (*param_optind < 1)
  9137. return 1;
  9138. optnext = optfirst + *param_optind - 1;
  9139. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  9140. p = NULL;
  9141. else
  9142. p = optnext[-1] + *optoff;
  9143. if (p == NULL || *p == '\0') {
  9144. /* Current word is done, advance */
  9145. p = *optnext;
  9146. if (p == NULL || *p != '-' || *++p == '\0') {
  9147. atend:
  9148. p = NULL;
  9149. done = 1;
  9150. goto out;
  9151. }
  9152. optnext++;
  9153. if (LONE_DASH(p)) /* check for "--" */
  9154. goto atend;
  9155. }
  9156. c = *p++;
  9157. for (q = optstr; *q != c;) {
  9158. if (*q == '\0') {
  9159. if (optstr[0] == ':') {
  9160. s[0] = c;
  9161. s[1] = '\0';
  9162. err |= setvarsafe("OPTARG", s, 0);
  9163. } else {
  9164. fprintf(stderr, "Illegal option -%c\n", c);
  9165. unsetvar("OPTARG");
  9166. }
  9167. c = '?';
  9168. goto out;
  9169. }
  9170. if (*++q == ':')
  9171. q++;
  9172. }
  9173. if (*++q == ':') {
  9174. if (*p == '\0' && (p = *optnext) == NULL) {
  9175. if (optstr[0] == ':') {
  9176. s[0] = c;
  9177. s[1] = '\0';
  9178. err |= setvarsafe("OPTARG", s, 0);
  9179. c = ':';
  9180. } else {
  9181. fprintf(stderr, "No arg for -%c option\n", c);
  9182. unsetvar("OPTARG");
  9183. c = '?';
  9184. }
  9185. goto out;
  9186. }
  9187. if (p == *optnext)
  9188. optnext++;
  9189. err |= setvarsafe("OPTARG", p, 0);
  9190. p = NULL;
  9191. } else
  9192. err |= setvarsafe("OPTARG", nullstr, 0);
  9193. out:
  9194. *optoff = p ? p - *(optnext - 1) : -1;
  9195. *param_optind = optnext - optfirst + 1;
  9196. fmtstr(s, sizeof(s), "%d", *param_optind);
  9197. err |= setvarsafe("OPTIND", s, VNOFUNC);
  9198. s[0] = c;
  9199. s[1] = '\0';
  9200. err |= setvarsafe(optvar, s, 0);
  9201. if (err) {
  9202. *param_optind = 1;
  9203. *optoff = -1;
  9204. flush_stdout_stderr();
  9205. raise_exception(EXERROR);
  9206. }
  9207. return done;
  9208. }
  9209. /*
  9210. * The getopts builtin. Shellparam.optnext points to the next argument
  9211. * to be processed. Shellparam.optptr points to the next character to
  9212. * be processed in the current argument. If shellparam.optnext is NULL,
  9213. * then it's the first time getopts has been called.
  9214. */
  9215. static int FAST_FUNC
  9216. getoptscmd(int argc, char **argv)
  9217. {
  9218. char **optbase;
  9219. if (argc < 3)
  9220. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9221. if (argc == 3) {
  9222. optbase = shellparam.p;
  9223. if (shellparam.optind > shellparam.nparam + 1) {
  9224. shellparam.optind = 1;
  9225. shellparam.optoff = -1;
  9226. }
  9227. } else {
  9228. optbase = &argv[3];
  9229. if (shellparam.optind > argc - 2) {
  9230. shellparam.optind = 1;
  9231. shellparam.optoff = -1;
  9232. }
  9233. }
  9234. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9235. &shellparam.optoff);
  9236. }
  9237. #endif /* ASH_GETOPTS */
  9238. /* ============ Shell parser */
  9239. struct heredoc {
  9240. struct heredoc *next; /* next here document in list */
  9241. union node *here; /* redirection node */
  9242. char *eofmark; /* string indicating end of input */
  9243. smallint striptabs; /* if set, strip leading tabs */
  9244. };
  9245. static smallint tokpushback; /* last token pushed back */
  9246. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9247. static smallint quoteflag; /* set if (part of) last token was quoted */
  9248. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9249. static struct heredoc *heredoclist; /* list of here documents to read */
  9250. static char *wordtext; /* text of last word returned by readtoken */
  9251. static struct nodelist *backquotelist;
  9252. static union node *redirnode;
  9253. static struct heredoc *heredoc;
  9254. /*
  9255. * NEOF is returned by parsecmd when it encounters an end of file. It
  9256. * must be distinct from NULL, so we use the address of a variable that
  9257. * happens to be handy.
  9258. */
  9259. #define NEOF ((union node *)&tokpushback)
  9260. /*
  9261. * Called when an unexpected token is read during the parse. The argument
  9262. * is the token that is expected, or -1 if more than one type of token can
  9263. * occur at this point.
  9264. */
  9265. static void raise_error_unexpected_syntax(int) NORETURN;
  9266. static void
  9267. raise_error_unexpected_syntax(int token)
  9268. {
  9269. char msg[64];
  9270. int l;
  9271. l = sprintf(msg, "unexpected %s", tokname(lasttoken));
  9272. if (token >= 0)
  9273. sprintf(msg + l, " (expecting %s)", tokname(token));
  9274. raise_error_syntax(msg);
  9275. /* NOTREACHED */
  9276. }
  9277. #define EOFMARKLEN 79
  9278. /* parsing is heavily cross-recursive, need these forward decls */
  9279. static union node *andor(void);
  9280. static union node *pipeline(void);
  9281. static union node *parse_command(void);
  9282. static void parseheredoc(void);
  9283. static char peektoken(void);
  9284. static int readtoken(void);
  9285. static union node *
  9286. list(int nlflag)
  9287. {
  9288. union node *n1, *n2, *n3;
  9289. int tok;
  9290. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9291. if (nlflag == 2 && peektoken())
  9292. return NULL;
  9293. n1 = NULL;
  9294. for (;;) {
  9295. n2 = andor();
  9296. tok = readtoken();
  9297. if (tok == TBACKGND) {
  9298. if (n2->type == NPIPE) {
  9299. n2->npipe.pipe_backgnd = 1;
  9300. } else {
  9301. if (n2->type != NREDIR) {
  9302. n3 = stzalloc(sizeof(struct nredir));
  9303. n3->nredir.n = n2;
  9304. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9305. n2 = n3;
  9306. }
  9307. n2->type = NBACKGND;
  9308. }
  9309. }
  9310. if (n1 == NULL) {
  9311. n1 = n2;
  9312. } else {
  9313. n3 = stzalloc(sizeof(struct nbinary));
  9314. n3->type = NSEMI;
  9315. n3->nbinary.ch1 = n1;
  9316. n3->nbinary.ch2 = n2;
  9317. n1 = n3;
  9318. }
  9319. switch (tok) {
  9320. case TBACKGND:
  9321. case TSEMI:
  9322. tok = readtoken();
  9323. /* fall through */
  9324. case TNL:
  9325. if (tok == TNL) {
  9326. parseheredoc();
  9327. if (nlflag == 1)
  9328. return n1;
  9329. } else {
  9330. tokpushback = 1;
  9331. }
  9332. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9333. if (peektoken())
  9334. return n1;
  9335. break;
  9336. case TEOF:
  9337. if (heredoclist)
  9338. parseheredoc();
  9339. else
  9340. pungetc(); /* push back EOF on input */
  9341. return n1;
  9342. default:
  9343. if (nlflag == 1)
  9344. raise_error_unexpected_syntax(-1);
  9345. tokpushback = 1;
  9346. return n1;
  9347. }
  9348. }
  9349. }
  9350. static union node *
  9351. andor(void)
  9352. {
  9353. union node *n1, *n2, *n3;
  9354. int t;
  9355. n1 = pipeline();
  9356. for (;;) {
  9357. t = readtoken();
  9358. if (t == TAND) {
  9359. t = NAND;
  9360. } else if (t == TOR) {
  9361. t = NOR;
  9362. } else {
  9363. tokpushback = 1;
  9364. return n1;
  9365. }
  9366. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9367. n2 = pipeline();
  9368. n3 = stzalloc(sizeof(struct nbinary));
  9369. n3->type = t;
  9370. n3->nbinary.ch1 = n1;
  9371. n3->nbinary.ch2 = n2;
  9372. n1 = n3;
  9373. }
  9374. }
  9375. static union node *
  9376. pipeline(void)
  9377. {
  9378. union node *n1, *n2, *pipenode;
  9379. struct nodelist *lp, *prev;
  9380. int negate;
  9381. negate = 0;
  9382. TRACE(("pipeline: entered\n"));
  9383. if (readtoken() == TNOT) {
  9384. negate = !negate;
  9385. checkkwd = CHKKWD | CHKALIAS;
  9386. } else
  9387. tokpushback = 1;
  9388. n1 = parse_command();
  9389. if (readtoken() == TPIPE) {
  9390. pipenode = stzalloc(sizeof(struct npipe));
  9391. pipenode->type = NPIPE;
  9392. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9393. lp = stzalloc(sizeof(struct nodelist));
  9394. pipenode->npipe.cmdlist = lp;
  9395. lp->n = n1;
  9396. do {
  9397. prev = lp;
  9398. lp = stzalloc(sizeof(struct nodelist));
  9399. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9400. lp->n = parse_command();
  9401. prev->next = lp;
  9402. } while (readtoken() == TPIPE);
  9403. lp->next = NULL;
  9404. n1 = pipenode;
  9405. }
  9406. tokpushback = 1;
  9407. if (negate) {
  9408. n2 = stzalloc(sizeof(struct nnot));
  9409. n2->type = NNOT;
  9410. n2->nnot.com = n1;
  9411. return n2;
  9412. }
  9413. return n1;
  9414. }
  9415. static union node *
  9416. makename(void)
  9417. {
  9418. union node *n;
  9419. n = stzalloc(sizeof(struct narg));
  9420. n->type = NARG;
  9421. /*n->narg.next = NULL; - stzalloc did it */
  9422. n->narg.text = wordtext;
  9423. n->narg.backquote = backquotelist;
  9424. return n;
  9425. }
  9426. static void
  9427. fixredir(union node *n, const char *text, int err)
  9428. {
  9429. int fd;
  9430. TRACE(("Fix redir %s %d\n", text, err));
  9431. if (!err)
  9432. n->ndup.vname = NULL;
  9433. fd = bb_strtou(text, NULL, 10);
  9434. if (!errno && fd >= 0)
  9435. n->ndup.dupfd = fd;
  9436. else if (LONE_DASH(text))
  9437. n->ndup.dupfd = -1;
  9438. else {
  9439. if (err)
  9440. raise_error_syntax("bad fd number");
  9441. n->ndup.vname = makename();
  9442. }
  9443. }
  9444. /*
  9445. * Returns true if the text contains nothing to expand (no dollar signs
  9446. * or backquotes).
  9447. */
  9448. static int
  9449. noexpand(const char *text)
  9450. {
  9451. const char *p;
  9452. char c;
  9453. p = text;
  9454. while ((c = *p++) != '\0') {
  9455. if (c == CTLQUOTEMARK)
  9456. continue;
  9457. if (c == CTLESC)
  9458. p++;
  9459. else if (SIT((signed char)c, BASESYNTAX) == CCTL)
  9460. return 0;
  9461. }
  9462. return 1;
  9463. }
  9464. static void
  9465. parsefname(void)
  9466. {
  9467. union node *n = redirnode;
  9468. if (readtoken() != TWORD)
  9469. raise_error_unexpected_syntax(-1);
  9470. if (n->type == NHERE) {
  9471. struct heredoc *here = heredoc;
  9472. struct heredoc *p;
  9473. int i;
  9474. if (quoteflag == 0)
  9475. n->type = NXHERE;
  9476. TRACE(("Here document %d\n", n->type));
  9477. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9478. raise_error_syntax("illegal eof marker for << redirection");
  9479. rmescapes(wordtext);
  9480. here->eofmark = wordtext;
  9481. here->next = NULL;
  9482. if (heredoclist == NULL)
  9483. heredoclist = here;
  9484. else {
  9485. for (p = heredoclist; p->next; p = p->next)
  9486. continue;
  9487. p->next = here;
  9488. }
  9489. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9490. fixredir(n, wordtext, 0);
  9491. } else {
  9492. n->nfile.fname = makename();
  9493. }
  9494. }
  9495. static union node *
  9496. simplecmd(void)
  9497. {
  9498. union node *args, **app;
  9499. union node *n = NULL;
  9500. union node *vars, **vpp;
  9501. union node **rpp, *redir;
  9502. int savecheckkwd;
  9503. #if ENABLE_ASH_BASH_COMPAT
  9504. smallint double_brackets_flag = 0;
  9505. #endif
  9506. args = NULL;
  9507. app = &args;
  9508. vars = NULL;
  9509. vpp = &vars;
  9510. redir = NULL;
  9511. rpp = &redir;
  9512. savecheckkwd = CHKALIAS;
  9513. for (;;) {
  9514. int t;
  9515. checkkwd = savecheckkwd;
  9516. t = readtoken();
  9517. switch (t) {
  9518. #if ENABLE_ASH_BASH_COMPAT
  9519. case TAND: /* "&&" */
  9520. case TOR: /* "||" */
  9521. if (!double_brackets_flag) {
  9522. tokpushback = 1;
  9523. goto out;
  9524. }
  9525. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9526. #endif
  9527. case TWORD:
  9528. n = stzalloc(sizeof(struct narg));
  9529. n->type = NARG;
  9530. /*n->narg.next = NULL; - stzalloc did it */
  9531. n->narg.text = wordtext;
  9532. #if ENABLE_ASH_BASH_COMPAT
  9533. if (strcmp("[[", wordtext) == 0)
  9534. double_brackets_flag = 1;
  9535. else if (strcmp("]]", wordtext) == 0)
  9536. double_brackets_flag = 0;
  9537. #endif
  9538. n->narg.backquote = backquotelist;
  9539. if (savecheckkwd && isassignment(wordtext)) {
  9540. *vpp = n;
  9541. vpp = &n->narg.next;
  9542. } else {
  9543. *app = n;
  9544. app = &n->narg.next;
  9545. savecheckkwd = 0;
  9546. }
  9547. break;
  9548. case TREDIR:
  9549. *rpp = n = redirnode;
  9550. rpp = &n->nfile.next;
  9551. parsefname(); /* read name of redirection file */
  9552. break;
  9553. case TLP:
  9554. if (args && app == &args->narg.next
  9555. && !vars && !redir
  9556. ) {
  9557. struct builtincmd *bcmd;
  9558. const char *name;
  9559. /* We have a function */
  9560. if (readtoken() != TRP)
  9561. raise_error_unexpected_syntax(TRP);
  9562. name = n->narg.text;
  9563. if (!goodname(name)
  9564. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9565. ) {
  9566. raise_error_syntax("bad function name");
  9567. }
  9568. n->type = NDEFUN;
  9569. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9570. n->narg.next = parse_command();
  9571. return n;
  9572. }
  9573. /* fall through */
  9574. default:
  9575. tokpushback = 1;
  9576. goto out;
  9577. }
  9578. }
  9579. out:
  9580. *app = NULL;
  9581. *vpp = NULL;
  9582. *rpp = NULL;
  9583. n = stzalloc(sizeof(struct ncmd));
  9584. n->type = NCMD;
  9585. n->ncmd.args = args;
  9586. n->ncmd.assign = vars;
  9587. n->ncmd.redirect = redir;
  9588. return n;
  9589. }
  9590. static union node *
  9591. parse_command(void)
  9592. {
  9593. union node *n1, *n2;
  9594. union node *ap, **app;
  9595. union node *cp, **cpp;
  9596. union node *redir, **rpp;
  9597. union node **rpp2;
  9598. int t;
  9599. redir = NULL;
  9600. rpp2 = &redir;
  9601. switch (readtoken()) {
  9602. default:
  9603. raise_error_unexpected_syntax(-1);
  9604. /* NOTREACHED */
  9605. case TIF:
  9606. n1 = stzalloc(sizeof(struct nif));
  9607. n1->type = NIF;
  9608. n1->nif.test = list(0);
  9609. if (readtoken() != TTHEN)
  9610. raise_error_unexpected_syntax(TTHEN);
  9611. n1->nif.ifpart = list(0);
  9612. n2 = n1;
  9613. while (readtoken() == TELIF) {
  9614. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9615. n2 = n2->nif.elsepart;
  9616. n2->type = NIF;
  9617. n2->nif.test = list(0);
  9618. if (readtoken() != TTHEN)
  9619. raise_error_unexpected_syntax(TTHEN);
  9620. n2->nif.ifpart = list(0);
  9621. }
  9622. if (lasttoken == TELSE)
  9623. n2->nif.elsepart = list(0);
  9624. else {
  9625. n2->nif.elsepart = NULL;
  9626. tokpushback = 1;
  9627. }
  9628. t = TFI;
  9629. break;
  9630. case TWHILE:
  9631. case TUNTIL: {
  9632. int got;
  9633. n1 = stzalloc(sizeof(struct nbinary));
  9634. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9635. n1->nbinary.ch1 = list(0);
  9636. got = readtoken();
  9637. if (got != TDO) {
  9638. TRACE(("expecting DO got %s %s\n", tokname(got),
  9639. got == TWORD ? wordtext : ""));
  9640. raise_error_unexpected_syntax(TDO);
  9641. }
  9642. n1->nbinary.ch2 = list(0);
  9643. t = TDONE;
  9644. break;
  9645. }
  9646. case TFOR:
  9647. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9648. raise_error_syntax("bad for loop variable");
  9649. n1 = stzalloc(sizeof(struct nfor));
  9650. n1->type = NFOR;
  9651. n1->nfor.var = wordtext;
  9652. checkkwd = CHKKWD | CHKALIAS;
  9653. if (readtoken() == TIN) {
  9654. app = &ap;
  9655. while (readtoken() == TWORD) {
  9656. n2 = stzalloc(sizeof(struct narg));
  9657. n2->type = NARG;
  9658. /*n2->narg.next = NULL; - stzalloc did it */
  9659. n2->narg.text = wordtext;
  9660. n2->narg.backquote = backquotelist;
  9661. *app = n2;
  9662. app = &n2->narg.next;
  9663. }
  9664. *app = NULL;
  9665. n1->nfor.args = ap;
  9666. if (lasttoken != TNL && lasttoken != TSEMI)
  9667. raise_error_unexpected_syntax(-1);
  9668. } else {
  9669. n2 = stzalloc(sizeof(struct narg));
  9670. n2->type = NARG;
  9671. /*n2->narg.next = NULL; - stzalloc did it */
  9672. n2->narg.text = (char *)dolatstr;
  9673. /*n2->narg.backquote = NULL;*/
  9674. n1->nfor.args = n2;
  9675. /*
  9676. * Newline or semicolon here is optional (but note
  9677. * that the original Bourne shell only allowed NL).
  9678. */
  9679. if (lasttoken != TNL && lasttoken != TSEMI)
  9680. tokpushback = 1;
  9681. }
  9682. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9683. if (readtoken() != TDO)
  9684. raise_error_unexpected_syntax(TDO);
  9685. n1->nfor.body = list(0);
  9686. t = TDONE;
  9687. break;
  9688. case TCASE:
  9689. n1 = stzalloc(sizeof(struct ncase));
  9690. n1->type = NCASE;
  9691. if (readtoken() != TWORD)
  9692. raise_error_unexpected_syntax(TWORD);
  9693. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  9694. n2->type = NARG;
  9695. /*n2->narg.next = NULL; - stzalloc did it */
  9696. n2->narg.text = wordtext;
  9697. n2->narg.backquote = backquotelist;
  9698. do {
  9699. checkkwd = CHKKWD | CHKALIAS;
  9700. } while (readtoken() == TNL);
  9701. if (lasttoken != TIN)
  9702. raise_error_unexpected_syntax(TIN);
  9703. cpp = &n1->ncase.cases;
  9704. next_case:
  9705. checkkwd = CHKNL | CHKKWD;
  9706. t = readtoken();
  9707. while (t != TESAC) {
  9708. if (lasttoken == TLP)
  9709. readtoken();
  9710. *cpp = cp = stzalloc(sizeof(struct nclist));
  9711. cp->type = NCLIST;
  9712. app = &cp->nclist.pattern;
  9713. for (;;) {
  9714. *app = ap = stzalloc(sizeof(struct narg));
  9715. ap->type = NARG;
  9716. /*ap->narg.next = NULL; - stzalloc did it */
  9717. ap->narg.text = wordtext;
  9718. ap->narg.backquote = backquotelist;
  9719. if (readtoken() != TPIPE)
  9720. break;
  9721. app = &ap->narg.next;
  9722. readtoken();
  9723. }
  9724. //ap->narg.next = NULL;
  9725. if (lasttoken != TRP)
  9726. raise_error_unexpected_syntax(TRP);
  9727. cp->nclist.body = list(2);
  9728. cpp = &cp->nclist.next;
  9729. checkkwd = CHKNL | CHKKWD;
  9730. t = readtoken();
  9731. if (t != TESAC) {
  9732. if (t != TENDCASE)
  9733. raise_error_unexpected_syntax(TENDCASE);
  9734. goto next_case;
  9735. }
  9736. }
  9737. *cpp = NULL;
  9738. goto redir;
  9739. case TLP:
  9740. n1 = stzalloc(sizeof(struct nredir));
  9741. n1->type = NSUBSHELL;
  9742. n1->nredir.n = list(0);
  9743. /*n1->nredir.redirect = NULL; - stzalloc did it */
  9744. t = TRP;
  9745. break;
  9746. case TBEGIN:
  9747. n1 = list(0);
  9748. t = TEND;
  9749. break;
  9750. case TWORD:
  9751. case TREDIR:
  9752. tokpushback = 1;
  9753. return simplecmd();
  9754. }
  9755. if (readtoken() != t)
  9756. raise_error_unexpected_syntax(t);
  9757. redir:
  9758. /* Now check for redirection which may follow command */
  9759. checkkwd = CHKKWD | CHKALIAS;
  9760. rpp = rpp2;
  9761. while (readtoken() == TREDIR) {
  9762. *rpp = n2 = redirnode;
  9763. rpp = &n2->nfile.next;
  9764. parsefname();
  9765. }
  9766. tokpushback = 1;
  9767. *rpp = NULL;
  9768. if (redir) {
  9769. if (n1->type != NSUBSHELL) {
  9770. n2 = stzalloc(sizeof(struct nredir));
  9771. n2->type = NREDIR;
  9772. n2->nredir.n = n1;
  9773. n1 = n2;
  9774. }
  9775. n1->nredir.redirect = redir;
  9776. }
  9777. return n1;
  9778. }
  9779. #if ENABLE_ASH_BASH_COMPAT
  9780. static int decode_dollar_squote(void)
  9781. {
  9782. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  9783. int c, cnt;
  9784. char *p;
  9785. char buf[4];
  9786. c = pgetc();
  9787. p = strchr(C_escapes, c);
  9788. if (p) {
  9789. buf[0] = c;
  9790. p = buf;
  9791. cnt = 3;
  9792. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  9793. do {
  9794. c = pgetc();
  9795. *++p = c;
  9796. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  9797. pungetc();
  9798. } else if (c == 'x') { /* \xHH */
  9799. do {
  9800. c = pgetc();
  9801. *++p = c;
  9802. } while (isxdigit(c) && --cnt);
  9803. pungetc();
  9804. if (cnt == 3) { /* \x but next char is "bad" */
  9805. c = 'x';
  9806. goto unrecognized;
  9807. }
  9808. } else { /* simple seq like \\ or \t */
  9809. p++;
  9810. }
  9811. *p = '\0';
  9812. p = buf;
  9813. c = bb_process_escape_sequence((void*)&p);
  9814. } else { /* unrecognized "\z": print both chars unless ' or " */
  9815. if (c != '\'' && c != '"') {
  9816. unrecognized:
  9817. c |= 0x100; /* "please encode \, then me" */
  9818. }
  9819. }
  9820. return c;
  9821. }
  9822. #endif
  9823. /*
  9824. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  9825. * is not NULL, read a here document. In the latter case, eofmark is the
  9826. * word which marks the end of the document and striptabs is true if
  9827. * leading tabs should be stripped from the document. The argument firstc
  9828. * is the first character of the input token or document.
  9829. *
  9830. * Because C does not have internal subroutines, I have simulated them
  9831. * using goto's to implement the subroutine linkage. The following macros
  9832. * will run code that appears at the end of readtoken1.
  9833. */
  9834. #define CHECKEND() {goto checkend; checkend_return:;}
  9835. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  9836. #define PARSESUB() {goto parsesub; parsesub_return:;}
  9837. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  9838. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  9839. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  9840. static int
  9841. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  9842. {
  9843. /* NB: syntax parameter fits into smallint */
  9844. int c = firstc;
  9845. char *out;
  9846. int len;
  9847. char line[EOFMARKLEN + 1];
  9848. struct nodelist *bqlist;
  9849. smallint quotef;
  9850. smallint dblquote;
  9851. smallint oldstyle;
  9852. smallint prevsyntax; /* syntax before arithmetic */
  9853. #if ENABLE_ASH_EXPAND_PRMT
  9854. smallint pssyntax; /* we are expanding a prompt string */
  9855. #endif
  9856. int varnest; /* levels of variables expansion */
  9857. int arinest; /* levels of arithmetic expansion */
  9858. int parenlevel; /* levels of parens in arithmetic */
  9859. int dqvarnest; /* levels of variables expansion within double quotes */
  9860. IF_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  9861. #if __GNUC__
  9862. /* Avoid longjmp clobbering */
  9863. (void) &out;
  9864. (void) &quotef;
  9865. (void) &dblquote;
  9866. (void) &varnest;
  9867. (void) &arinest;
  9868. (void) &parenlevel;
  9869. (void) &dqvarnest;
  9870. (void) &oldstyle;
  9871. (void) &prevsyntax;
  9872. (void) &syntax;
  9873. #endif
  9874. startlinno = g_parsefile->linno;
  9875. bqlist = NULL;
  9876. quotef = 0;
  9877. oldstyle = 0;
  9878. prevsyntax = 0;
  9879. #if ENABLE_ASH_EXPAND_PRMT
  9880. pssyntax = (syntax == PSSYNTAX);
  9881. if (pssyntax)
  9882. syntax = DQSYNTAX;
  9883. #endif
  9884. dblquote = (syntax == DQSYNTAX);
  9885. varnest = 0;
  9886. arinest = 0;
  9887. parenlevel = 0;
  9888. dqvarnest = 0;
  9889. STARTSTACKSTR(out);
  9890. loop:
  9891. /* For each line, until end of word */
  9892. {
  9893. CHECKEND(); /* set c to PEOF if at end of here document */
  9894. for (;;) { /* until end of line or end of word */
  9895. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  9896. switch (SIT(c, syntax)) {
  9897. case CNL: /* '\n' */
  9898. if (syntax == BASESYNTAX)
  9899. goto endword; /* exit outer loop */
  9900. USTPUTC(c, out);
  9901. g_parsefile->linno++;
  9902. if (doprompt)
  9903. setprompt(2);
  9904. c = pgetc();
  9905. goto loop; /* continue outer loop */
  9906. case CWORD:
  9907. USTPUTC(c, out);
  9908. break;
  9909. case CCTL:
  9910. if (eofmark == NULL || dblquote)
  9911. USTPUTC(CTLESC, out);
  9912. #if ENABLE_ASH_BASH_COMPAT
  9913. if (c == '\\' && bash_dollar_squote) {
  9914. c = decode_dollar_squote();
  9915. if (c & 0x100) {
  9916. USTPUTC('\\', out);
  9917. c = (unsigned char)c;
  9918. }
  9919. }
  9920. #endif
  9921. USTPUTC(c, out);
  9922. break;
  9923. case CBACK: /* backslash */
  9924. c = pgetc2();
  9925. if (c == PEOF) {
  9926. USTPUTC(CTLESC, out);
  9927. USTPUTC('\\', out);
  9928. pungetc();
  9929. } else if (c == '\n') {
  9930. if (doprompt)
  9931. setprompt(2);
  9932. } else {
  9933. #if ENABLE_ASH_EXPAND_PRMT
  9934. if (c == '$' && pssyntax) {
  9935. USTPUTC(CTLESC, out);
  9936. USTPUTC('\\', out);
  9937. }
  9938. #endif
  9939. if (dblquote && c != '\\'
  9940. && c != '`' && c != '$'
  9941. && (c != '"' || eofmark != NULL)
  9942. ) {
  9943. USTPUTC(CTLESC, out);
  9944. USTPUTC('\\', out);
  9945. }
  9946. if (SIT(c, SQSYNTAX) == CCTL)
  9947. USTPUTC(CTLESC, out);
  9948. USTPUTC(c, out);
  9949. quotef = 1;
  9950. }
  9951. break;
  9952. case CSQUOTE:
  9953. syntax = SQSYNTAX;
  9954. quotemark:
  9955. if (eofmark == NULL) {
  9956. USTPUTC(CTLQUOTEMARK, out);
  9957. }
  9958. break;
  9959. case CDQUOTE:
  9960. syntax = DQSYNTAX;
  9961. dblquote = 1;
  9962. goto quotemark;
  9963. case CENDQUOTE:
  9964. IF_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  9965. if (eofmark != NULL && arinest == 0
  9966. && varnest == 0
  9967. ) {
  9968. USTPUTC(c, out);
  9969. } else {
  9970. if (dqvarnest == 0) {
  9971. syntax = BASESYNTAX;
  9972. dblquote = 0;
  9973. }
  9974. quotef = 1;
  9975. goto quotemark;
  9976. }
  9977. break;
  9978. case CVAR: /* '$' */
  9979. PARSESUB(); /* parse substitution */
  9980. break;
  9981. case CENDVAR: /* '}' */
  9982. if (varnest > 0) {
  9983. varnest--;
  9984. if (dqvarnest > 0) {
  9985. dqvarnest--;
  9986. }
  9987. USTPUTC(CTLENDVAR, out);
  9988. } else {
  9989. USTPUTC(c, out);
  9990. }
  9991. break;
  9992. #if ENABLE_SH_MATH_SUPPORT
  9993. case CLP: /* '(' in arithmetic */
  9994. parenlevel++;
  9995. USTPUTC(c, out);
  9996. break;
  9997. case CRP: /* ')' in arithmetic */
  9998. if (parenlevel > 0) {
  9999. USTPUTC(c, out);
  10000. --parenlevel;
  10001. } else {
  10002. if (pgetc() == ')') {
  10003. if (--arinest == 0) {
  10004. USTPUTC(CTLENDARI, out);
  10005. syntax = prevsyntax;
  10006. dblquote = (syntax == DQSYNTAX);
  10007. } else
  10008. USTPUTC(')', out);
  10009. } else {
  10010. /*
  10011. * unbalanced parens
  10012. * (don't 2nd guess - no error)
  10013. */
  10014. pungetc();
  10015. USTPUTC(')', out);
  10016. }
  10017. }
  10018. break;
  10019. #endif
  10020. case CBQUOTE: /* '`' */
  10021. PARSEBACKQOLD();
  10022. break;
  10023. case CENDFILE:
  10024. goto endword; /* exit outer loop */
  10025. case CIGN:
  10026. break;
  10027. default:
  10028. if (varnest == 0) {
  10029. #if ENABLE_ASH_BASH_COMPAT
  10030. if (c == '&') {
  10031. if (pgetc() == '>')
  10032. c = 0x100 + '>'; /* flag &> */
  10033. pungetc();
  10034. }
  10035. #endif
  10036. goto endword; /* exit outer loop */
  10037. }
  10038. #if ENABLE_ASH_ALIAS
  10039. if (c != PEOA)
  10040. #endif
  10041. USTPUTC(c, out);
  10042. }
  10043. c = pgetc_fast();
  10044. } /* for (;;) */
  10045. }
  10046. endword:
  10047. #if ENABLE_SH_MATH_SUPPORT
  10048. if (syntax == ARISYNTAX)
  10049. raise_error_syntax("missing '))'");
  10050. #endif
  10051. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  10052. raise_error_syntax("unterminated quoted string");
  10053. if (varnest != 0) {
  10054. startlinno = g_parsefile->linno;
  10055. /* { */
  10056. raise_error_syntax("missing '}'");
  10057. }
  10058. USTPUTC('\0', out);
  10059. len = out - (char *)stackblock();
  10060. out = stackblock();
  10061. if (eofmark == NULL) {
  10062. if ((c == '>' || c == '<' IF_ASH_BASH_COMPAT( || c == 0x100 + '>'))
  10063. && quotef == 0
  10064. ) {
  10065. if (isdigit_str9(out)) {
  10066. PARSEREDIR(); /* passed as params: out, c */
  10067. lasttoken = TREDIR;
  10068. return lasttoken;
  10069. }
  10070. /* else: non-number X seen, interpret it
  10071. * as "NNNX>file" = "NNNX >file" */
  10072. }
  10073. pungetc();
  10074. }
  10075. quoteflag = quotef;
  10076. backquotelist = bqlist;
  10077. grabstackblock(len);
  10078. wordtext = out;
  10079. lasttoken = TWORD;
  10080. return lasttoken;
  10081. /* end of readtoken routine */
  10082. /*
  10083. * Check to see whether we are at the end of the here document. When this
  10084. * is called, c is set to the first character of the next input line. If
  10085. * we are at the end of the here document, this routine sets the c to PEOF.
  10086. */
  10087. checkend: {
  10088. if (eofmark) {
  10089. #if ENABLE_ASH_ALIAS
  10090. if (c == PEOA) {
  10091. c = pgetc2();
  10092. }
  10093. #endif
  10094. if (striptabs) {
  10095. while (c == '\t') {
  10096. c = pgetc2();
  10097. }
  10098. }
  10099. if (c == *eofmark) {
  10100. if (pfgets(line, sizeof(line)) != NULL) {
  10101. char *p, *q;
  10102. p = line;
  10103. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  10104. continue;
  10105. if (*p == '\n' && *q == '\0') {
  10106. c = PEOF;
  10107. g_parsefile->linno++;
  10108. needprompt = doprompt;
  10109. } else {
  10110. pushstring(line, NULL);
  10111. }
  10112. }
  10113. }
  10114. }
  10115. goto checkend_return;
  10116. }
  10117. /*
  10118. * Parse a redirection operator. The variable "out" points to a string
  10119. * specifying the fd to be redirected. The variable "c" contains the
  10120. * first character of the redirection operator.
  10121. */
  10122. parseredir: {
  10123. /* out is already checked to be a valid number or "" */
  10124. int fd = (*out == '\0' ? -1 : atoi(out));
  10125. union node *np;
  10126. np = stzalloc(sizeof(struct nfile));
  10127. if (c == '>') {
  10128. np->nfile.fd = 1;
  10129. c = pgetc();
  10130. if (c == '>')
  10131. np->type = NAPPEND;
  10132. else if (c == '|')
  10133. np->type = NCLOBBER;
  10134. else if (c == '&')
  10135. np->type = NTOFD;
  10136. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  10137. else {
  10138. np->type = NTO;
  10139. pungetc();
  10140. }
  10141. }
  10142. #if ENABLE_ASH_BASH_COMPAT
  10143. else if (c == 0x100 + '>') { /* this flags &> redirection */
  10144. np->nfile.fd = 1;
  10145. pgetc(); /* this is '>', no need to check */
  10146. np->type = NTO2;
  10147. }
  10148. #endif
  10149. else { /* c == '<' */
  10150. /*np->nfile.fd = 0; - stzalloc did it */
  10151. c = pgetc();
  10152. switch (c) {
  10153. case '<':
  10154. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  10155. np = stzalloc(sizeof(struct nhere));
  10156. /*np->nfile.fd = 0; - stzalloc did it */
  10157. }
  10158. np->type = NHERE;
  10159. heredoc = stzalloc(sizeof(struct heredoc));
  10160. heredoc->here = np;
  10161. c = pgetc();
  10162. if (c == '-') {
  10163. heredoc->striptabs = 1;
  10164. } else {
  10165. /*heredoc->striptabs = 0; - stzalloc did it */
  10166. pungetc();
  10167. }
  10168. break;
  10169. case '&':
  10170. np->type = NFROMFD;
  10171. break;
  10172. case '>':
  10173. np->type = NFROMTO;
  10174. break;
  10175. default:
  10176. np->type = NFROM;
  10177. pungetc();
  10178. break;
  10179. }
  10180. }
  10181. if (fd >= 0)
  10182. np->nfile.fd = fd;
  10183. redirnode = np;
  10184. goto parseredir_return;
  10185. }
  10186. /*
  10187. * Parse a substitution. At this point, we have read the dollar sign
  10188. * and nothing else.
  10189. */
  10190. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  10191. * (assuming ascii char codes, as the original implementation did) */
  10192. #define is_special(c) \
  10193. (((unsigned)(c) - 33 < 32) \
  10194. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  10195. parsesub: {
  10196. int subtype;
  10197. int typeloc;
  10198. int flags;
  10199. char *p;
  10200. static const char types[] ALIGN1 = "}-+?=";
  10201. c = pgetc();
  10202. if (c <= PEOA_OR_PEOF
  10203. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  10204. ) {
  10205. #if ENABLE_ASH_BASH_COMPAT
  10206. if (c == '\'')
  10207. bash_dollar_squote = 1;
  10208. else
  10209. #endif
  10210. USTPUTC('$', out);
  10211. pungetc();
  10212. } else if (c == '(') { /* $(command) or $((arith)) */
  10213. if (pgetc() == '(') {
  10214. #if ENABLE_SH_MATH_SUPPORT
  10215. PARSEARITH();
  10216. #else
  10217. raise_error_syntax("you disabled math support for $((arith)) syntax");
  10218. #endif
  10219. } else {
  10220. pungetc();
  10221. PARSEBACKQNEW();
  10222. }
  10223. } else {
  10224. USTPUTC(CTLVAR, out);
  10225. typeloc = out - (char *)stackblock();
  10226. USTPUTC(VSNORMAL, out);
  10227. subtype = VSNORMAL;
  10228. if (c == '{') {
  10229. c = pgetc();
  10230. if (c == '#') {
  10231. c = pgetc();
  10232. if (c == '}')
  10233. c = '#';
  10234. else
  10235. subtype = VSLENGTH;
  10236. } else
  10237. subtype = 0;
  10238. }
  10239. if (c > PEOA_OR_PEOF && is_name(c)) {
  10240. do {
  10241. STPUTC(c, out);
  10242. c = pgetc();
  10243. } while (c > PEOA_OR_PEOF && is_in_name(c));
  10244. } else if (isdigit(c)) {
  10245. do {
  10246. STPUTC(c, out);
  10247. c = pgetc();
  10248. } while (isdigit(c));
  10249. } else if (is_special(c)) {
  10250. USTPUTC(c, out);
  10251. c = pgetc();
  10252. } else {
  10253. badsub:
  10254. raise_error_syntax("bad substitution");
  10255. }
  10256. STPUTC('=', out);
  10257. flags = 0;
  10258. if (subtype == 0) {
  10259. switch (c) {
  10260. case ':':
  10261. c = pgetc();
  10262. #if ENABLE_ASH_BASH_COMPAT
  10263. if (c == ':' || c == '$' || isdigit(c)) {
  10264. pungetc();
  10265. subtype = VSSUBSTR;
  10266. break;
  10267. }
  10268. #endif
  10269. flags = VSNUL;
  10270. /*FALLTHROUGH*/
  10271. default:
  10272. p = strchr(types, c);
  10273. if (p == NULL)
  10274. goto badsub;
  10275. subtype = p - types + VSNORMAL;
  10276. break;
  10277. case '%':
  10278. case '#': {
  10279. int cc = c;
  10280. subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
  10281. c = pgetc();
  10282. if (c == cc)
  10283. subtype++;
  10284. else
  10285. pungetc();
  10286. break;
  10287. }
  10288. #if ENABLE_ASH_BASH_COMPAT
  10289. case '/':
  10290. subtype = VSREPLACE;
  10291. c = pgetc();
  10292. if (c == '/')
  10293. subtype++; /* VSREPLACEALL */
  10294. else
  10295. pungetc();
  10296. break;
  10297. #endif
  10298. }
  10299. } else {
  10300. pungetc();
  10301. }
  10302. if (dblquote || arinest)
  10303. flags |= VSQUOTE;
  10304. *((char *)stackblock() + typeloc) = subtype | flags;
  10305. if (subtype != VSNORMAL) {
  10306. varnest++;
  10307. if (dblquote || arinest) {
  10308. dqvarnest++;
  10309. }
  10310. }
  10311. }
  10312. goto parsesub_return;
  10313. }
  10314. /*
  10315. * Called to parse command substitutions. Newstyle is set if the command
  10316. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10317. * list of commands (passed by reference), and savelen is the number of
  10318. * characters on the top of the stack which must be preserved.
  10319. */
  10320. parsebackq: {
  10321. struct nodelist **nlpp;
  10322. smallint savepbq;
  10323. union node *n;
  10324. char *volatile str;
  10325. struct jmploc jmploc;
  10326. struct jmploc *volatile savehandler;
  10327. size_t savelen;
  10328. smallint saveprompt = 0;
  10329. #ifdef __GNUC__
  10330. (void) &saveprompt;
  10331. #endif
  10332. savepbq = parsebackquote;
  10333. if (setjmp(jmploc.loc)) {
  10334. free(str);
  10335. parsebackquote = 0;
  10336. exception_handler = savehandler;
  10337. longjmp(exception_handler->loc, 1);
  10338. }
  10339. INT_OFF;
  10340. str = NULL;
  10341. savelen = out - (char *)stackblock();
  10342. if (savelen > 0) {
  10343. str = ckmalloc(savelen);
  10344. memcpy(str, stackblock(), savelen);
  10345. }
  10346. savehandler = exception_handler;
  10347. exception_handler = &jmploc;
  10348. INT_ON;
  10349. if (oldstyle) {
  10350. /* We must read until the closing backquote, giving special
  10351. treatment to some slashes, and then push the string and
  10352. reread it as input, interpreting it normally. */
  10353. char *pout;
  10354. int pc;
  10355. size_t psavelen;
  10356. char *pstr;
  10357. STARTSTACKSTR(pout);
  10358. for (;;) {
  10359. if (needprompt) {
  10360. setprompt(2);
  10361. }
  10362. pc = pgetc();
  10363. switch (pc) {
  10364. case '`':
  10365. goto done;
  10366. case '\\':
  10367. pc = pgetc();
  10368. if (pc == '\n') {
  10369. g_parsefile->linno++;
  10370. if (doprompt)
  10371. setprompt(2);
  10372. /*
  10373. * If eating a newline, avoid putting
  10374. * the newline into the new character
  10375. * stream (via the STPUTC after the
  10376. * switch).
  10377. */
  10378. continue;
  10379. }
  10380. if (pc != '\\' && pc != '`' && pc != '$'
  10381. && (!dblquote || pc != '"'))
  10382. STPUTC('\\', pout);
  10383. if (pc > PEOA_OR_PEOF) {
  10384. break;
  10385. }
  10386. /* fall through */
  10387. case PEOF:
  10388. #if ENABLE_ASH_ALIAS
  10389. case PEOA:
  10390. #endif
  10391. startlinno = g_parsefile->linno;
  10392. raise_error_syntax("EOF in backquote substitution");
  10393. case '\n':
  10394. g_parsefile->linno++;
  10395. needprompt = doprompt;
  10396. break;
  10397. default:
  10398. break;
  10399. }
  10400. STPUTC(pc, pout);
  10401. }
  10402. done:
  10403. STPUTC('\0', pout);
  10404. psavelen = pout - (char *)stackblock();
  10405. if (psavelen > 0) {
  10406. pstr = grabstackstr(pout);
  10407. setinputstring(pstr);
  10408. }
  10409. }
  10410. nlpp = &bqlist;
  10411. while (*nlpp)
  10412. nlpp = &(*nlpp)->next;
  10413. *nlpp = stzalloc(sizeof(**nlpp));
  10414. /* (*nlpp)->next = NULL; - stzalloc did it */
  10415. parsebackquote = oldstyle;
  10416. if (oldstyle) {
  10417. saveprompt = doprompt;
  10418. doprompt = 0;
  10419. }
  10420. n = list(2);
  10421. if (oldstyle)
  10422. doprompt = saveprompt;
  10423. else if (readtoken() != TRP)
  10424. raise_error_unexpected_syntax(TRP);
  10425. (*nlpp)->n = n;
  10426. if (oldstyle) {
  10427. /*
  10428. * Start reading from old file again, ignoring any pushed back
  10429. * tokens left from the backquote parsing
  10430. */
  10431. popfile();
  10432. tokpushback = 0;
  10433. }
  10434. while (stackblocksize() <= savelen)
  10435. growstackblock();
  10436. STARTSTACKSTR(out);
  10437. if (str) {
  10438. memcpy(out, str, savelen);
  10439. STADJUST(savelen, out);
  10440. INT_OFF;
  10441. free(str);
  10442. str = NULL;
  10443. INT_ON;
  10444. }
  10445. parsebackquote = savepbq;
  10446. exception_handler = savehandler;
  10447. if (arinest || dblquote)
  10448. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10449. else
  10450. USTPUTC(CTLBACKQ, out);
  10451. if (oldstyle)
  10452. goto parsebackq_oldreturn;
  10453. goto parsebackq_newreturn;
  10454. }
  10455. #if ENABLE_SH_MATH_SUPPORT
  10456. /*
  10457. * Parse an arithmetic expansion (indicate start of one and set state)
  10458. */
  10459. parsearith: {
  10460. if (++arinest == 1) {
  10461. prevsyntax = syntax;
  10462. syntax = ARISYNTAX;
  10463. USTPUTC(CTLARI, out);
  10464. if (dblquote)
  10465. USTPUTC('"', out);
  10466. else
  10467. USTPUTC(' ', out);
  10468. } else {
  10469. /*
  10470. * we collapse embedded arithmetic expansion to
  10471. * parenthesis, which should be equivalent
  10472. */
  10473. USTPUTC('(', out);
  10474. }
  10475. goto parsearith_return;
  10476. }
  10477. #endif
  10478. } /* end of readtoken */
  10479. /*
  10480. * Read the next input token.
  10481. * If the token is a word, we set backquotelist to the list of cmds in
  10482. * backquotes. We set quoteflag to true if any part of the word was
  10483. * quoted.
  10484. * If the token is TREDIR, then we set redirnode to a structure containing
  10485. * the redirection.
  10486. * In all cases, the variable startlinno is set to the number of the line
  10487. * on which the token starts.
  10488. *
  10489. * [Change comment: here documents and internal procedures]
  10490. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10491. * word parsing code into a separate routine. In this case, readtoken
  10492. * doesn't need to have any internal procedures, but parseword does.
  10493. * We could also make parseoperator in essence the main routine, and
  10494. * have parseword (readtoken1?) handle both words and redirection.]
  10495. */
  10496. #define NEW_xxreadtoken
  10497. #ifdef NEW_xxreadtoken
  10498. /* singles must be first! */
  10499. static const char xxreadtoken_chars[7] ALIGN1 = {
  10500. '\n', '(', ')', /* singles */
  10501. '&', '|', ';', /* doubles */
  10502. 0
  10503. };
  10504. #define xxreadtoken_singles 3
  10505. #define xxreadtoken_doubles 3
  10506. static const char xxreadtoken_tokens[] ALIGN1 = {
  10507. TNL, TLP, TRP, /* only single occurrence allowed */
  10508. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10509. TEOF, /* corresponds to trailing nul */
  10510. TAND, TOR, TENDCASE /* if double occurrence */
  10511. };
  10512. static int
  10513. xxreadtoken(void)
  10514. {
  10515. int c;
  10516. if (tokpushback) {
  10517. tokpushback = 0;
  10518. return lasttoken;
  10519. }
  10520. if (needprompt) {
  10521. setprompt(2);
  10522. }
  10523. startlinno = g_parsefile->linno;
  10524. for (;;) { /* until token or start of word found */
  10525. c = pgetc_fast();
  10526. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  10527. continue;
  10528. if (c == '#') {
  10529. while ((c = pgetc()) != '\n' && c != PEOF)
  10530. continue;
  10531. pungetc();
  10532. } else if (c == '\\') {
  10533. if (pgetc() != '\n') {
  10534. pungetc();
  10535. break; /* return readtoken1(...) */
  10536. }
  10537. startlinno = ++g_parsefile->linno;
  10538. if (doprompt)
  10539. setprompt(2);
  10540. } else {
  10541. const char *p;
  10542. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10543. if (c != PEOF) {
  10544. if (c == '\n') {
  10545. g_parsefile->linno++;
  10546. needprompt = doprompt;
  10547. }
  10548. p = strchr(xxreadtoken_chars, c);
  10549. if (p == NULL)
  10550. break; /* return readtoken1(...) */
  10551. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10552. int cc = pgetc();
  10553. if (cc == c) { /* double occurrence? */
  10554. p += xxreadtoken_doubles + 1;
  10555. } else {
  10556. pungetc();
  10557. #if ENABLE_ASH_BASH_COMPAT
  10558. if (c == '&' && cc == '>') /* &> */
  10559. break; /* return readtoken1(...) */
  10560. #endif
  10561. }
  10562. }
  10563. }
  10564. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10565. return lasttoken;
  10566. }
  10567. } /* for (;;) */
  10568. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10569. }
  10570. #else /* old xxreadtoken */
  10571. #define RETURN(token) return lasttoken = token
  10572. static int
  10573. xxreadtoken(void)
  10574. {
  10575. int c;
  10576. if (tokpushback) {
  10577. tokpushback = 0;
  10578. return lasttoken;
  10579. }
  10580. if (needprompt) {
  10581. setprompt(2);
  10582. }
  10583. startlinno = g_parsefile->linno;
  10584. for (;;) { /* until token or start of word found */
  10585. c = pgetc_fast();
  10586. switch (c) {
  10587. case ' ': case '\t':
  10588. #if ENABLE_ASH_ALIAS
  10589. case PEOA:
  10590. #endif
  10591. continue;
  10592. case '#':
  10593. while ((c = pgetc()) != '\n' && c != PEOF)
  10594. continue;
  10595. pungetc();
  10596. continue;
  10597. case '\\':
  10598. if (pgetc() == '\n') {
  10599. startlinno = ++g_parsefile->linno;
  10600. if (doprompt)
  10601. setprompt(2);
  10602. continue;
  10603. }
  10604. pungetc();
  10605. goto breakloop;
  10606. case '\n':
  10607. g_parsefile->linno++;
  10608. needprompt = doprompt;
  10609. RETURN(TNL);
  10610. case PEOF:
  10611. RETURN(TEOF);
  10612. case '&':
  10613. if (pgetc() == '&')
  10614. RETURN(TAND);
  10615. pungetc();
  10616. RETURN(TBACKGND);
  10617. case '|':
  10618. if (pgetc() == '|')
  10619. RETURN(TOR);
  10620. pungetc();
  10621. RETURN(TPIPE);
  10622. case ';':
  10623. if (pgetc() == ';')
  10624. RETURN(TENDCASE);
  10625. pungetc();
  10626. RETURN(TSEMI);
  10627. case '(':
  10628. RETURN(TLP);
  10629. case ')':
  10630. RETURN(TRP);
  10631. default:
  10632. goto breakloop;
  10633. }
  10634. }
  10635. breakloop:
  10636. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10637. #undef RETURN
  10638. }
  10639. #endif /* old xxreadtoken */
  10640. static int
  10641. readtoken(void)
  10642. {
  10643. int t;
  10644. #if DEBUG
  10645. smallint alreadyseen = tokpushback;
  10646. #endif
  10647. #if ENABLE_ASH_ALIAS
  10648. top:
  10649. #endif
  10650. t = xxreadtoken();
  10651. /*
  10652. * eat newlines
  10653. */
  10654. if (checkkwd & CHKNL) {
  10655. while (t == TNL) {
  10656. parseheredoc();
  10657. t = xxreadtoken();
  10658. }
  10659. }
  10660. if (t != TWORD || quoteflag) {
  10661. goto out;
  10662. }
  10663. /*
  10664. * check for keywords
  10665. */
  10666. if (checkkwd & CHKKWD) {
  10667. const char *const *pp;
  10668. pp = findkwd(wordtext);
  10669. if (pp) {
  10670. lasttoken = t = pp - tokname_array;
  10671. TRACE(("keyword %s recognized\n", tokname(t)));
  10672. goto out;
  10673. }
  10674. }
  10675. if (checkkwd & CHKALIAS) {
  10676. #if ENABLE_ASH_ALIAS
  10677. struct alias *ap;
  10678. ap = lookupalias(wordtext, 1);
  10679. if (ap != NULL) {
  10680. if (*ap->val) {
  10681. pushstring(ap->val, ap);
  10682. }
  10683. goto top;
  10684. }
  10685. #endif
  10686. }
  10687. out:
  10688. checkkwd = 0;
  10689. #if DEBUG
  10690. if (!alreadyseen)
  10691. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10692. else
  10693. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10694. #endif
  10695. return t;
  10696. }
  10697. static char
  10698. peektoken(void)
  10699. {
  10700. int t;
  10701. t = readtoken();
  10702. tokpushback = 1;
  10703. return tokname_array[t][0];
  10704. }
  10705. /*
  10706. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  10707. * valid parse tree indicating a blank line.)
  10708. */
  10709. static union node *
  10710. parsecmd(int interact)
  10711. {
  10712. int t;
  10713. tokpushback = 0;
  10714. doprompt = interact;
  10715. if (doprompt)
  10716. setprompt(doprompt);
  10717. needprompt = 0;
  10718. t = readtoken();
  10719. if (t == TEOF)
  10720. return NEOF;
  10721. if (t == TNL)
  10722. return NULL;
  10723. tokpushback = 1;
  10724. return list(1);
  10725. }
  10726. /*
  10727. * Input any here documents.
  10728. */
  10729. static void
  10730. parseheredoc(void)
  10731. {
  10732. struct heredoc *here;
  10733. union node *n;
  10734. here = heredoclist;
  10735. heredoclist = NULL;
  10736. while (here) {
  10737. if (needprompt) {
  10738. setprompt(2);
  10739. }
  10740. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  10741. here->eofmark, here->striptabs);
  10742. n = stzalloc(sizeof(struct narg));
  10743. n->narg.type = NARG;
  10744. /*n->narg.next = NULL; - stzalloc did it */
  10745. n->narg.text = wordtext;
  10746. n->narg.backquote = backquotelist;
  10747. here->here->nhere.doc = n;
  10748. here = here->next;
  10749. }
  10750. }
  10751. /*
  10752. * called by editline -- any expansions to the prompt should be added here.
  10753. */
  10754. #if ENABLE_ASH_EXPAND_PRMT
  10755. static const char *
  10756. expandstr(const char *ps)
  10757. {
  10758. union node n;
  10759. /* XXX Fix (char *) cast. It _is_ a bug. ps is variable's value,
  10760. * and token processing _can_ alter it (delete NULs etc). */
  10761. setinputstring((char *)ps);
  10762. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  10763. popfile();
  10764. n.narg.type = NARG;
  10765. n.narg.next = NULL;
  10766. n.narg.text = wordtext;
  10767. n.narg.backquote = backquotelist;
  10768. expandarg(&n, NULL, 0);
  10769. return stackblock();
  10770. }
  10771. #endif
  10772. /*
  10773. * Execute a command or commands contained in a string.
  10774. */
  10775. static int
  10776. evalstring(char *s, int mask)
  10777. {
  10778. union node *n;
  10779. struct stackmark smark;
  10780. int skip;
  10781. setinputstring(s);
  10782. setstackmark(&smark);
  10783. skip = 0;
  10784. while ((n = parsecmd(0)) != NEOF) {
  10785. evaltree(n, 0);
  10786. popstackmark(&smark);
  10787. skip = evalskip;
  10788. if (skip)
  10789. break;
  10790. }
  10791. popfile();
  10792. skip &= mask;
  10793. evalskip = skip;
  10794. return skip;
  10795. }
  10796. /*
  10797. * The eval command.
  10798. */
  10799. static int FAST_FUNC
  10800. evalcmd(int argc UNUSED_PARAM, char **argv)
  10801. {
  10802. char *p;
  10803. char *concat;
  10804. if (argv[1]) {
  10805. p = argv[1];
  10806. argv += 2;
  10807. if (argv[0]) {
  10808. STARTSTACKSTR(concat);
  10809. for (;;) {
  10810. concat = stack_putstr(p, concat);
  10811. p = *argv++;
  10812. if (p == NULL)
  10813. break;
  10814. STPUTC(' ', concat);
  10815. }
  10816. STPUTC('\0', concat);
  10817. p = grabstackstr(concat);
  10818. }
  10819. evalstring(p, ~SKIPEVAL);
  10820. }
  10821. return exitstatus;
  10822. }
  10823. /*
  10824. * Read and execute commands. "Top" is nonzero for the top level command
  10825. * loop; it turns on prompting if the shell is interactive.
  10826. */
  10827. static int
  10828. cmdloop(int top)
  10829. {
  10830. union node *n;
  10831. struct stackmark smark;
  10832. int inter;
  10833. int numeof = 0;
  10834. TRACE(("cmdloop(%d) called\n", top));
  10835. for (;;) {
  10836. int skip;
  10837. setstackmark(&smark);
  10838. #if JOBS
  10839. if (doing_jobctl)
  10840. showjobs(stderr, SHOW_CHANGED);
  10841. #endif
  10842. inter = 0;
  10843. if (iflag && top) {
  10844. inter++;
  10845. #if ENABLE_ASH_MAIL
  10846. chkmail();
  10847. #endif
  10848. }
  10849. n = parsecmd(inter);
  10850. #if DEBUG > 2
  10851. if (debug && (n != NEOF))
  10852. showtree(n);
  10853. #endif
  10854. if (n == NEOF) {
  10855. if (!top || numeof >= 50)
  10856. break;
  10857. if (!stoppedjobs()) {
  10858. if (!Iflag)
  10859. break;
  10860. out2str("\nUse \"exit\" to leave shell.\n");
  10861. }
  10862. numeof++;
  10863. } else if (nflag == 0) {
  10864. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  10865. job_warning >>= 1;
  10866. numeof = 0;
  10867. evaltree(n, 0);
  10868. }
  10869. popstackmark(&smark);
  10870. skip = evalskip;
  10871. if (skip) {
  10872. evalskip = 0;
  10873. return skip & SKIPEVAL;
  10874. }
  10875. }
  10876. return 0;
  10877. }
  10878. /*
  10879. * Take commands from a file. To be compatible we should do a path
  10880. * search for the file, which is necessary to find sub-commands.
  10881. */
  10882. static char *
  10883. find_dot_file(char *name)
  10884. {
  10885. char *fullname;
  10886. const char *path = pathval();
  10887. struct stat statb;
  10888. /* don't try this for absolute or relative paths */
  10889. if (strchr(name, '/'))
  10890. return name;
  10891. /* IIRC standards do not say whether . is to be searched.
  10892. * And it is even smaller this way, making it unconditional for now:
  10893. */
  10894. if (1) { /* ENABLE_ASH_BASH_COMPAT */
  10895. fullname = name;
  10896. goto try_cur_dir;
  10897. }
  10898. while ((fullname = path_advance(&path, name)) != NULL) {
  10899. try_cur_dir:
  10900. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  10901. /*
  10902. * Don't bother freeing here, since it will
  10903. * be freed by the caller.
  10904. */
  10905. return fullname;
  10906. }
  10907. if (fullname != name)
  10908. stunalloc(fullname);
  10909. }
  10910. /* not found in the PATH */
  10911. ash_msg_and_raise_error("%s: not found", name);
  10912. /* NOTREACHED */
  10913. }
  10914. static int FAST_FUNC
  10915. dotcmd(int argc, char **argv)
  10916. {
  10917. struct strlist *sp;
  10918. volatile struct shparam saveparam;
  10919. int status = 0;
  10920. for (sp = cmdenviron; sp; sp = sp->next)
  10921. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  10922. if (argv[1]) { /* That's what SVR2 does */
  10923. char *fullname = find_dot_file(argv[1]);
  10924. argv += 2;
  10925. argc -= 2;
  10926. if (argc) { /* argc > 0, argv[0] != NULL */
  10927. saveparam = shellparam;
  10928. shellparam.malloced = 0;
  10929. shellparam.nparam = argc;
  10930. shellparam.p = argv;
  10931. };
  10932. setinputfile(fullname, INPUT_PUSH_FILE);
  10933. commandname = fullname;
  10934. cmdloop(0);
  10935. popfile();
  10936. if (argc) {
  10937. freeparam(&shellparam);
  10938. shellparam = saveparam;
  10939. };
  10940. status = exitstatus;
  10941. }
  10942. return status;
  10943. }
  10944. static int FAST_FUNC
  10945. exitcmd(int argc UNUSED_PARAM, char **argv)
  10946. {
  10947. if (stoppedjobs())
  10948. return 0;
  10949. if (argv[1])
  10950. exitstatus = number(argv[1]);
  10951. raise_exception(EXEXIT);
  10952. /* NOTREACHED */
  10953. }
  10954. /*
  10955. * Read a file containing shell functions.
  10956. */
  10957. static void
  10958. readcmdfile(char *name)
  10959. {
  10960. setinputfile(name, INPUT_PUSH_FILE);
  10961. cmdloop(0);
  10962. popfile();
  10963. }
  10964. /* ============ find_command inplementation */
  10965. /*
  10966. * Resolve a command name. If you change this routine, you may have to
  10967. * change the shellexec routine as well.
  10968. */
  10969. static void
  10970. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  10971. {
  10972. struct tblentry *cmdp;
  10973. int idx;
  10974. int prev;
  10975. char *fullname;
  10976. struct stat statb;
  10977. int e;
  10978. int updatetbl;
  10979. struct builtincmd *bcmd;
  10980. /* If name contains a slash, don't use PATH or hash table */
  10981. if (strchr(name, '/') != NULL) {
  10982. entry->u.index = -1;
  10983. if (act & DO_ABS) {
  10984. while (stat(name, &statb) < 0) {
  10985. #ifdef SYSV
  10986. if (errno == EINTR)
  10987. continue;
  10988. #endif
  10989. entry->cmdtype = CMDUNKNOWN;
  10990. return;
  10991. }
  10992. }
  10993. entry->cmdtype = CMDNORMAL;
  10994. return;
  10995. }
  10996. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  10997. updatetbl = (path == pathval());
  10998. if (!updatetbl) {
  10999. act |= DO_ALTPATH;
  11000. if (strstr(path, "%builtin") != NULL)
  11001. act |= DO_ALTBLTIN;
  11002. }
  11003. /* If name is in the table, check answer will be ok */
  11004. cmdp = cmdlookup(name, 0);
  11005. if (cmdp != NULL) {
  11006. int bit;
  11007. switch (cmdp->cmdtype) {
  11008. default:
  11009. #if DEBUG
  11010. abort();
  11011. #endif
  11012. case CMDNORMAL:
  11013. bit = DO_ALTPATH;
  11014. break;
  11015. case CMDFUNCTION:
  11016. bit = DO_NOFUNC;
  11017. break;
  11018. case CMDBUILTIN:
  11019. bit = DO_ALTBLTIN;
  11020. break;
  11021. }
  11022. if (act & bit) {
  11023. updatetbl = 0;
  11024. cmdp = NULL;
  11025. } else if (cmdp->rehash == 0)
  11026. /* if not invalidated by cd, we're done */
  11027. goto success;
  11028. }
  11029. /* If %builtin not in path, check for builtin next */
  11030. bcmd = find_builtin(name);
  11031. if (bcmd) {
  11032. if (IS_BUILTIN_REGULAR(bcmd))
  11033. goto builtin_success;
  11034. if (act & DO_ALTPATH) {
  11035. if (!(act & DO_ALTBLTIN))
  11036. goto builtin_success;
  11037. } else if (builtinloc <= 0) {
  11038. goto builtin_success;
  11039. }
  11040. }
  11041. #if ENABLE_FEATURE_SH_STANDALONE
  11042. {
  11043. int applet_no = find_applet_by_name(name);
  11044. if (applet_no >= 0) {
  11045. entry->cmdtype = CMDNORMAL;
  11046. entry->u.index = -2 - applet_no;
  11047. return;
  11048. }
  11049. }
  11050. #endif
  11051. /* We have to search path. */
  11052. prev = -1; /* where to start */
  11053. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11054. if (cmdp->cmdtype == CMDBUILTIN)
  11055. prev = builtinloc;
  11056. else
  11057. prev = cmdp->param.index;
  11058. }
  11059. e = ENOENT;
  11060. idx = -1;
  11061. loop:
  11062. while ((fullname = path_advance(&path, name)) != NULL) {
  11063. stunalloc(fullname);
  11064. /* NB: code below will still use fullname
  11065. * despite it being "unallocated" */
  11066. idx++;
  11067. if (pathopt) {
  11068. if (prefix(pathopt, "builtin")) {
  11069. if (bcmd)
  11070. goto builtin_success;
  11071. continue;
  11072. }
  11073. if ((act & DO_NOFUNC)
  11074. || !prefix(pathopt, "func")
  11075. ) { /* ignore unimplemented options */
  11076. continue;
  11077. }
  11078. }
  11079. /* if rehash, don't redo absolute path names */
  11080. if (fullname[0] == '/' && idx <= prev) {
  11081. if (idx < prev)
  11082. continue;
  11083. TRACE(("searchexec \"%s\": no change\n", name));
  11084. goto success;
  11085. }
  11086. while (stat(fullname, &statb) < 0) {
  11087. #ifdef SYSV
  11088. if (errno == EINTR)
  11089. continue;
  11090. #endif
  11091. if (errno != ENOENT && errno != ENOTDIR)
  11092. e = errno;
  11093. goto loop;
  11094. }
  11095. e = EACCES; /* if we fail, this will be the error */
  11096. if (!S_ISREG(statb.st_mode))
  11097. continue;
  11098. if (pathopt) { /* this is a %func directory */
  11099. stalloc(strlen(fullname) + 1);
  11100. /* NB: stalloc will return space pointed by fullname
  11101. * (because we don't have any intervening allocations
  11102. * between stunalloc above and this stalloc) */
  11103. readcmdfile(fullname);
  11104. cmdp = cmdlookup(name, 0);
  11105. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  11106. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  11107. stunalloc(fullname);
  11108. goto success;
  11109. }
  11110. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  11111. if (!updatetbl) {
  11112. entry->cmdtype = CMDNORMAL;
  11113. entry->u.index = idx;
  11114. return;
  11115. }
  11116. INT_OFF;
  11117. cmdp = cmdlookup(name, 1);
  11118. cmdp->cmdtype = CMDNORMAL;
  11119. cmdp->param.index = idx;
  11120. INT_ON;
  11121. goto success;
  11122. }
  11123. /* We failed. If there was an entry for this command, delete it */
  11124. if (cmdp && updatetbl)
  11125. delete_cmd_entry();
  11126. if (act & DO_ERR)
  11127. ash_msg("%s: %s", name, errmsg(e, "not found"));
  11128. entry->cmdtype = CMDUNKNOWN;
  11129. return;
  11130. builtin_success:
  11131. if (!updatetbl) {
  11132. entry->cmdtype = CMDBUILTIN;
  11133. entry->u.cmd = bcmd;
  11134. return;
  11135. }
  11136. INT_OFF;
  11137. cmdp = cmdlookup(name, 1);
  11138. cmdp->cmdtype = CMDBUILTIN;
  11139. cmdp->param.cmd = bcmd;
  11140. INT_ON;
  11141. success:
  11142. cmdp->rehash = 0;
  11143. entry->cmdtype = cmdp->cmdtype;
  11144. entry->u = cmdp->param;
  11145. }
  11146. /* ============ trap.c */
  11147. /*
  11148. * The trap builtin.
  11149. */
  11150. static int FAST_FUNC
  11151. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11152. {
  11153. char *action;
  11154. char **ap;
  11155. int signo;
  11156. nextopt(nullstr);
  11157. ap = argptr;
  11158. if (!*ap) {
  11159. for (signo = 0; signo < NSIG; signo++) {
  11160. if (trap[signo] != NULL) {
  11161. out1fmt("trap -- %s %s\n",
  11162. single_quote(trap[signo]),
  11163. get_signame(signo));
  11164. }
  11165. }
  11166. return 0;
  11167. }
  11168. action = NULL;
  11169. if (ap[1])
  11170. action = *ap++;
  11171. while (*ap) {
  11172. signo = get_signum(*ap);
  11173. if (signo < 0)
  11174. ash_msg_and_raise_error("%s: bad trap", *ap);
  11175. INT_OFF;
  11176. if (action) {
  11177. if (LONE_DASH(action))
  11178. action = NULL;
  11179. else
  11180. action = ckstrdup(action);
  11181. }
  11182. free(trap[signo]);
  11183. trap[signo] = action;
  11184. if (signo != 0)
  11185. setsignal(signo);
  11186. INT_ON;
  11187. ap++;
  11188. }
  11189. return 0;
  11190. }
  11191. /* ============ Builtins */
  11192. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  11193. /*
  11194. * Lists available builtins
  11195. */
  11196. static int FAST_FUNC
  11197. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11198. {
  11199. unsigned col;
  11200. unsigned i;
  11201. out1fmt(
  11202. "Built-in commands:\n"
  11203. "------------------\n");
  11204. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  11205. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  11206. builtintab[i].name + 1);
  11207. if (col > 60) {
  11208. out1fmt("\n");
  11209. col = 0;
  11210. }
  11211. }
  11212. #if ENABLE_FEATURE_SH_STANDALONE
  11213. {
  11214. const char *a = applet_names;
  11215. while (*a) {
  11216. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  11217. if (col > 60) {
  11218. out1fmt("\n");
  11219. col = 0;
  11220. }
  11221. a += strlen(a) + 1;
  11222. }
  11223. }
  11224. #endif
  11225. out1fmt("\n\n");
  11226. return EXIT_SUCCESS;
  11227. }
  11228. #endif /* FEATURE_SH_EXTRA_QUIET */
  11229. /*
  11230. * The export and readonly commands.
  11231. */
  11232. static int FAST_FUNC
  11233. exportcmd(int argc UNUSED_PARAM, char **argv)
  11234. {
  11235. struct var *vp;
  11236. char *name;
  11237. const char *p;
  11238. char **aptr;
  11239. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  11240. if (nextopt("p") != 'p') {
  11241. aptr = argptr;
  11242. name = *aptr;
  11243. if (name) {
  11244. do {
  11245. p = strchr(name, '=');
  11246. if (p != NULL) {
  11247. p++;
  11248. } else {
  11249. vp = *findvar(hashvar(name), name);
  11250. if (vp) {
  11251. vp->flags |= flag;
  11252. continue;
  11253. }
  11254. }
  11255. setvar(name, p, flag);
  11256. } while ((name = *++aptr) != NULL);
  11257. return 0;
  11258. }
  11259. }
  11260. showvars(argv[0], flag, 0);
  11261. return 0;
  11262. }
  11263. /*
  11264. * Delete a function if it exists.
  11265. */
  11266. static void
  11267. unsetfunc(const char *name)
  11268. {
  11269. struct tblentry *cmdp;
  11270. cmdp = cmdlookup(name, 0);
  11271. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  11272. delete_cmd_entry();
  11273. }
  11274. /*
  11275. * The unset builtin command. We unset the function before we unset the
  11276. * variable to allow a function to be unset when there is a readonly variable
  11277. * with the same name.
  11278. */
  11279. static int FAST_FUNC
  11280. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11281. {
  11282. char **ap;
  11283. int i;
  11284. int flag = 0;
  11285. int ret = 0;
  11286. while ((i = nextopt("vf")) != '\0') {
  11287. flag = i;
  11288. }
  11289. for (ap = argptr; *ap; ap++) {
  11290. if (flag != 'f') {
  11291. i = unsetvar(*ap);
  11292. ret |= i;
  11293. if (!(i & 2))
  11294. continue;
  11295. }
  11296. if (flag != 'v')
  11297. unsetfunc(*ap);
  11298. }
  11299. return ret & 1;
  11300. }
  11301. /* setmode.c */
  11302. #include <sys/times.h>
  11303. static const unsigned char timescmd_str[] ALIGN1 = {
  11304. ' ', offsetof(struct tms, tms_utime),
  11305. '\n', offsetof(struct tms, tms_stime),
  11306. ' ', offsetof(struct tms, tms_cutime),
  11307. '\n', offsetof(struct tms, tms_cstime),
  11308. 0
  11309. };
  11310. static int FAST_FUNC
  11311. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11312. {
  11313. long clk_tck, s, t;
  11314. const unsigned char *p;
  11315. struct tms buf;
  11316. clk_tck = sysconf(_SC_CLK_TCK);
  11317. times(&buf);
  11318. p = timescmd_str;
  11319. do {
  11320. t = *(clock_t *)(((char *) &buf) + p[1]);
  11321. s = t / clk_tck;
  11322. out1fmt("%ldm%ld.%.3lds%c",
  11323. s/60, s%60,
  11324. ((t - s * clk_tck) * 1000) / clk_tck,
  11325. p[0]);
  11326. } while (*(p += 2));
  11327. return 0;
  11328. }
  11329. #if ENABLE_SH_MATH_SUPPORT
  11330. /*
  11331. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  11332. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11333. *
  11334. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11335. */
  11336. static int FAST_FUNC
  11337. letcmd(int argc UNUSED_PARAM, char **argv)
  11338. {
  11339. arith_t i;
  11340. argv++;
  11341. if (!*argv)
  11342. ash_msg_and_raise_error("expression expected");
  11343. do {
  11344. i = ash_arith(*argv);
  11345. } while (*++argv);
  11346. return !i;
  11347. }
  11348. #endif /* SH_MATH_SUPPORT */
  11349. /* ============ miscbltin.c
  11350. *
  11351. * Miscellaneous builtins.
  11352. */
  11353. #undef rflag
  11354. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11355. typedef enum __rlimit_resource rlim_t;
  11356. #endif
  11357. /*
  11358. * The read builtin. Options:
  11359. * -r Do not interpret '\' specially
  11360. * -s Turn off echo (tty only)
  11361. * -n NCHARS Read NCHARS max
  11362. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11363. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11364. * -u FD Read from given FD instead of fd 0
  11365. * This uses unbuffered input, which may be avoidable in some cases.
  11366. * TODO: bash also has:
  11367. * -a ARRAY Read into array[0],[1],etc
  11368. * -d DELIM End on DELIM char, not newline
  11369. * -e Use line editing (tty only)
  11370. */
  11371. static int FAST_FUNC
  11372. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11373. {
  11374. static const char *const arg_REPLY[] = { "REPLY", NULL };
  11375. char **ap;
  11376. int backslash;
  11377. char c;
  11378. int rflag;
  11379. char *prompt;
  11380. const char *ifs;
  11381. char *p;
  11382. int startword;
  11383. int status;
  11384. int i;
  11385. int fd = 0;
  11386. #if ENABLE_ASH_READ_NCHARS
  11387. int nchars = 0; /* if != 0, -n is in effect */
  11388. int silent = 0;
  11389. struct termios tty, old_tty;
  11390. #endif
  11391. #if ENABLE_ASH_READ_TIMEOUT
  11392. unsigned end_ms = 0;
  11393. unsigned timeout = 0;
  11394. #endif
  11395. rflag = 0;
  11396. prompt = NULL;
  11397. while ((i = nextopt("p:u:r"
  11398. IF_ASH_READ_TIMEOUT("t:")
  11399. IF_ASH_READ_NCHARS("n:s")
  11400. )) != '\0') {
  11401. switch (i) {
  11402. case 'p':
  11403. prompt = optionarg;
  11404. break;
  11405. #if ENABLE_ASH_READ_NCHARS
  11406. case 'n':
  11407. nchars = bb_strtou(optionarg, NULL, 10);
  11408. if (nchars < 0 || errno)
  11409. ash_msg_and_raise_error("invalid count");
  11410. /* nchars == 0: off (bash 3.2 does this too) */
  11411. break;
  11412. case 's':
  11413. silent = 1;
  11414. break;
  11415. #endif
  11416. #if ENABLE_ASH_READ_TIMEOUT
  11417. case 't':
  11418. timeout = bb_strtou(optionarg, NULL, 10);
  11419. if (errno || timeout > UINT_MAX / 2048)
  11420. ash_msg_and_raise_error("invalid timeout");
  11421. timeout *= 1000;
  11422. #if 0 /* even bash have no -t N.NNN support */
  11423. ts.tv_sec = bb_strtou(optionarg, &p, 10);
  11424. ts.tv_usec = 0;
  11425. /* EINVAL means number is ok, but not terminated by NUL */
  11426. if (*p == '.' && errno == EINVAL) {
  11427. char *p2;
  11428. if (*++p) {
  11429. int scale;
  11430. ts.tv_usec = bb_strtou(p, &p2, 10);
  11431. if (errno)
  11432. ash_msg_and_raise_error("invalid timeout");
  11433. scale = p2 - p;
  11434. /* normalize to usec */
  11435. if (scale > 6)
  11436. ash_msg_and_raise_error("invalid timeout");
  11437. while (scale++ < 6)
  11438. ts.tv_usec *= 10;
  11439. }
  11440. } else if (ts.tv_sec < 0 || errno) {
  11441. ash_msg_and_raise_error("invalid timeout");
  11442. }
  11443. if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
  11444. ash_msg_and_raise_error("invalid timeout");
  11445. }
  11446. #endif /* if 0 */
  11447. break;
  11448. #endif
  11449. case 'r':
  11450. rflag = 1;
  11451. break;
  11452. case 'u':
  11453. fd = bb_strtou(optionarg, NULL, 10);
  11454. if (fd < 0 || errno)
  11455. ash_msg_and_raise_error("invalid file descriptor");
  11456. break;
  11457. default:
  11458. break;
  11459. }
  11460. }
  11461. if (prompt && isatty(fd)) {
  11462. out2str(prompt);
  11463. }
  11464. ap = argptr;
  11465. if (*ap == NULL)
  11466. ap = (char**)arg_REPLY;
  11467. ifs = bltinlookup("IFS");
  11468. if (ifs == NULL)
  11469. ifs = defifs;
  11470. #if ENABLE_ASH_READ_NCHARS
  11471. tcgetattr(fd, &tty);
  11472. old_tty = tty;
  11473. if (nchars || silent) {
  11474. if (nchars) {
  11475. tty.c_lflag &= ~ICANON;
  11476. tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
  11477. }
  11478. if (silent) {
  11479. tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
  11480. }
  11481. /* if tcgetattr failed, tcsetattr will fail too.
  11482. * Ignoring, it's harmless. */
  11483. tcsetattr(fd, TCSANOW, &tty);
  11484. }
  11485. #endif
  11486. status = 0;
  11487. startword = 2;
  11488. backslash = 0;
  11489. #if ENABLE_ASH_READ_TIMEOUT
  11490. if (timeout) /* NB: ensuring end_ms is nonzero */
  11491. end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
  11492. #endif
  11493. STARTSTACKSTR(p);
  11494. do {
  11495. const char *is_ifs;
  11496. #if ENABLE_ASH_READ_TIMEOUT
  11497. if (end_ms) {
  11498. struct pollfd pfd[1];
  11499. pfd[0].fd = fd;
  11500. pfd[0].events = POLLIN;
  11501. timeout = end_ms - (unsigned)(monotonic_us() / 1000);
  11502. if ((int)timeout <= 0 /* already late? */
  11503. || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
  11504. ) { /* timed out! */
  11505. #if ENABLE_ASH_READ_NCHARS
  11506. tcsetattr(fd, TCSANOW, &old_tty);
  11507. #endif
  11508. return 1;
  11509. }
  11510. }
  11511. #endif
  11512. if (nonblock_safe_read(fd, &c, 1) != 1) {
  11513. status = 1;
  11514. break;
  11515. }
  11516. if (c == '\0')
  11517. continue;
  11518. if (backslash) {
  11519. backslash = 0;
  11520. if (c != '\n')
  11521. goto put;
  11522. continue;
  11523. }
  11524. if (!rflag && c == '\\') {
  11525. backslash = 1;
  11526. continue;
  11527. }
  11528. if (c == '\n')
  11529. break;
  11530. /* $IFS splitting */
  11531. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
  11532. is_ifs = strchr(ifs, c);
  11533. if (startword && is_ifs) {
  11534. if (isspace(c))
  11535. continue;
  11536. /* it is a non-space ifs char */
  11537. startword--;
  11538. if (startword == 1) /* first one? */
  11539. continue; /* yes, it is not next word yet */
  11540. }
  11541. startword = 0;
  11542. if (ap[1] != NULL && is_ifs) {
  11543. const char *beg;
  11544. STACKSTRNUL(p);
  11545. beg = stackblock();
  11546. setvar(*ap, beg, 0);
  11547. ap++;
  11548. /* can we skip one non-space ifs char? (2: yes) */
  11549. startword = isspace(c) ? 2 : 1;
  11550. STARTSTACKSTR(p);
  11551. continue;
  11552. }
  11553. put:
  11554. STPUTC(c, p);
  11555. }
  11556. /* end of do {} while: */
  11557. #if ENABLE_ASH_READ_NCHARS
  11558. while (--nchars);
  11559. #else
  11560. while (1);
  11561. #endif
  11562. #if ENABLE_ASH_READ_NCHARS
  11563. tcsetattr(fd, TCSANOW, &old_tty);
  11564. #endif
  11565. STACKSTRNUL(p);
  11566. /* Remove trailing space ifs chars */
  11567. while ((char *)stackblock() <= --p && isspace(*p) && strchr(ifs, *p) != NULL)
  11568. *p = '\0';
  11569. setvar(*ap, stackblock(), 0);
  11570. while (*++ap != NULL)
  11571. setvar(*ap, nullstr, 0);
  11572. return status;
  11573. }
  11574. static int FAST_FUNC
  11575. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11576. {
  11577. static const char permuser[3] ALIGN1 = "ugo";
  11578. static const char permmode[3] ALIGN1 = "rwx";
  11579. static const short permmask[] ALIGN2 = {
  11580. S_IRUSR, S_IWUSR, S_IXUSR,
  11581. S_IRGRP, S_IWGRP, S_IXGRP,
  11582. S_IROTH, S_IWOTH, S_IXOTH
  11583. };
  11584. /* TODO: use bb_parse_mode() instead */
  11585. char *ap;
  11586. mode_t mask;
  11587. int i;
  11588. int symbolic_mode = 0;
  11589. while (nextopt("S") != '\0') {
  11590. symbolic_mode = 1;
  11591. }
  11592. INT_OFF;
  11593. mask = umask(0);
  11594. umask(mask);
  11595. INT_ON;
  11596. ap = *argptr;
  11597. if (ap == NULL) {
  11598. if (symbolic_mode) {
  11599. char buf[18];
  11600. char *p = buf;
  11601. for (i = 0; i < 3; i++) {
  11602. int j;
  11603. *p++ = permuser[i];
  11604. *p++ = '=';
  11605. for (j = 0; j < 3; j++) {
  11606. if ((mask & permmask[3 * i + j]) == 0) {
  11607. *p++ = permmode[j];
  11608. }
  11609. }
  11610. *p++ = ',';
  11611. }
  11612. *--p = 0;
  11613. puts(buf);
  11614. } else {
  11615. out1fmt("%.4o\n", mask);
  11616. }
  11617. } else {
  11618. if (isdigit((unsigned char) *ap)) {
  11619. mask = 0;
  11620. do {
  11621. if (*ap >= '8' || *ap < '0')
  11622. ash_msg_and_raise_error(illnum, argv[1]);
  11623. mask = (mask << 3) + (*ap - '0');
  11624. } while (*++ap != '\0');
  11625. umask(mask);
  11626. } else {
  11627. mask = ~mask & 0777;
  11628. if (!bb_parse_mode(ap, &mask)) {
  11629. ash_msg_and_raise_error("illegal mode: %s", ap);
  11630. }
  11631. umask(~mask & 0777);
  11632. }
  11633. }
  11634. return 0;
  11635. }
  11636. /*
  11637. * ulimit builtin
  11638. *
  11639. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11640. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11641. * ash by J.T. Conklin.
  11642. *
  11643. * Public domain.
  11644. */
  11645. struct limits {
  11646. uint8_t cmd; /* RLIMIT_xxx fit into it */
  11647. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  11648. char option;
  11649. };
  11650. static const struct limits limits_tbl[] = {
  11651. #ifdef RLIMIT_CPU
  11652. { RLIMIT_CPU, 0, 't' },
  11653. #endif
  11654. #ifdef RLIMIT_FSIZE
  11655. { RLIMIT_FSIZE, 9, 'f' },
  11656. #endif
  11657. #ifdef RLIMIT_DATA
  11658. { RLIMIT_DATA, 10, 'd' },
  11659. #endif
  11660. #ifdef RLIMIT_STACK
  11661. { RLIMIT_STACK, 10, 's' },
  11662. #endif
  11663. #ifdef RLIMIT_CORE
  11664. { RLIMIT_CORE, 9, 'c' },
  11665. #endif
  11666. #ifdef RLIMIT_RSS
  11667. { RLIMIT_RSS, 10, 'm' },
  11668. #endif
  11669. #ifdef RLIMIT_MEMLOCK
  11670. { RLIMIT_MEMLOCK, 10, 'l' },
  11671. #endif
  11672. #ifdef RLIMIT_NPROC
  11673. { RLIMIT_NPROC, 0, 'p' },
  11674. #endif
  11675. #ifdef RLIMIT_NOFILE
  11676. { RLIMIT_NOFILE, 0, 'n' },
  11677. #endif
  11678. #ifdef RLIMIT_AS
  11679. { RLIMIT_AS, 10, 'v' },
  11680. #endif
  11681. #ifdef RLIMIT_LOCKS
  11682. { RLIMIT_LOCKS, 0, 'w' },
  11683. #endif
  11684. };
  11685. static const char limits_name[] =
  11686. #ifdef RLIMIT_CPU
  11687. "time(seconds)" "\0"
  11688. #endif
  11689. #ifdef RLIMIT_FSIZE
  11690. "file(blocks)" "\0"
  11691. #endif
  11692. #ifdef RLIMIT_DATA
  11693. "data(kb)" "\0"
  11694. #endif
  11695. #ifdef RLIMIT_STACK
  11696. "stack(kb)" "\0"
  11697. #endif
  11698. #ifdef RLIMIT_CORE
  11699. "coredump(blocks)" "\0"
  11700. #endif
  11701. #ifdef RLIMIT_RSS
  11702. "memory(kb)" "\0"
  11703. #endif
  11704. #ifdef RLIMIT_MEMLOCK
  11705. "locked memory(kb)" "\0"
  11706. #endif
  11707. #ifdef RLIMIT_NPROC
  11708. "process" "\0"
  11709. #endif
  11710. #ifdef RLIMIT_NOFILE
  11711. "nofiles" "\0"
  11712. #endif
  11713. #ifdef RLIMIT_AS
  11714. "vmemory(kb)" "\0"
  11715. #endif
  11716. #ifdef RLIMIT_LOCKS
  11717. "locks" "\0"
  11718. #endif
  11719. ;
  11720. enum limtype { SOFT = 0x1, HARD = 0x2 };
  11721. static void
  11722. printlim(enum limtype how, const struct rlimit *limit,
  11723. const struct limits *l)
  11724. {
  11725. rlim_t val;
  11726. val = limit->rlim_max;
  11727. if (how & SOFT)
  11728. val = limit->rlim_cur;
  11729. if (val == RLIM_INFINITY)
  11730. out1fmt("unlimited\n");
  11731. else {
  11732. val >>= l->factor_shift;
  11733. out1fmt("%lld\n", (long long) val);
  11734. }
  11735. }
  11736. static int FAST_FUNC
  11737. ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11738. {
  11739. int c;
  11740. rlim_t val = 0;
  11741. enum limtype how = SOFT | HARD;
  11742. const struct limits *l;
  11743. int set, all = 0;
  11744. int optc, what;
  11745. struct rlimit limit;
  11746. what = 'f';
  11747. while ((optc = nextopt("HSa"
  11748. #ifdef RLIMIT_CPU
  11749. "t"
  11750. #endif
  11751. #ifdef RLIMIT_FSIZE
  11752. "f"
  11753. #endif
  11754. #ifdef RLIMIT_DATA
  11755. "d"
  11756. #endif
  11757. #ifdef RLIMIT_STACK
  11758. "s"
  11759. #endif
  11760. #ifdef RLIMIT_CORE
  11761. "c"
  11762. #endif
  11763. #ifdef RLIMIT_RSS
  11764. "m"
  11765. #endif
  11766. #ifdef RLIMIT_MEMLOCK
  11767. "l"
  11768. #endif
  11769. #ifdef RLIMIT_NPROC
  11770. "p"
  11771. #endif
  11772. #ifdef RLIMIT_NOFILE
  11773. "n"
  11774. #endif
  11775. #ifdef RLIMIT_AS
  11776. "v"
  11777. #endif
  11778. #ifdef RLIMIT_LOCKS
  11779. "w"
  11780. #endif
  11781. )) != '\0')
  11782. switch (optc) {
  11783. case 'H':
  11784. how = HARD;
  11785. break;
  11786. case 'S':
  11787. how = SOFT;
  11788. break;
  11789. case 'a':
  11790. all = 1;
  11791. break;
  11792. default:
  11793. what = optc;
  11794. }
  11795. for (l = limits_tbl; l->option != what; l++)
  11796. continue;
  11797. set = *argptr ? 1 : 0;
  11798. if (set) {
  11799. char *p = *argptr;
  11800. if (all || argptr[1])
  11801. ash_msg_and_raise_error("too many arguments");
  11802. if (strncmp(p, "unlimited\n", 9) == 0)
  11803. val = RLIM_INFINITY;
  11804. else {
  11805. val = (rlim_t) 0;
  11806. while ((c = *p++) >= '0' && c <= '9') {
  11807. val = (val * 10) + (long)(c - '0');
  11808. // val is actually 'unsigned long int' and can't get < 0
  11809. if (val < (rlim_t) 0)
  11810. break;
  11811. }
  11812. if (c)
  11813. ash_msg_and_raise_error("bad number");
  11814. val <<= l->factor_shift;
  11815. }
  11816. }
  11817. if (all) {
  11818. const char *lname = limits_name;
  11819. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  11820. getrlimit(l->cmd, &limit);
  11821. out1fmt("%-20s ", lname);
  11822. lname += strlen(lname) + 1;
  11823. printlim(how, &limit, l);
  11824. }
  11825. return 0;
  11826. }
  11827. getrlimit(l->cmd, &limit);
  11828. if (set) {
  11829. if (how & HARD)
  11830. limit.rlim_max = val;
  11831. if (how & SOFT)
  11832. limit.rlim_cur = val;
  11833. if (setrlimit(l->cmd, &limit) < 0)
  11834. ash_msg_and_raise_error("error setting limit (%m)");
  11835. } else {
  11836. printlim(how, &limit, l);
  11837. }
  11838. return 0;
  11839. }
  11840. /* ============ main() and helpers */
  11841. /*
  11842. * Called to exit the shell.
  11843. */
  11844. static void exitshell(void) NORETURN;
  11845. static void
  11846. exitshell(void)
  11847. {
  11848. struct jmploc loc;
  11849. char *p;
  11850. int status;
  11851. status = exitstatus;
  11852. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11853. if (setjmp(loc.loc)) {
  11854. if (exception_type == EXEXIT)
  11855. /* dash bug: it just does _exit(exitstatus) here
  11856. * but we have to do setjobctl(0) first!
  11857. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11858. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11859. status = exitstatus;
  11860. goto out;
  11861. }
  11862. exception_handler = &loc;
  11863. p = trap[0];
  11864. if (p) {
  11865. trap[0] = NULL;
  11866. evalstring(p, 0);
  11867. }
  11868. flush_stdout_stderr();
  11869. out:
  11870. setjobctl(0);
  11871. _exit(status);
  11872. /* NOTREACHED */
  11873. }
  11874. static void
  11875. init(void)
  11876. {
  11877. /* from input.c: */
  11878. basepf.next_to_pgetc = basepf.buf = basebuf;
  11879. /* from trap.c: */
  11880. signal(SIGCHLD, SIG_DFL);
  11881. /* from var.c: */
  11882. {
  11883. char **envp;
  11884. char ppid[sizeof(int)*3 + 1];
  11885. const char *p;
  11886. struct stat st1, st2;
  11887. initvar();
  11888. for (envp = environ; envp && *envp; envp++) {
  11889. if (strchr(*envp, '=')) {
  11890. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11891. }
  11892. }
  11893. snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
  11894. setvar("PPID", ppid, 0);
  11895. p = lookupvar("PWD");
  11896. if (p)
  11897. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11898. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  11899. p = '\0';
  11900. setpwd(p, 0);
  11901. }
  11902. }
  11903. /*
  11904. * Process the shell command line arguments.
  11905. */
  11906. static void
  11907. procargs(char **argv)
  11908. {
  11909. int i;
  11910. const char *xminusc;
  11911. char **xargv;
  11912. xargv = argv;
  11913. arg0 = xargv[0];
  11914. /* if (xargv[0]) - mmm, this is always true! */
  11915. xargv++;
  11916. for (i = 0; i < NOPTS; i++)
  11917. optlist[i] = 2;
  11918. argptr = xargv;
  11919. if (options(1)) {
  11920. /* it already printed err message */
  11921. raise_exception(EXERROR);
  11922. }
  11923. xargv = argptr;
  11924. xminusc = minusc;
  11925. if (*xargv == NULL) {
  11926. if (xminusc)
  11927. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11928. sflag = 1;
  11929. }
  11930. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11931. iflag = 1;
  11932. if (mflag == 2)
  11933. mflag = iflag;
  11934. for (i = 0; i < NOPTS; i++)
  11935. if (optlist[i] == 2)
  11936. optlist[i] = 0;
  11937. #if DEBUG == 2
  11938. debug = 1;
  11939. #endif
  11940. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11941. if (xminusc) {
  11942. minusc = *xargv++;
  11943. if (*xargv)
  11944. goto setarg0;
  11945. } else if (!sflag) {
  11946. setinputfile(*xargv, 0);
  11947. setarg0:
  11948. arg0 = *xargv++;
  11949. commandname = arg0;
  11950. }
  11951. shellparam.p = xargv;
  11952. #if ENABLE_ASH_GETOPTS
  11953. shellparam.optind = 1;
  11954. shellparam.optoff = -1;
  11955. #endif
  11956. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  11957. while (*xargv) {
  11958. shellparam.nparam++;
  11959. xargv++;
  11960. }
  11961. optschanged();
  11962. }
  11963. /*
  11964. * Read /etc/profile or .profile.
  11965. */
  11966. static void
  11967. read_profile(const char *name)
  11968. {
  11969. int skip;
  11970. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11971. return;
  11972. skip = cmdloop(0);
  11973. popfile();
  11974. if (skip)
  11975. exitshell();
  11976. }
  11977. /*
  11978. * This routine is called when an error or an interrupt occurs in an
  11979. * interactive shell and control is returned to the main command loop.
  11980. */
  11981. static void
  11982. reset(void)
  11983. {
  11984. /* from eval.c: */
  11985. evalskip = 0;
  11986. loopnest = 0;
  11987. /* from input.c: */
  11988. g_parsefile->left_in_buffer = 0;
  11989. g_parsefile->left_in_line = 0; /* clear input buffer */
  11990. popallfiles();
  11991. /* from parser.c: */
  11992. tokpushback = 0;
  11993. checkkwd = 0;
  11994. /* from redir.c: */
  11995. clearredir(/*drop:*/ 0);
  11996. }
  11997. #if PROFILE
  11998. static short profile_buf[16384];
  11999. extern int etext();
  12000. #endif
  12001. /*
  12002. * Main routine. We initialize things, parse the arguments, execute
  12003. * profiles if we're a login shell, and then call cmdloop to execute
  12004. * commands. The setjmp call sets up the location to jump to when an
  12005. * exception occurs. When an exception occurs the variable "state"
  12006. * is used to figure out how far we had gotten.
  12007. */
  12008. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12009. int ash_main(int argc UNUSED_PARAM, char **argv)
  12010. {
  12011. const char *shinit;
  12012. volatile smallint state;
  12013. struct jmploc jmploc;
  12014. struct stackmark smark;
  12015. /* Initialize global data */
  12016. INIT_G_misc();
  12017. INIT_G_memstack();
  12018. INIT_G_var();
  12019. #if ENABLE_ASH_ALIAS
  12020. INIT_G_alias();
  12021. #endif
  12022. INIT_G_cmdtable();
  12023. #if PROFILE
  12024. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12025. #endif
  12026. #if ENABLE_FEATURE_EDITING
  12027. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12028. #endif
  12029. state = 0;
  12030. if (setjmp(jmploc.loc)) {
  12031. smallint e;
  12032. smallint s;
  12033. reset();
  12034. e = exception_type;
  12035. if (e == EXERROR)
  12036. exitstatus = 2;
  12037. s = state;
  12038. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  12039. exitshell();
  12040. if (e == EXINT)
  12041. outcslow('\n', stderr);
  12042. popstackmark(&smark);
  12043. FORCE_INT_ON; /* enable interrupts */
  12044. if (s == 1)
  12045. goto state1;
  12046. if (s == 2)
  12047. goto state2;
  12048. if (s == 3)
  12049. goto state3;
  12050. goto state4;
  12051. }
  12052. exception_handler = &jmploc;
  12053. #if DEBUG
  12054. opentrace();
  12055. TRACE(("Shell args: "));
  12056. trace_puts_args(argv);
  12057. #endif
  12058. rootpid = getpid();
  12059. #if ENABLE_ASH_RANDOM_SUPPORT
  12060. /* Can use monotonic_ns() for better randomness but for now it is
  12061. * not used anywhere else in busybox... so avoid bloat */
  12062. random_galois_LFSR = random_LCG = rootpid + monotonic_us();
  12063. #endif
  12064. init();
  12065. setstackmark(&smark);
  12066. procargs(argv);
  12067. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12068. if (iflag) {
  12069. const char *hp = lookupvar("HISTFILE");
  12070. if (hp == NULL) {
  12071. hp = lookupvar("HOME");
  12072. if (hp != NULL) {
  12073. char *defhp = concat_path_file(hp, ".ash_history");
  12074. setvar("HISTFILE", defhp, 0);
  12075. free(defhp);
  12076. }
  12077. }
  12078. }
  12079. #endif
  12080. if (/* argv[0] && */ argv[0][0] == '-')
  12081. isloginsh = 1;
  12082. if (isloginsh) {
  12083. state = 1;
  12084. read_profile("/etc/profile");
  12085. state1:
  12086. state = 2;
  12087. read_profile(".profile");
  12088. }
  12089. state2:
  12090. state = 3;
  12091. if (
  12092. #ifndef linux
  12093. getuid() == geteuid() && getgid() == getegid() &&
  12094. #endif
  12095. iflag
  12096. ) {
  12097. shinit = lookupvar("ENV");
  12098. if (shinit != NULL && *shinit != '\0') {
  12099. read_profile(shinit);
  12100. }
  12101. }
  12102. state3:
  12103. state = 4;
  12104. if (minusc) {
  12105. /* evalstring pushes parsefile stack.
  12106. * Ensure we don't falsely claim that 0 (stdin)
  12107. * is one of stacked source fds.
  12108. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12109. if (!sflag)
  12110. g_parsefile->fd = -1;
  12111. evalstring(minusc, 0);
  12112. }
  12113. if (sflag || minusc == NULL) {
  12114. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12115. if (iflag) {
  12116. const char *hp = lookupvar("HISTFILE");
  12117. if (hp)
  12118. line_input_state->hist_file = hp;
  12119. }
  12120. #endif
  12121. state4: /* XXX ??? - why isn't this before the "if" statement */
  12122. cmdloop(1);
  12123. }
  12124. #if PROFILE
  12125. monitor(0);
  12126. #endif
  12127. #ifdef GPROF
  12128. {
  12129. extern void _mcleanup(void);
  12130. _mcleanup();
  12131. }
  12132. #endif
  12133. exitshell();
  12134. /* NOTREACHED */
  12135. }
  12136. /*-
  12137. * Copyright (c) 1989, 1991, 1993, 1994
  12138. * The Regents of the University of California. All rights reserved.
  12139. *
  12140. * This code is derived from software contributed to Berkeley by
  12141. * Kenneth Almquist.
  12142. *
  12143. * Redistribution and use in source and binary forms, with or without
  12144. * modification, are permitted provided that the following conditions
  12145. * are met:
  12146. * 1. Redistributions of source code must retain the above copyright
  12147. * notice, this list of conditions and the following disclaimer.
  12148. * 2. Redistributions in binary form must reproduce the above copyright
  12149. * notice, this list of conditions and the following disclaimer in the
  12150. * documentation and/or other materials provided with the distribution.
  12151. * 3. Neither the name of the University nor the names of its contributors
  12152. * may be used to endorse or promote products derived from this software
  12153. * without specific prior written permission.
  12154. *
  12155. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12156. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12157. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12158. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12159. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12160. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12161. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12162. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12163. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12164. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12165. * SUCH DAMAGE.
  12166. */