ash.c 280 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528
  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-2003 Herbert Xu <herbert@debian.org>
  9. * was re-ported from NetBSD and debianized.
  10. *
  11. *
  12. * This code is derived from software contributed to Berkeley by
  13. * Kenneth Almquist.
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 2 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. * General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program; if not, write to the Free Software
  27. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  28. *
  29. * Original BSD copyright notice is retained at the end of this file.
  30. */
  31. /*
  32. * rewrite arith.y to micro stack based cryptic algorithm by
  33. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  34. *
  35. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2003 to be
  36. * used in busybox and size optimizations,
  37. * support locale, rewrited arith (see notes to this)
  38. *
  39. */
  40. /*
  41. * The follow should be set to reflect the type of system you have:
  42. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  43. * define SYSV if you are running under System V.
  44. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  45. * define DEBUG=2 to compile in and turn on debugging.
  46. *
  47. * When debugging is on, debugging info will be written to ./trace and
  48. * a quit signal will generate a core dump.
  49. */
  50. /* This enables alias support in ash. If you want to support things
  51. * like "alias ls='ls -l'" with ash, enable this. This is only useful
  52. * when ash is used as an intractive shell. This adds about 1.5k */
  53. #define BB_ASH_ALIAS
  54. /* If you need ash to act as a full Posix shell, with full math
  55. * support, enable this. This adds a bit over 2k an x86 system. */
  56. #define BB_ASH_MATH_SUPPORT
  57. /* Getopts is used by shell procedures to parse positional parameters.
  58. * You probably want to leave this disabled, and use the busybox getopt
  59. * applet if you want to do this sort of thing. There are some scripts
  60. * out there that use it, so if you need it, enable it. Most people will
  61. * leave this disabled. This adds 1k on an x86 system. */
  62. #undef BB_ASH_GETOPTS
  63. /* This allows you to override shell builtins and use whatever is on
  64. * the filesystem. This is most useful when ash is acting as a
  65. * standalone shell. Adds about 272 bytes. */
  66. #undef BB_ASH_CMDCMD
  67. /* Check for mail */
  68. #undef BB_ASH_MAIL
  69. /* Optimize size vs speed as size */
  70. #define BB_ASH_OPTIMIZE_FOR_SIZE
  71. /* Enable this to compile in extra debugging noise. When debugging is
  72. * on, debugging info will be written to $HOME/trace and a quit signal
  73. * will generate a core dump. */
  74. #undef DEBUG
  75. #define IFS_BROKEN
  76. #define PROFILE 0
  77. #ifdef DEBUG
  78. #define _GNU_SOURCE
  79. #endif
  80. #include <sys/types.h>
  81. #include <sys/cdefs.h>
  82. #include <sys/ioctl.h>
  83. #include <sys/param.h>
  84. #include <sys/resource.h>
  85. #include <sys/stat.h>
  86. #include <sys/time.h>
  87. #include <sys/wait.h>
  88. #include <stdio.h>
  89. #include <stdlib.h>
  90. #include <string.h>
  91. #include <unistd.h>
  92. #include <stdarg.h>
  93. #include <stddef.h>
  94. #include <assert.h>
  95. #include <ctype.h>
  96. #include <dirent.h>
  97. #include <errno.h>
  98. #include <fcntl.h>
  99. #include <limits.h>
  100. #include <paths.h>
  101. #include <setjmp.h>
  102. #include <signal.h>
  103. #include <stdint.h>
  104. #include <sysexits.h>
  105. #include <fnmatch.h>
  106. #include "busybox.h"
  107. #include "pwd_grp/pwd.h"
  108. #ifdef BB_ASH_JOB_CONTROL
  109. #define JOBS 1
  110. #else
  111. #undef JOBS
  112. #endif
  113. #if JOBS
  114. #include <termios.h>
  115. #endif
  116. #include "cmdedit.h"
  117. #ifdef __GLIBC__
  118. /* glibc sucks */
  119. static int *dash_errno;
  120. #undef errno
  121. #define errno (*dash_errno)
  122. #endif
  123. #if defined(__uClinux__)
  124. #error "Do not even bother, ash will not run on uClinux"
  125. #endif
  126. #ifdef DEBUG
  127. #define _DIAGASSERT(assert_expr) assert(assert_expr)
  128. #else
  129. #define _DIAGASSERT(assert_expr)
  130. #endif
  131. #ifdef BB_ASH_ALIAS
  132. /* $NetBSD: alias.h,v 1.5 2002/11/24 22:35:38 christos Exp $ */
  133. #define ALIASINUSE 1
  134. #define ALIASDEAD 2
  135. struct alias {
  136. struct alias *next;
  137. char *name;
  138. char *val;
  139. int flag;
  140. };
  141. static struct alias *lookupalias(const char *, int);
  142. static int aliascmd(int, char **);
  143. static int unaliascmd(int, char **);
  144. static void rmaliases(void);
  145. static int unalias(const char *);
  146. static void printalias(const struct alias *);
  147. #endif
  148. /* $NetBSD: cd.h,v 1.3 2002/11/24 22:35:39 christos Exp $ */
  149. static void setpwd(const char *, int);
  150. /* $NetBSD: error.h,v 1.15 2002/11/24 22:35:39 christos Exp $ */
  151. /*
  152. * Types of operations (passed to the errmsg routine).
  153. */
  154. static const char not_found_msg[] = "%s: not found";
  155. #define E_OPEN "No such file" /* opening a file */
  156. #define E_CREAT "Directory nonexistent" /* creating a file */
  157. #define E_EXEC not_found_msg+4 /* executing a program */
  158. /*
  159. * We enclose jmp_buf in a structure so that we can declare pointers to
  160. * jump locations. The global variable handler contains the location to
  161. * jump to when an exception occurs, and the global variable exception
  162. * contains a code identifying the exeception. To implement nested
  163. * exception handlers, the user should save the value of handler on entry
  164. * to an inner scope, set handler to point to a jmploc structure for the
  165. * inner scope, and restore handler on exit from the scope.
  166. */
  167. struct jmploc {
  168. jmp_buf loc;
  169. };
  170. static struct jmploc *handler;
  171. static int exception;
  172. static volatile int suppressint;
  173. static volatile sig_atomic_t intpending;
  174. static int exerrno; /* Last exec error, error for EXEXEC */
  175. /* exceptions */
  176. #define EXINT 0 /* SIGINT received */
  177. #define EXERROR 1 /* a generic error */
  178. #define EXSHELLPROC 2 /* execute a shell procedure */
  179. #define EXEXEC 3 /* command execution failed */
  180. #define EXEXIT 4 /* exit the shell */
  181. #define EXSIG 5 /* trapped signal in wait(1) */
  182. /* do we generate EXSIG events */
  183. static int exsig;
  184. /* last pending signal */
  185. static volatile sig_atomic_t pendingsigs;
  186. /*
  187. * These macros allow the user to suspend the handling of interrupt signals
  188. * over a period of time. This is similar to SIGHOLD to or sigblock, but
  189. * much more efficient and portable. (But hacking the kernel is so much
  190. * more fun than worrying about efficiency and portability. :-))
  191. */
  192. #define barrier() ({ __asm__ __volatile__ ("": : :"memory"); })
  193. #define INTOFF \
  194. ({ \
  195. suppressint++; \
  196. barrier(); \
  197. 0; \
  198. })
  199. #define SAVEINT(v) ((v) = suppressint)
  200. #define RESTOREINT(v) \
  201. ({ \
  202. barrier(); \
  203. if ((suppressint = (v)) == 0 && intpending) onint(); \
  204. 0; \
  205. })
  206. #define EXSIGON() \
  207. ({ \
  208. exsig++; \
  209. barrier(); \
  210. if (pendingsigs) \
  211. exraise(EXSIG); \
  212. 0; \
  213. })
  214. /* EXSIG is turned off by evalbltin(). */
  215. static void exraise(int) __attribute__((__noreturn__));
  216. static void onint(void) __attribute__((__noreturn__));
  217. static void error(const char *, ...) __attribute__((__noreturn__));
  218. static void exerror(int, const char *, ...) __attribute__((__noreturn__));
  219. static void sh_warnx(const char *, ...);
  220. #ifdef BB_ASH_OPTIMIZE_FOR_SIZE
  221. static void
  222. inton(void) {
  223. if (--suppressint == 0 && intpending) {
  224. onint();
  225. }
  226. }
  227. #define INTON inton()
  228. static void forceinton(void)
  229. {
  230. suppressint = 0;
  231. if (intpending)
  232. onint();
  233. }
  234. #define FORCEINTON forceinton()
  235. #else
  236. #define INTON \
  237. ({ \
  238. barrier(); \
  239. if (--suppressint == 0 && intpending) onint(); \
  240. 0; \
  241. })
  242. #define FORCEINTON \
  243. ({ \
  244. barrier(); \
  245. suppressint = 0; \
  246. if (intpending) onint(); \
  247. 0; \
  248. })
  249. #endif /* BB_ASH_OPTIMIZE_FOR_SIZE */
  250. /*
  251. * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
  252. * so we use _setjmp instead.
  253. */
  254. #if defined(BSD) && !defined(__SVR4) && !defined(__GLIBC__)
  255. #define setjmp(jmploc) _setjmp(jmploc)
  256. #define longjmp(jmploc, val) _longjmp(jmploc, val)
  257. #endif
  258. /* $NetBSD: expand.h,v 1.13 2002/11/24 22:35:40 christos Exp $ */
  259. struct strlist {
  260. struct strlist *next;
  261. char *text;
  262. };
  263. struct arglist {
  264. struct strlist *list;
  265. struct strlist **lastp;
  266. };
  267. /*
  268. * expandarg() flags
  269. */
  270. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  271. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  272. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  273. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  274. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  275. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  276. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  277. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  278. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  279. union node;
  280. static void expandarg(union node *, struct arglist *, int);
  281. #define rmescapes(p) _rmescapes((p), 0)
  282. static char *_rmescapes(char *, int);
  283. static int casematch(union node *, char *);
  284. #ifdef BB_ASH_MATH_SUPPORT
  285. static void expari(int);
  286. #endif
  287. /* $NetBSD: eval.h,v 1.13 2002/11/24 22:35:39 christos Exp $ */
  288. static char *commandname; /* currently executing command */
  289. static struct strlist *cmdenviron; /* environment for builtin command */
  290. static int exitstatus; /* exit status of last command */
  291. static int back_exitstatus; /* exit status of backquoted command */
  292. struct backcmd { /* result of evalbackcmd */
  293. int fd; /* file descriptor to read from */
  294. char *buf; /* buffer */
  295. int nleft; /* number of chars in buffer */
  296. struct job *jp; /* job structure for command */
  297. };
  298. /*
  299. * This file was generated by the mknodes program.
  300. */
  301. #define NCMD 0
  302. #define NPIPE 1
  303. #define NREDIR 2
  304. #define NBACKGND 3
  305. #define NSUBSHELL 4
  306. #define NAND 5
  307. #define NOR 6
  308. #define NSEMI 7
  309. #define NIF 8
  310. #define NWHILE 9
  311. #define NUNTIL 10
  312. #define NFOR 11
  313. #define NCASE 12
  314. #define NCLIST 13
  315. #define NDEFUN 14
  316. #define NARG 15
  317. #define NTO 16
  318. #define NCLOBBER 17
  319. #define NFROM 18
  320. #define NFROMTO 19
  321. #define NAPPEND 20
  322. #define NTOFD 21
  323. #define NFROMFD 22
  324. #define NHERE 23
  325. #define NXHERE 24
  326. #define NNOT 25
  327. struct ncmd {
  328. int type;
  329. union node *assign;
  330. union node *args;
  331. union node *redirect;
  332. };
  333. struct npipe {
  334. int type;
  335. int backgnd;
  336. struct nodelist *cmdlist;
  337. };
  338. struct nredir {
  339. int type;
  340. union node *n;
  341. union node *redirect;
  342. };
  343. struct nbinary {
  344. int type;
  345. union node *ch1;
  346. union node *ch2;
  347. };
  348. struct nif {
  349. int type;
  350. union node *test;
  351. union node *ifpart;
  352. union node *elsepart;
  353. };
  354. struct nfor {
  355. int type;
  356. union node *args;
  357. union node *body;
  358. char *var;
  359. };
  360. struct ncase {
  361. int type;
  362. union node *expr;
  363. union node *cases;
  364. };
  365. struct nclist {
  366. int type;
  367. union node *next;
  368. union node *pattern;
  369. union node *body;
  370. };
  371. struct narg {
  372. int type;
  373. union node *next;
  374. char *text;
  375. struct nodelist *backquote;
  376. };
  377. struct nfile {
  378. int type;
  379. union node *next;
  380. int fd;
  381. union node *fname;
  382. char *expfname;
  383. };
  384. struct ndup {
  385. int type;
  386. union node *next;
  387. int fd;
  388. int dupfd;
  389. union node *vname;
  390. };
  391. struct nhere {
  392. int type;
  393. union node *next;
  394. int fd;
  395. union node *doc;
  396. };
  397. struct nnot {
  398. int type;
  399. union node *com;
  400. };
  401. union node {
  402. int type;
  403. struct ncmd ncmd;
  404. struct npipe npipe;
  405. struct nredir nredir;
  406. struct nbinary nbinary;
  407. struct nif nif;
  408. struct nfor nfor;
  409. struct ncase ncase;
  410. struct nclist nclist;
  411. struct narg narg;
  412. struct nfile nfile;
  413. struct ndup ndup;
  414. struct nhere nhere;
  415. struct nnot nnot;
  416. };
  417. struct nodelist {
  418. struct nodelist *next;
  419. union node *n;
  420. };
  421. struct funcnode {
  422. int count;
  423. union node n;
  424. };
  425. static void freefunc(struct funcnode *);
  426. /* $NetBSD: parser.h,v 1.15 2002/11/24 22:35:42 christos Exp $ */
  427. /* control characters in argument strings */
  428. #define CTL_FIRST '\201' /* first 'special' character */
  429. #define CTLESC '\201' /* escape next character */
  430. #define CTLVAR '\202' /* variable defn */
  431. #define CTLENDVAR '\203'
  432. #define CTLBACKQ '\204'
  433. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  434. /* CTLBACKQ | CTLQUOTE == '\205' */
  435. #define CTLARI '\206' /* arithmetic expression */
  436. #define CTLENDARI '\207'
  437. #define CTLQUOTEMARK '\210'
  438. #define CTL_LAST '\210' /* last 'special' character */
  439. /* variable substitution byte (follows CTLVAR) */
  440. #define VSTYPE 0x0f /* type of variable substitution */
  441. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  442. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  443. /* values of VSTYPE field */
  444. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  445. #define VSMINUS 0x2 /* ${var-text} */
  446. #define VSPLUS 0x3 /* ${var+text} */
  447. #define VSQUESTION 0x4 /* ${var?message} */
  448. #define VSASSIGN 0x5 /* ${var=text} */
  449. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  450. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  451. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  452. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  453. #define VSLENGTH 0xa /* ${#var} */
  454. /* values of checkkwd variable */
  455. #define CHKALIAS 0x1
  456. #define CHKKWD 0x2
  457. #define CHKNL 0x4
  458. #define IBUFSIZ (BUFSIZ + 1)
  459. /*
  460. * NEOF is returned by parsecmd when it encounters an end of file. It
  461. * must be distinct from NULL, so we use the address of a variable that
  462. * happens to be handy.
  463. */
  464. static int plinno = 1; /* input line number */
  465. /* number of characters left in input buffer */
  466. static int parsenleft; /* copy of parsefile->nleft */
  467. static int parselleft; /* copy of parsefile->lleft */
  468. /* next character in input buffer */
  469. static char *parsenextc; /* copy of parsefile->nextc */
  470. struct strpush {
  471. struct strpush *prev; /* preceding string on stack */
  472. char *prevstring;
  473. int prevnleft;
  474. #ifdef BB_ASH_ALIAS
  475. struct alias *ap; /* if push was associated with an alias */
  476. #endif
  477. char *string; /* remember the string since it may change */
  478. };
  479. struct parsefile {
  480. struct parsefile *prev; /* preceding file on stack */
  481. int linno; /* current line */
  482. int fd; /* file descriptor (or -1 if string) */
  483. int nleft; /* number of chars left in this line */
  484. int lleft; /* number of chars left in this buffer */
  485. char *nextc; /* next char in buffer */
  486. char *buf; /* input buffer */
  487. struct strpush *strpush; /* for pushing strings at this level */
  488. struct strpush basestrpush; /* so pushing one is fast */
  489. };
  490. static struct parsefile basepf; /* top level input file */
  491. static char basebuf[IBUFSIZ]; /* buffer for top level input file */
  492. static struct parsefile *parsefile = &basepf; /* current input file */
  493. static int tokpushback; /* last token pushed back */
  494. #define NEOF ((union node *)&tokpushback)
  495. static int parsebackquote; /* nonzero if we are inside backquotes */
  496. static int doprompt; /* if set, prompt the user */
  497. static int needprompt; /* true if interactive and at start of line */
  498. static int lasttoken; /* last token read */
  499. static char *wordtext; /* text of last word returned by readtoken */
  500. static int checkkwd;
  501. static struct nodelist *backquotelist;
  502. static union node *redirnode;
  503. static struct heredoc *heredoc;
  504. static int quoteflag; /* set if (part of) last token was quoted */
  505. static int startlinno; /* line # where last token started */
  506. static union node *parsecmd(int);
  507. static void fixredir(union node *, const char *, int);
  508. static const char *const *findkwd(const char *);
  509. static char *endofname(const char *);
  510. /* $NetBSD: shell.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
  511. typedef void *pointer;
  512. static char nullstr[1]; /* zero length string */
  513. static const char spcstr[] = " ";
  514. static const char snlfmt[] = "%s\n";
  515. static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
  516. static const char illnum[] = "Illegal number: %s";
  517. static const char homestr[] = "HOME";
  518. #ifdef DEBUG
  519. #define TRACE(param) trace param
  520. #define TRACEV(param) tracev param
  521. #else
  522. #define TRACE(param)
  523. #define TRACEV(param)
  524. #endif
  525. #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
  526. #define __builtin_expect(x, expected_value) (x)
  527. #endif
  528. #define likely(x) __builtin_expect((x),1)
  529. #define TEOF 0
  530. #define TNL 1
  531. #define TREDIR 2
  532. #define TWORD 3
  533. #define TSEMI 4
  534. #define TBACKGND 5
  535. #define TAND 6
  536. #define TOR 7
  537. #define TPIPE 8
  538. #define TLP 9
  539. #define TRP 10
  540. #define TENDCASE 11
  541. #define TENDBQUOTE 12
  542. #define TNOT 13
  543. #define TCASE 14
  544. #define TDO 15
  545. #define TDONE 16
  546. #define TELIF 17
  547. #define TELSE 18
  548. #define TESAC 19
  549. #define TFI 20
  550. #define TFOR 21
  551. #define TIF 22
  552. #define TIN 23
  553. #define TTHEN 24
  554. #define TUNTIL 25
  555. #define TWHILE 26
  556. #define TBEGIN 27
  557. #define TEND 28
  558. /* first char is indicating which tokens mark the end of a list */
  559. static const char *const tokname_array[] = {
  560. "\1end of file",
  561. "\0newline",
  562. "\0redirection",
  563. "\0word",
  564. "\0;",
  565. "\0&",
  566. "\0&&",
  567. "\0||",
  568. "\0|",
  569. "\0(",
  570. "\1)",
  571. "\1;;",
  572. "\1`",
  573. #define KWDOFFSET 13
  574. /* the following are keywords */
  575. "\0!",
  576. "\0case",
  577. "\1do",
  578. "\1done",
  579. "\1elif",
  580. "\1else",
  581. "\1esac",
  582. "\1fi",
  583. "\0for",
  584. "\0if",
  585. "\0in",
  586. "\1then",
  587. "\0until",
  588. "\0while",
  589. "\0{",
  590. "\1}",
  591. };
  592. static const char *tokname(int tok)
  593. {
  594. static char buf[16];
  595. if (tok >= TSEMI)
  596. buf[0] = '"';
  597. sprintf(buf + (tok >= TSEMI), "%s%c",
  598. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  599. return buf;
  600. }
  601. /* $NetBSD: machdep.h,v 1.10 2002/10/07 14:26:08 christos Exp $ */
  602. /*
  603. * Most machines require the value returned from malloc to be aligned
  604. * in some way. The following macro will get this right on many machines.
  605. */
  606. #define SHELL_SIZE (sizeof(union {int i; char *cp; double d; }) - 1)
  607. /*
  608. * It appears that grabstackstr() will barf with such alignments
  609. * because stalloc() will return a string allocated in a new stackblock.
  610. */
  611. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  612. /*
  613. * This file was generated by the mksyntax program.
  614. */
  615. /* Syntax classes */
  616. #define CWORD 0 /* character is nothing special */
  617. #define CNL 1 /* newline character */
  618. #define CBACK 2 /* a backslash character */
  619. #define CSQUOTE 3 /* single quote */
  620. #define CDQUOTE 4 /* double quote */
  621. #define CENDQUOTE 5 /* a terminating quote */
  622. #define CBQUOTE 6 /* backwards single quote */
  623. #define CVAR 7 /* a dollar sign */
  624. #define CENDVAR 8 /* a '}' character */
  625. #define CLP 9 /* a left paren in arithmetic */
  626. #define CRP 10 /* a right paren in arithmetic */
  627. #define CENDFILE 11 /* end of file */
  628. #define CCTL 12 /* like CWORD, except it must be escaped */
  629. #define CSPCL 13 /* these terminate a word */
  630. #define CIGN 14 /* character should be ignored */
  631. #ifdef BB_ASH_ALIAS
  632. #define SYNBASE 130
  633. #define PEOF -130
  634. #define PEOA -129
  635. #define PEOA_OR_PEOF PEOA
  636. #else
  637. #define SYNBASE 129
  638. #define PEOF -129
  639. #define PEOA_OR_PEOF PEOF
  640. #endif
  641. #define is_digit(c) ((unsigned)((c) - '0') <= 9)
  642. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  643. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  644. /*
  645. * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  646. * (assuming ascii char codes, as the original implementation did)
  647. */
  648. #define is_special(c) \
  649. ( (((unsigned int)c) - 33 < 32) \
  650. && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
  651. #define digit_val(c) ((c) - '0')
  652. /*
  653. * This file was generated by the mksyntax program.
  654. */
  655. #ifdef BB_ASH_OPTIMIZE_FOR_SIZE
  656. #define USE_SIT_FUNCTION
  657. #endif
  658. /* number syntax index */
  659. #define BASESYNTAX 0 /* not in quotes */
  660. #define DQSYNTAX 1 /* in double quotes */
  661. #define SQSYNTAX 2 /* in single quotes */
  662. #define ARISYNTAX 3 /* in arithmetic */
  663. #ifdef BB_ASH_MATH_SUPPORT
  664. static const char S_I_T[][4] = {
  665. #ifdef BB_ASH_ALIAS
  666. {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
  667. #endif
  668. {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
  669. {CNL, CNL, CNL, CNL}, /* 2, \n */
  670. {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
  671. {CDQUOTE, CENDQUOTE, CWORD, CWORD}, /* 4, '"' */
  672. {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
  673. {CSQUOTE, CWORD, CENDQUOTE, CWORD}, /* 6, "'" */
  674. {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
  675. {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
  676. {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
  677. {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
  678. {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
  679. #ifndef USE_SIT_FUNCTION
  680. {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
  681. {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
  682. {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
  683. #endif
  684. };
  685. #else
  686. static const char S_I_T[][3] = {
  687. #ifdef BB_ASH_ALIAS
  688. {CSPCL, CIGN, CIGN}, /* 0, PEOA */
  689. #endif
  690. {CSPCL, CWORD, CWORD}, /* 1, ' ' */
  691. {CNL, CNL, CNL}, /* 2, \n */
  692. {CWORD, CCTL, CCTL}, /* 3, !*-/:=?[]~ */
  693. {CDQUOTE, CENDQUOTE, CWORD}, /* 4, '"' */
  694. {CVAR, CVAR, CWORD}, /* 5, $ */
  695. {CSQUOTE, CWORD, CENDQUOTE}, /* 6, "'" */
  696. {CSPCL, CWORD, CWORD}, /* 7, ( */
  697. {CSPCL, CWORD, CWORD}, /* 8, ) */
  698. {CBACK, CBACK, CCTL}, /* 9, \ */
  699. {CBQUOTE, CBQUOTE, CWORD}, /* 10, ` */
  700. {CENDVAR, CENDVAR, CWORD}, /* 11, } */
  701. #ifndef USE_SIT_FUNCTION
  702. {CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
  703. {CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
  704. {CCTL, CCTL, CCTL} /* 14, CTLESC ... */
  705. #endif
  706. };
  707. #endif /* BB_ASH_MATH_SUPPORT */
  708. #ifdef USE_SIT_FUNCTION
  709. #define U_C(c) ((unsigned char)(c))
  710. static int SIT(int c, int syntax)
  711. {
  712. static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  713. #ifdef BB_ASH_ALIAS
  714. static const char syntax_index_table[] = {
  715. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  716. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  717. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  718. 11, 3 /* "}~" */
  719. };
  720. #else
  721. static const char syntax_index_table[] = {
  722. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  723. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  724. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  725. 10, 2 /* "}~" */
  726. };
  727. #endif
  728. const char *s;
  729. int indx;
  730. if (c == PEOF) /* 2^8+2 */
  731. return CENDFILE;
  732. #ifdef BB_ASH_ALIAS
  733. if (c == PEOA) /* 2^8+1 */
  734. indx = 0;
  735. else
  736. #endif
  737. if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
  738. return CCTL;
  739. else {
  740. s = strchr(spec_symbls, c);
  741. if (s == 0 || *s == 0)
  742. return CWORD;
  743. indx = syntax_index_table[(s - spec_symbls)];
  744. }
  745. return S_I_T[indx][syntax];
  746. }
  747. #else /* USE_SIT_FUNCTION */
  748. #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
  749. #ifdef BB_ASH_ALIAS
  750. #define CSPCL_CIGN_CIGN_CIGN 0
  751. #define CSPCL_CWORD_CWORD_CWORD 1
  752. #define CNL_CNL_CNL_CNL 2
  753. #define CWORD_CCTL_CCTL_CWORD 3
  754. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  755. #define CVAR_CVAR_CWORD_CVAR 5
  756. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  757. #define CSPCL_CWORD_CWORD_CLP 7
  758. #define CSPCL_CWORD_CWORD_CRP 8
  759. #define CBACK_CBACK_CCTL_CBACK 9
  760. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  761. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  762. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  763. #define CWORD_CWORD_CWORD_CWORD 13
  764. #define CCTL_CCTL_CCTL_CCTL 14
  765. #else
  766. #define CSPCL_CWORD_CWORD_CWORD 0
  767. #define CNL_CNL_CNL_CNL 1
  768. #define CWORD_CCTL_CCTL_CWORD 2
  769. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  770. #define CVAR_CVAR_CWORD_CVAR 4
  771. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  772. #define CSPCL_CWORD_CWORD_CLP 6
  773. #define CSPCL_CWORD_CWORD_CRP 7
  774. #define CBACK_CBACK_CCTL_CBACK 8
  775. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  776. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  777. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  778. #define CWORD_CWORD_CWORD_CWORD 12
  779. #define CCTL_CCTL_CCTL_CCTL 13
  780. #endif
  781. static const char syntax_index_table[258] = {
  782. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  783. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  784. #ifdef BB_ASH_ALIAS
  785. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  786. #endif
  787. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  788. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  789. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  790. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  791. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  792. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  793. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  794. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  795. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  796. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  797. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  798. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  799. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  800. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  801. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  802. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  803. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  804. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  805. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  806. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  807. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  808. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  809. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  810. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  811. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  812. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  813. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  814. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  815. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  816. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  817. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  818. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  819. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  820. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  821. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  822. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  823. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  824. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  825. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  826. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  827. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  828. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  829. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  830. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  831. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  832. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  833. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  834. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  835. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  836. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  837. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  838. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  839. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  840. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  841. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  842. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  843. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  844. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  845. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  846. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  847. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  848. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  849. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  850. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  851. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  852. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  853. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  854. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  855. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  856. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  857. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  858. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  859. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  860. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  861. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  862. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  863. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  864. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  865. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  866. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  867. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  868. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  869. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  870. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  871. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  872. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  873. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  874. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  875. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  876. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  877. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  878. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  879. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  880. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  881. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  882. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  883. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  884. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  885. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  886. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  887. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  888. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  889. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  890. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  891. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  892. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  893. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  894. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  895. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  896. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  897. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  898. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  899. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  900. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  901. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  902. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  903. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  904. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  905. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  906. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  907. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  908. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  909. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  910. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  911. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  912. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  913. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  914. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  915. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  916. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  917. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  918. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  919. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  920. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  921. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  922. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  923. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  924. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  925. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  926. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  927. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  928. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  929. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  930. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  931. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  932. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  933. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  934. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  935. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  936. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  937. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  938. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  939. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  940. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  941. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  942. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  943. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  944. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  945. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  946. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  947. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  948. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  949. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  950. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  951. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  952. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  953. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  954. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  955. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  956. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  957. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  958. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  959. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  960. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  961. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  962. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  963. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  964. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  965. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  966. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  967. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  968. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  969. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  970. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  971. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  972. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  973. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  974. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  975. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  976. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  977. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  978. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  979. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  980. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  981. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  982. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  983. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  984. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  985. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  986. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  987. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  988. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  989. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  990. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  991. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  992. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  993. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  994. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  995. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  996. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  997. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  998. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  999. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  1000. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  1001. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  1002. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  1003. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  1004. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  1005. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  1006. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  1007. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  1008. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  1009. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  1010. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  1011. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  1012. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  1013. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  1014. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  1015. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  1016. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  1017. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  1018. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  1019. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  1020. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  1021. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  1022. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  1023. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  1024. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  1025. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  1026. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  1027. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  1028. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  1029. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  1030. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  1031. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  1032. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  1033. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  1034. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  1035. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  1036. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  1037. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  1038. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  1039. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  1040. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  1041. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  1042. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  1043. };
  1044. #endif /* USE_SIT_FUNCTION */
  1045. /* $NetBSD: alias.c,v 1.11 2002/11/24 22:35:38 christos Exp $ */
  1046. #define ATABSIZE 39
  1047. static int funcblocksize; /* size of structures in function */
  1048. static int funcstringsize; /* size of strings in node */
  1049. static pointer funcblock; /* block to allocate function from */
  1050. static char *funcstring; /* block to allocate strings from */
  1051. static const short nodesize[26] = {
  1052. SHELL_ALIGN(sizeof (struct ncmd)),
  1053. SHELL_ALIGN(sizeof (struct npipe)),
  1054. SHELL_ALIGN(sizeof (struct nredir)),
  1055. SHELL_ALIGN(sizeof (struct nredir)),
  1056. SHELL_ALIGN(sizeof (struct nredir)),
  1057. SHELL_ALIGN(sizeof (struct nbinary)),
  1058. SHELL_ALIGN(sizeof (struct nbinary)),
  1059. SHELL_ALIGN(sizeof (struct nbinary)),
  1060. SHELL_ALIGN(sizeof (struct nif)),
  1061. SHELL_ALIGN(sizeof (struct nbinary)),
  1062. SHELL_ALIGN(sizeof (struct nbinary)),
  1063. SHELL_ALIGN(sizeof (struct nfor)),
  1064. SHELL_ALIGN(sizeof (struct ncase)),
  1065. SHELL_ALIGN(sizeof (struct nclist)),
  1066. SHELL_ALIGN(sizeof (struct narg)),
  1067. SHELL_ALIGN(sizeof (struct narg)),
  1068. SHELL_ALIGN(sizeof (struct nfile)),
  1069. SHELL_ALIGN(sizeof (struct nfile)),
  1070. SHELL_ALIGN(sizeof (struct nfile)),
  1071. SHELL_ALIGN(sizeof (struct nfile)),
  1072. SHELL_ALIGN(sizeof (struct nfile)),
  1073. SHELL_ALIGN(sizeof (struct ndup)),
  1074. SHELL_ALIGN(sizeof (struct ndup)),
  1075. SHELL_ALIGN(sizeof (struct nhere)),
  1076. SHELL_ALIGN(sizeof (struct nhere)),
  1077. SHELL_ALIGN(sizeof (struct nnot)),
  1078. };
  1079. static void calcsize(union node *);
  1080. static void sizenodelist(struct nodelist *);
  1081. static union node *copynode(union node *);
  1082. static struct nodelist *copynodelist(struct nodelist *);
  1083. static char *nodesavestr(char *);
  1084. static void evalstring(char *, int);
  1085. union node; /* BLETCH for ansi C */
  1086. static void evaltree(union node *, int);
  1087. static void evalbackcmd(union node *, struct backcmd *);
  1088. /* in_function returns nonzero if we are currently evaluating a function */
  1089. #define in_function() funcnest
  1090. static int evalskip; /* set if we are skipping commands */
  1091. static int skipcount; /* number of levels to skip */
  1092. static int funcnest; /* depth of function calls */
  1093. /* reasons for skipping commands (see comment on breakcmd routine) */
  1094. #define SKIPBREAK 1
  1095. #define SKIPCONT 2
  1096. #define SKIPFUNC 3
  1097. #define SKIPFILE 4
  1098. /*
  1099. * This file was generated by the mkbuiltins program.
  1100. */
  1101. #ifdef JOBS
  1102. static int bgcmd(int, char **);
  1103. #endif
  1104. static int breakcmd(int, char **);
  1105. static int cdcmd(int, char **);
  1106. #ifdef BB_ASH_CMDCMD
  1107. static int commandcmd(int, char **);
  1108. #endif
  1109. static int dotcmd(int, char **);
  1110. static int evalcmd(int, char **);
  1111. static int execcmd(int, char **);
  1112. static int exitcmd(int, char **);
  1113. static int exportcmd(int, char **);
  1114. static int falsecmd(int, char **);
  1115. #ifdef JOBS
  1116. static int fgcmd(int, char **);
  1117. #endif
  1118. #ifdef BB_ASH_GETOPTS
  1119. static int getoptscmd(int, char **);
  1120. #endif
  1121. static int hashcmd(int, char **);
  1122. #ifndef BB_FEATURE_SH_EXTRA_QUIET
  1123. static int helpcmd(int argc, char **argv);
  1124. #endif
  1125. #ifdef JOBS
  1126. static int jobscmd(int, char **);
  1127. #endif
  1128. #ifdef BB_ASH_MATH_SUPPORT
  1129. static int letcmd(int, char **);
  1130. #endif
  1131. static int localcmd(int, char **);
  1132. static int pwdcmd(int, char **);
  1133. static int readcmd(int, char **);
  1134. static int returncmd(int, char **);
  1135. static int setcmd(int, char **);
  1136. static int shiftcmd(int, char **);
  1137. static int timescmd(int, char **);
  1138. static int trapcmd(int, char **);
  1139. static int truecmd(int, char **);
  1140. static int typecmd(int, char **);
  1141. static int umaskcmd(int, char **);
  1142. static int unsetcmd(int, char **);
  1143. static int waitcmd(int, char **);
  1144. static int ulimitcmd(int, char **);
  1145. #ifdef JOBS
  1146. static int killcmd(int, char **);
  1147. #endif
  1148. /* $NetBSD: mail.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
  1149. #ifdef BB_ASH_MAIL
  1150. static void chkmail(void);
  1151. static void changemail(const char *);
  1152. #endif
  1153. /* $NetBSD: exec.h,v 1.20 2003/01/22 20:36:04 dsl Exp $ */
  1154. /* values of cmdtype */
  1155. #define CMDUNKNOWN -1 /* no entry in table for command */
  1156. #define CMDNORMAL 0 /* command is an executable program */
  1157. #define CMDFUNCTION 1 /* command is a shell function */
  1158. #define CMDBUILTIN 2 /* command is a shell builtin */
  1159. struct builtincmd {
  1160. const char *name;
  1161. int (*builtin)(int, char **);
  1162. /* unsigned flags; */
  1163. };
  1164. #ifdef BB_ASH_CMDCMD
  1165. # ifdef JOBS
  1166. # ifdef BB_ASH_ALIAS
  1167. # define COMMANDCMD (builtincmd + 7)
  1168. # define EXECCMD (builtincmd + 10)
  1169. # else
  1170. # define COMMANDCMD (builtincmd + 6)
  1171. # define EXECCMD (builtincmd + 9)
  1172. # endif
  1173. # else /* ! JOBS */
  1174. # ifdef BB_ASH_ALIAS
  1175. # define COMMANDCMD (builtincmd + 6)
  1176. # define EXECCMD (builtincmd + 9)
  1177. # else
  1178. # define COMMANDCMD (builtincmd + 5)
  1179. # define EXECCMD (builtincmd + 8)
  1180. # endif
  1181. # endif /* JOBS */
  1182. #else /* ! BB_ASH_CMDCMD */
  1183. # ifdef JOBS
  1184. # ifdef BB_ASH_ALIAS
  1185. # define EXECCMD (builtincmd + 9)
  1186. # else
  1187. # define EXECCMD (builtincmd + 8)
  1188. # endif
  1189. # else /* ! JOBS */
  1190. # ifdef BB_ASH_ALIAS
  1191. # define EXECCMD (builtincmd + 8)
  1192. # else
  1193. # define EXECCMD (builtincmd + 7)
  1194. # endif
  1195. # endif /* JOBS */
  1196. #endif /* BB_ASH_CMDCMD */
  1197. #define BUILTIN_NOSPEC "0"
  1198. #define BUILTIN_SPECIAL "1"
  1199. #define BUILTIN_REGULAR "2"
  1200. #define BUILTIN_SPEC_REG "3"
  1201. #define BUILTIN_ASSIGN "4"
  1202. #define BUILTIN_SPEC_ASSG "5"
  1203. #define BUILTIN_REG_ASSG "6"
  1204. #define BUILTIN_SPEC_REG_ASSG "7"
  1205. #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
  1206. #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
  1207. static const struct builtincmd builtincmd[] = {
  1208. { BUILTIN_SPEC_REG ".", dotcmd },
  1209. { BUILTIN_SPEC_REG ":", truecmd },
  1210. #ifdef BB_ASH_ALIAS
  1211. { BUILTIN_REG_ASSG "alias", aliascmd },
  1212. #endif
  1213. #ifdef JOBS
  1214. { BUILTIN_REGULAR "bg", bgcmd },
  1215. #endif
  1216. { BUILTIN_SPEC_REG "break", breakcmd },
  1217. { BUILTIN_REGULAR "cd", cdcmd },
  1218. { BUILTIN_NOSPEC "chdir", cdcmd },
  1219. #ifdef BB_ASH_CMDCMD
  1220. { BUILTIN_REGULAR "command", commandcmd },
  1221. #endif
  1222. { BUILTIN_SPEC_REG "continue", breakcmd },
  1223. { BUILTIN_SPEC_REG "eval", evalcmd },
  1224. { BUILTIN_SPEC_REG "exec", execcmd },
  1225. { BUILTIN_SPEC_REG "exit", exitcmd },
  1226. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  1227. { BUILTIN_REGULAR "false", falsecmd },
  1228. #ifdef JOBS
  1229. { BUILTIN_REGULAR "fg", fgcmd },
  1230. #endif
  1231. #ifdef BB_ASH_GETOPTS
  1232. { BUILTIN_REGULAR "getopts", getoptscmd },
  1233. #endif
  1234. { BUILTIN_NOSPEC "hash", hashcmd },
  1235. #ifndef BB_FEATURE_SH_EXTRA_QUIET
  1236. { BUILTIN_NOSPEC "help", helpcmd },
  1237. #endif
  1238. #ifdef JOBS
  1239. { BUILTIN_REGULAR "jobs", jobscmd },
  1240. { BUILTIN_REGULAR "kill", killcmd },
  1241. #endif
  1242. #ifdef BB_ASH_MATH_SUPPORT
  1243. { BUILTIN_NOSPEC "let", letcmd },
  1244. #endif
  1245. { BUILTIN_ASSIGN "local", localcmd },
  1246. { BUILTIN_NOSPEC "pwd", pwdcmd },
  1247. { BUILTIN_REGULAR "read", readcmd },
  1248. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  1249. { BUILTIN_SPEC_REG "return", returncmd },
  1250. { BUILTIN_SPEC_REG "set", setcmd },
  1251. { BUILTIN_SPEC_REG "shift", shiftcmd },
  1252. { BUILTIN_SPEC_REG "times", timescmd },
  1253. { BUILTIN_SPEC_REG "trap", trapcmd },
  1254. { BUILTIN_REGULAR "true", truecmd },
  1255. { BUILTIN_NOSPEC "type", typecmd },
  1256. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  1257. { BUILTIN_REGULAR "umask", umaskcmd },
  1258. #ifdef BB_ASH_ALIAS
  1259. { BUILTIN_REGULAR "unalias", unaliascmd },
  1260. #endif
  1261. { BUILTIN_SPEC_REG "unset", unsetcmd },
  1262. { BUILTIN_REGULAR "wait", waitcmd },
  1263. };
  1264. #define NUMBUILTINS (sizeof (builtincmd) / sizeof (struct builtincmd) )
  1265. struct cmdentry {
  1266. int cmdtype;
  1267. union param {
  1268. int index;
  1269. const struct builtincmd *cmd;
  1270. struct funcnode *func;
  1271. } u;
  1272. };
  1273. /* action to find_command() */
  1274. #define DO_ERR 0x01 /* prints errors */
  1275. #define DO_ABS 0x02 /* checks absolute paths */
  1276. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  1277. #define DO_ALTPATH 0x08 /* using alternate path */
  1278. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  1279. static const char *pathopt; /* set by padvance */
  1280. static void shellexec(char **, const char *, int)
  1281. __attribute__((__noreturn__));
  1282. static char *padvance(const char **, const char *);
  1283. static void find_command(char *, struct cmdentry *, int, const char *);
  1284. static struct builtincmd *find_builtin(const char *);
  1285. static void hashcd(void);
  1286. static void changepath(const char *);
  1287. static void defun(char *, union node *);
  1288. static void unsetfunc(const char *);
  1289. #ifdef BB_ASH_MATH_SUPPORT
  1290. static int dash_arith(const char *);
  1291. #endif
  1292. /* $NetBSD: init.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
  1293. static void reset(void);
  1294. /* $NetBSD: var.h,v 1.21 2003/01/22 20:36:04 dsl Exp $ */
  1295. /*
  1296. * Shell variables.
  1297. */
  1298. /* flags */
  1299. #define VEXPORT 0x01 /* variable is exported */
  1300. #define VREADONLY 0x02 /* variable cannot be modified */
  1301. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1302. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1303. #define VSTACK 0x10 /* text is allocated on the stack */
  1304. #define VUNSET 0x20 /* the variable is not set */
  1305. #define VNOFUNC 0x40 /* don't call the callback function */
  1306. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1307. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1308. struct var {
  1309. struct var *next; /* next entry in hash list */
  1310. int flags; /* flags are defined above */
  1311. const char *text; /* name=value */
  1312. void (*func)(const char *);
  1313. /* function to be called when */
  1314. /* the variable gets set/unset */
  1315. };
  1316. struct localvar {
  1317. struct localvar *next; /* next local variable in list */
  1318. struct var *vp; /* the variable that was made local */
  1319. int flags; /* saved flags */
  1320. const char *text; /* saved text */
  1321. };
  1322. static struct localvar *localvars;
  1323. /*
  1324. * Shell variables.
  1325. */
  1326. #ifdef BB_ASH_GETOPTS
  1327. static void getoptsreset(const char *);
  1328. #endif
  1329. #ifdef BB_LOCALE_SUPPORT
  1330. #include <locale.h>
  1331. static void change_lc_all(const char *value);
  1332. static void change_lc_ctype(const char *value);
  1333. #endif
  1334. #define VTABSIZE 39
  1335. static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
  1336. #ifdef IFS_BROKEN
  1337. static const char defifsvar[] = "IFS= \t\n";
  1338. #define defifs (defifsvar + 4)
  1339. #else
  1340. static const char defifs[] = " \t\n";
  1341. #endif
  1342. static struct var varinit[] = {
  1343. #ifdef IFS_BROKEN
  1344. { 0, VSTRFIXED|VTEXTFIXED, defifsvar, 0 },
  1345. #else
  1346. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", 0 },
  1347. #endif
  1348. #ifdef BB_ASH_MAIL
  1349. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
  1350. { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1351. #endif
  1352. { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
  1353. { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
  1354. { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
  1355. { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
  1356. #ifdef BB_ASH_GETOPTS
  1357. { 0, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
  1358. #endif
  1359. #ifdef BB_LOCALE_SUPPORT
  1360. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=", change_lc_all},
  1361. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=", change_lc_ctype},
  1362. #endif
  1363. #ifdef BB_FEATURE_COMMAND_SAVEHISTORY
  1364. {0, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE=", NULL},
  1365. #endif
  1366. };
  1367. #define vifs varinit[0]
  1368. #ifdef BB_ASH_MAIL
  1369. #define vmail (&vifs)[1]
  1370. #define vmpath (&vmail)[1]
  1371. #else
  1372. #define vmpath vifs
  1373. #endif
  1374. #define vpath (&vmpath)[1]
  1375. #define vps1 (&vpath)[1]
  1376. #define vps2 (&vps1)[1]
  1377. #define vps4 (&vps2)[1]
  1378. #define voptind (&vps4)[1]
  1379. #define defpath (defpathvar + 5)
  1380. /*
  1381. * The following macros access the values of the above variables.
  1382. * They have to skip over the name. They return the null string
  1383. * for unset variables.
  1384. */
  1385. #define ifsval() (vifs.text + 4)
  1386. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1387. #define mailval() (vmail.text + 5)
  1388. #define mpathval() (vmpath.text + 9)
  1389. #define pathval() (vpath.text + 5)
  1390. #define ps1val() (vps1.text + 4)
  1391. #define ps2val() (vps2.text + 4)
  1392. #define ps4val() (vps4.text + 4)
  1393. #define optindval() (voptind.text + 7)
  1394. #define mpathset() ((vmpath.flags & VUNSET) == 0)
  1395. static void setvar(const char *, const char *, int);
  1396. static void setvareq(char *, int);
  1397. static void listsetvar(struct strlist *, int);
  1398. static char *lookupvar(const char *);
  1399. static char *bltinlookup(const char *);
  1400. static char **listvars(int, int, char ***);
  1401. #define environment() listvars(VEXPORT, VUNSET, 0)
  1402. static int showvars(const char *, int, int);
  1403. static void poplocalvars(void);
  1404. static int unsetvar(const char *);
  1405. #ifdef BB_ASH_GETOPTS
  1406. static int setvarsafe(const char *, const char *, int);
  1407. #endif
  1408. static int varcmp(const char *, const char *);
  1409. static struct var **hashvar(const char *);
  1410. static inline int varequal(const char *a, const char *b) {
  1411. return !varcmp(a, b);
  1412. }
  1413. static int loopnest; /* current loop nesting level */
  1414. /*
  1415. * The parsefile structure pointed to by the global variable parsefile
  1416. * contains information about the current file being read.
  1417. */
  1418. struct redirtab {
  1419. struct redirtab *next;
  1420. int renamed[10];
  1421. int nullredirs;
  1422. };
  1423. static struct redirtab *redirlist;
  1424. static int nullredirs;
  1425. extern char **environ;
  1426. /* $NetBSD: output.h,v 1.16 2002/11/24 22:35:42 christos Exp $ */
  1427. static void outstr(const char *, FILE *);
  1428. static void outcslow(int, FILE *);
  1429. static void flushall(void);
  1430. static void flushout(FILE *);
  1431. static int out1fmt(const char *, ...)
  1432. __attribute__((__format__(__printf__,1,2)));
  1433. static int fmtstr(char *, size_t, const char *, ...)
  1434. __attribute__((__format__(__printf__,3,4)));
  1435. static void xwrite(int, const void *, size_t);
  1436. static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1437. static void out1str(const char *p)
  1438. {
  1439. outstr(p, stdout);
  1440. }
  1441. static void out2str(const char *p)
  1442. {
  1443. outstr(p, stderr);
  1444. flushout(stderr);
  1445. }
  1446. /*
  1447. * Initialization code.
  1448. */
  1449. /*
  1450. * This routine initializes the builtin variables.
  1451. */
  1452. static inline void
  1453. initvar(void)
  1454. {
  1455. struct var *vp;
  1456. struct var *end;
  1457. struct var **vpp;
  1458. /*
  1459. * PS1 depends on uid
  1460. */
  1461. #if defined(BB_FEATURE_COMMAND_EDITING) && defined(BB_FEATURE_SH_FANCY_PROMPT)
  1462. vps1.text = "PS1=\\w \\$ ";
  1463. #else
  1464. if (!geteuid())
  1465. vps1.text = "PS1=# ";
  1466. #endif
  1467. vp = varinit;
  1468. end = vp + sizeof(varinit) / sizeof(varinit[0]);
  1469. do {
  1470. vpp = hashvar(vp->text);
  1471. vp->next = *vpp;
  1472. *vpp = vp;
  1473. } while (++vp < end);
  1474. }
  1475. static inline void
  1476. init(void)
  1477. {
  1478. /* from input.c: */
  1479. {
  1480. basepf.nextc = basepf.buf = basebuf;
  1481. }
  1482. /* from trap.c: */
  1483. {
  1484. signal(SIGCHLD, SIG_DFL);
  1485. }
  1486. /* from var.c: */
  1487. {
  1488. char **envp;
  1489. char ppid[32];
  1490. initvar();
  1491. for (envp = environ ; *envp ; envp++) {
  1492. if (strchr(*envp, '=')) {
  1493. setvareq(*envp, VEXPORT|VTEXTFIXED);
  1494. }
  1495. }
  1496. snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
  1497. setvar("PPID", ppid, 0);
  1498. setpwd(0, 0);
  1499. }
  1500. }
  1501. /* PEOF (the end of file marker) */
  1502. /*
  1503. * The input line number. Input.c just defines this variable, and saves
  1504. * and restores it when files are pushed and popped. The user of this
  1505. * package must set its value.
  1506. */
  1507. static int pgetc(void);
  1508. static int pgetc2(void);
  1509. static int preadbuffer(void);
  1510. static void pungetc(void);
  1511. static void pushstring(char *, void *);
  1512. static void popstring(void);
  1513. static void setinputfile(const char *, int);
  1514. static void setinputfd(int, int);
  1515. static void setinputstring(char *);
  1516. static void popfile(void);
  1517. static void popallfiles(void);
  1518. static void closescript(void);
  1519. /* $NetBSD: jobs.h,v 1.17 2003/01/22 20:36:04 dsl Exp $ */
  1520. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  1521. #define FORK_FG 0
  1522. #define FORK_BG 1
  1523. #define FORK_NOJOB 2
  1524. /* mode flags for showjob(s) */
  1525. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  1526. #define SHOW_PID 0x04 /* include process pid */
  1527. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  1528. /*
  1529. * A job structure contains information about a job. A job is either a
  1530. * single process or a set of processes contained in a pipeline. In the
  1531. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  1532. * array of pids.
  1533. */
  1534. struct procstat {
  1535. pid_t pid; /* process id */
  1536. int status; /* last process status from wait() */
  1537. char *cmd; /* text of command being run */
  1538. };
  1539. struct job {
  1540. struct procstat ps0; /* status of process */
  1541. struct procstat *ps; /* status or processes when more than one */
  1542. #if JOBS
  1543. int stopstatus; /* status of a stopped job */
  1544. #endif
  1545. uint32_t
  1546. nprocs: 16, /* number of processes */
  1547. state: 8,
  1548. #define JOBRUNNING 0 /* at least one proc running */
  1549. #define JOBSTOPPED 1 /* all procs are stopped */
  1550. #define JOBDONE 2 /* all procs are completed */
  1551. #if JOBS
  1552. sigint: 1, /* job was killed by SIGINT */
  1553. jobctl: 1, /* job running under job control */
  1554. #endif
  1555. waited: 1, /* true if this entry has been waited for */
  1556. used: 1, /* true if this entry is in used */
  1557. changed: 1; /* true if status has changed */
  1558. struct job *prev_job; /* previous job */
  1559. };
  1560. static pid_t backgndpid; /* pid of last background process */
  1561. static int job_warning; /* user was warned about stopped jobs */
  1562. #if JOBS
  1563. static int jobctl; /* true if doing job control */
  1564. #endif
  1565. static struct job *makejob(union node *, int);
  1566. static int forkshell(struct job *, union node *, int);
  1567. static int waitforjob(struct job *);
  1568. static int stoppedjobs(void);
  1569. #if ! JOBS
  1570. #define setjobctl(on) /* do nothing */
  1571. #else
  1572. static void setjobctl(int);
  1573. static void showjobs(FILE *, int);
  1574. #endif
  1575. /* $NetBSD: main.h,v 1.9 2002/11/24 22:35:41 christos Exp $ */
  1576. /* pid of main shell */
  1577. static int rootpid;
  1578. /* true if we aren't a child of the main shell */
  1579. static int rootshell;
  1580. static void readcmdfile(char *);
  1581. static void cmdloop(int);
  1582. /* $NetBSD: memalloc.h,v 1.13 2003/01/22 20:36:04 dsl Exp $ */
  1583. struct stackmark {
  1584. struct stack_block *stackp;
  1585. char *stacknxt;
  1586. size_t stacknleft;
  1587. struct stackmark *marknext;
  1588. };
  1589. /* minimum size of a block */
  1590. #define MINSIZE SHELL_ALIGN(504)
  1591. struct stack_block {
  1592. struct stack_block *prev;
  1593. char space[MINSIZE];
  1594. };
  1595. static struct stack_block stackbase;
  1596. static struct stack_block *stackp = &stackbase;
  1597. static struct stackmark *markp;
  1598. static char *stacknxt = stackbase.space;
  1599. static size_t stacknleft = MINSIZE;
  1600. static char *sstrend = stackbase.space + MINSIZE;
  1601. static int herefd = -1;
  1602. static pointer ckmalloc(size_t);
  1603. static pointer ckrealloc(pointer, size_t);
  1604. static char *savestr(const char *);
  1605. static pointer stalloc(size_t);
  1606. static void stunalloc(pointer);
  1607. static void setstackmark(struct stackmark *);
  1608. static void popstackmark(struct stackmark *);
  1609. static void growstackblock(void);
  1610. static void *growstackstr(void);
  1611. static char *makestrspace(size_t, char *);
  1612. static char *stnputs(const char *, size_t, char *);
  1613. static char *stputs(const char *, char *);
  1614. static inline char *_STPUTC(char c, char *p) {
  1615. if (p == sstrend)
  1616. p = growstackstr();
  1617. *p++ = c;
  1618. return p;
  1619. }
  1620. #define stackblock() ((void *)stacknxt)
  1621. #define stackblocksize() stacknleft
  1622. #define STARTSTACKSTR(p) ((p) = stackblock())
  1623. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1624. #define CHECKSTRSPACE(n, p) \
  1625. ({ \
  1626. char *q = (p); \
  1627. size_t l = (n); \
  1628. size_t m = sstrend - q; \
  1629. if (l > m) \
  1630. (p) = makestrspace(l, q); \
  1631. 0; \
  1632. })
  1633. #define USTPUTC(c, p) (*p++ = (c))
  1634. #define STACKSTRNUL(p) ((p) == sstrend? (p = growstackstr(), *p = '\0') : (*p = '\0'))
  1635. #define STUNPUTC(p) (--p)
  1636. #define STTOPC(p) p[-1]
  1637. #define STADJUST(amount, p) (p += (amount))
  1638. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1639. #define ungrabstackstr(s, p) stunalloc((s))
  1640. #define stackstrend() ((void *)sstrend)
  1641. #define ckfree(p) free((pointer)(p))
  1642. /* $NetBSD: mystring.h,v 1.10 2002/11/24 22:35:42 christos Exp $ */
  1643. #define DOLATSTRLEN 4
  1644. static char *prefix(const char *, const char *);
  1645. static int number(const char *);
  1646. static int is_number(const char *);
  1647. static char *single_quote(const char *);
  1648. static char *sstrdup(const char *);
  1649. #define equal(s1, s2) (strcmp(s1, s2) == 0)
  1650. #define scopy(s1, s2) ((void)strcpy(s2, s1))
  1651. /* $NetBSD: options.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
  1652. struct shparam {
  1653. int nparam; /* # of positional parameters (without $0) */
  1654. unsigned char malloc; /* if parameter list dynamically allocated */
  1655. char **p; /* parameter list */
  1656. #ifdef BB_ASH_GETOPTS
  1657. int optind; /* next parameter to be processed by getopts */
  1658. int optoff; /* used by getopts */
  1659. #endif
  1660. };
  1661. #define eflag optlist[0]
  1662. #define fflag optlist[1]
  1663. #define Iflag optlist[2]
  1664. #define iflag optlist[3]
  1665. #define mflag optlist[4]
  1666. #define nflag optlist[5]
  1667. #define sflag optlist[6]
  1668. #define xflag optlist[7]
  1669. #define vflag optlist[8]
  1670. #define Cflag optlist[9]
  1671. #define aflag optlist[10]
  1672. #define bflag optlist[11]
  1673. #define uflag optlist[12]
  1674. #define qflag optlist[13]
  1675. #ifdef DEBUG
  1676. #define nolog optlist[14]
  1677. #define debug optlist[15]
  1678. #define NOPTS 16
  1679. #else
  1680. #define NOPTS 14
  1681. #endif
  1682. /* $NetBSD: options.c,v 1.33 2003/01/22 20:36:04 dsl Exp $ */
  1683. static const char *const optletters_optnames[NOPTS] = {
  1684. "e" "errexit",
  1685. "f" "noglob",
  1686. "I" "ignoreeof",
  1687. "i" "interactive",
  1688. "m" "monitor",
  1689. "n" "noexec",
  1690. "s" "stdin",
  1691. "x" "xtrace",
  1692. "v" "verbose",
  1693. "C" "noclobber",
  1694. "a" "allexport",
  1695. "b" "notify",
  1696. "u" "nounset",
  1697. "q" "quietprofile",
  1698. #ifdef DEBUG
  1699. "\0" "nolog",
  1700. "\0" "debug",
  1701. #endif
  1702. };
  1703. #define optletters(n) optletters_optnames[(n)][0]
  1704. #define optnames(n) (&optletters_optnames[(n)][1])
  1705. static char optlist[NOPTS];
  1706. static char *arg0; /* value of $0 */
  1707. static struct shparam shellparam; /* $@ current positional parameters */
  1708. static char **argptr; /* argument list for builtin commands */
  1709. static char *optionarg; /* set by nextopt (like getopt) */
  1710. static char *optptr; /* used by nextopt */
  1711. static char *minusc; /* argument to -c option */
  1712. static void procargs(int, char **);
  1713. static void optschanged(void);
  1714. static void setparam(char **);
  1715. static void freeparam(volatile struct shparam *);
  1716. static int shiftcmd(int, char **);
  1717. static int setcmd(int, char **);
  1718. static int nextopt(const char *);
  1719. /* $NetBSD: redir.h,v 1.14 2002/11/24 22:35:43 christos Exp $ */
  1720. /* flags passed to redirect */
  1721. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  1722. #define REDIR_SAVEFD2 03 /* set preverrout */
  1723. union node;
  1724. static void redirect(union node *, int);
  1725. static void popredir(int);
  1726. static void clearredir(int);
  1727. static int ash_copyfd(int, int);
  1728. static int redirectsafe(union node *, int);
  1729. /* $NetBSD: show.h,v 1.6 2003/01/22 20:36:04 dsl Exp $ */
  1730. #ifdef DEBUG
  1731. static void showtree(union node *);
  1732. static void trace(const char *, ...);
  1733. static void tracev(const char *, va_list);
  1734. static void trargs(char **);
  1735. static void trputc(int);
  1736. static void trputs(const char *);
  1737. static void opentrace(void);
  1738. #endif
  1739. /* $NetBSD: trap.h,v 1.16 2002/11/24 22:35:43 christos Exp $ */
  1740. /* trap handler commands */
  1741. static char *trap[NSIG];
  1742. /* current value of signal */
  1743. static char sigmode[NSIG - 1];
  1744. /* indicates specified signal received */
  1745. static char gotsig[NSIG - 1];
  1746. static void clear_traps(void);
  1747. static void setsignal(int);
  1748. static void ignoresig(int);
  1749. static void onsig(int);
  1750. static void dotrap(void);
  1751. static void setinteractive(int);
  1752. static void exitshell(void) __attribute__((__noreturn__));
  1753. static int decode_signal(const char *, int);
  1754. /*
  1755. * This routine is called when an error or an interrupt occurs in an
  1756. * interactive shell and control is returned to the main command loop.
  1757. */
  1758. static void
  1759. reset(void)
  1760. {
  1761. /* from eval.c: */
  1762. {
  1763. evalskip = 0;
  1764. loopnest = 0;
  1765. funcnest = 0;
  1766. }
  1767. /* from input.c: */
  1768. {
  1769. parselleft = parsenleft = 0; /* clear input buffer */
  1770. popallfiles();
  1771. }
  1772. /* from parser.c: */
  1773. {
  1774. tokpushback = 0;
  1775. checkkwd = 0;
  1776. }
  1777. /* from redir.c: */
  1778. {
  1779. clearredir(0);
  1780. }
  1781. }
  1782. #ifdef BB_ASH_ALIAS
  1783. static struct alias *atab[ATABSIZE];
  1784. static void setalias(const char *, const char *);
  1785. static struct alias *freealias(struct alias *);
  1786. static struct alias **__lookupalias(const char *);
  1787. static void
  1788. setalias(const char *name, const char *val)
  1789. {
  1790. struct alias *ap, **app;
  1791. app = __lookupalias(name);
  1792. ap = *app;
  1793. INTOFF;
  1794. if (ap) {
  1795. if (!(ap->flag & ALIASINUSE)) {
  1796. ckfree(ap->val);
  1797. }
  1798. ap->val = savestr(val);
  1799. ap->flag &= ~ALIASDEAD;
  1800. } else {
  1801. /* not found */
  1802. ap = ckmalloc(sizeof (struct alias));
  1803. ap->name = savestr(name);
  1804. ap->val = savestr(val);
  1805. ap->flag = 0;
  1806. ap->next = 0;
  1807. *app = ap;
  1808. }
  1809. INTON;
  1810. }
  1811. static int
  1812. unalias(const char *name)
  1813. {
  1814. struct alias **app;
  1815. app = __lookupalias(name);
  1816. if (*app) {
  1817. INTOFF;
  1818. *app = freealias(*app);
  1819. INTON;
  1820. return (0);
  1821. }
  1822. return (1);
  1823. }
  1824. static void
  1825. rmaliases(void)
  1826. {
  1827. struct alias *ap, **app;
  1828. int i;
  1829. INTOFF;
  1830. for (i = 0; i < ATABSIZE; i++) {
  1831. app = &atab[i];
  1832. for (ap = *app; ap; ap = *app) {
  1833. *app = freealias(*app);
  1834. if (ap == *app) {
  1835. app = &ap->next;
  1836. }
  1837. }
  1838. }
  1839. INTON;
  1840. }
  1841. static struct alias *
  1842. lookupalias(const char *name, int check)
  1843. {
  1844. struct alias *ap = *__lookupalias(name);
  1845. if (check && ap && (ap->flag & ALIASINUSE))
  1846. return (NULL);
  1847. return (ap);
  1848. }
  1849. /*
  1850. * TODO - sort output
  1851. */
  1852. static int
  1853. aliascmd(int argc, char **argv)
  1854. {
  1855. char *n, *v;
  1856. int ret = 0;
  1857. struct alias *ap;
  1858. if (argc == 1) {
  1859. int i;
  1860. for (i = 0; i < ATABSIZE; i++)
  1861. for (ap = atab[i]; ap; ap = ap->next) {
  1862. printalias(ap);
  1863. }
  1864. return (0);
  1865. }
  1866. while ((n = *++argv) != NULL) {
  1867. if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
  1868. if ((ap = *__lookupalias(n)) == NULL) {
  1869. fprintf(stderr, "%s: %s not found\n", "alias", n);
  1870. ret = 1;
  1871. } else
  1872. printalias(ap);
  1873. } else {
  1874. *v++ = '\0';
  1875. setalias(n, v);
  1876. }
  1877. }
  1878. return (ret);
  1879. }
  1880. static int
  1881. unaliascmd(int argc, char **argv)
  1882. {
  1883. int i;
  1884. while ((i = nextopt("a")) != '\0') {
  1885. if (i == 'a') {
  1886. rmaliases();
  1887. return (0);
  1888. }
  1889. }
  1890. for (i = 0; *argptr; argptr++) {
  1891. if (unalias(*argptr)) {
  1892. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  1893. i = 1;
  1894. }
  1895. }
  1896. return (i);
  1897. }
  1898. static struct alias *
  1899. freealias(struct alias *ap) {
  1900. struct alias *next;
  1901. if (ap->flag & ALIASINUSE) {
  1902. ap->flag |= ALIASDEAD;
  1903. return ap;
  1904. }
  1905. next = ap->next;
  1906. ckfree(ap->name);
  1907. ckfree(ap->val);
  1908. ckfree(ap);
  1909. return next;
  1910. }
  1911. static void
  1912. printalias(const struct alias *ap) {
  1913. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  1914. }
  1915. static struct alias **
  1916. __lookupalias(const char *name) {
  1917. unsigned int hashval;
  1918. struct alias **app;
  1919. const char *p;
  1920. unsigned int ch;
  1921. p = name;
  1922. ch = (unsigned char)*p;
  1923. hashval = ch << 4;
  1924. while (ch) {
  1925. hashval += ch;
  1926. ch = (unsigned char)*++p;
  1927. }
  1928. app = &atab[hashval % ATABSIZE];
  1929. for (; *app; app = &(*app)->next) {
  1930. if (equal(name, (*app)->name)) {
  1931. break;
  1932. }
  1933. }
  1934. return app;
  1935. }
  1936. #endif /* BB_ASH_ALIAS */
  1937. /* $NetBSD: cd.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
  1938. /*
  1939. * The cd and pwd commands.
  1940. */
  1941. #define CD_PHYSICAL 1
  1942. #define CD_PRINT 2
  1943. static int docd(const char *, int);
  1944. static int cdopt(void);
  1945. static char *curdir = nullstr; /* current working directory */
  1946. static char *physdir = nullstr; /* physical working directory */
  1947. static int
  1948. cdopt(void)
  1949. {
  1950. int flags = 0;
  1951. int i, j;
  1952. j = 'L';
  1953. while ((i = nextopt("LP"))) {
  1954. if (i != j) {
  1955. flags ^= CD_PHYSICAL;
  1956. j = i;
  1957. }
  1958. }
  1959. return flags;
  1960. }
  1961. static int
  1962. cdcmd(int argc, char **argv)
  1963. {
  1964. const char *dest;
  1965. const char *path;
  1966. const char *p;
  1967. char c;
  1968. struct stat statb;
  1969. int flags;
  1970. flags = cdopt();
  1971. dest = *argptr;
  1972. if (!dest)
  1973. dest = bltinlookup(homestr);
  1974. else if (dest[0] == '-' && dest[1] == '\0') {
  1975. dest = bltinlookup("OLDPWD");
  1976. flags |= CD_PRINT;
  1977. goto step7;
  1978. }
  1979. if (!dest)
  1980. dest = nullstr;
  1981. if (*dest == '/')
  1982. goto step7;
  1983. if (*dest == '.') {
  1984. c = dest[1];
  1985. dotdot:
  1986. switch (c) {
  1987. case '\0':
  1988. case '/':
  1989. goto step6;
  1990. case '.':
  1991. c = dest[2];
  1992. if (c != '.')
  1993. goto dotdot;
  1994. }
  1995. }
  1996. if (!*dest)
  1997. dest = ".";
  1998. if (!(path = bltinlookup("CDPATH"))) {
  1999. step6:
  2000. step7:
  2001. p = dest;
  2002. goto docd;
  2003. }
  2004. do {
  2005. c = *path;
  2006. p = padvance(&path, dest);
  2007. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2008. if (c && c != ':')
  2009. flags |= CD_PRINT;
  2010. docd:
  2011. if (!docd(p, flags))
  2012. goto out;
  2013. break;
  2014. }
  2015. } while (path);
  2016. error("can't cd to %s", dest);
  2017. /* NOTREACHED */
  2018. out:
  2019. if (flags & CD_PRINT)
  2020. out1fmt(snlfmt, curdir);
  2021. return 0;
  2022. }
  2023. /*
  2024. * Update curdir (the name of the current directory) in response to a
  2025. * cd command.
  2026. */
  2027. static inline const char *
  2028. updatepwd(const char *dir)
  2029. {
  2030. char *new;
  2031. char *p;
  2032. char *cdcomppath;
  2033. const char *lim;
  2034. cdcomppath = sstrdup(dir);
  2035. STARTSTACKSTR(new);
  2036. if (*dir != '/') {
  2037. if (curdir == nullstr)
  2038. return 0;
  2039. new = stputs(curdir, new);
  2040. }
  2041. new = makestrspace(strlen(dir) + 2, new);
  2042. lim = stackblock() + 1;
  2043. if (*dir != '/') {
  2044. if (new[-1] != '/')
  2045. USTPUTC('/', new);
  2046. if (new > lim && *lim == '/')
  2047. lim++;
  2048. } else {
  2049. USTPUTC('/', new);
  2050. cdcomppath++;
  2051. if (dir[1] == '/' && dir[2] != '/') {
  2052. USTPUTC('/', new);
  2053. cdcomppath++;
  2054. lim++;
  2055. }
  2056. }
  2057. p = strtok(cdcomppath, "/");
  2058. while (p) {
  2059. switch(*p) {
  2060. case '.':
  2061. if (p[1] == '.' && p[2] == '\0') {
  2062. while (new > lim) {
  2063. STUNPUTC(new);
  2064. if (new[-1] == '/')
  2065. break;
  2066. }
  2067. break;
  2068. } else if (p[1] == '\0')
  2069. break;
  2070. /* fall through */
  2071. default:
  2072. new = stputs(p, new);
  2073. USTPUTC('/', new);
  2074. }
  2075. p = strtok(0, "/");
  2076. }
  2077. if (new > lim)
  2078. STUNPUTC(new);
  2079. *new = 0;
  2080. return stackblock();
  2081. }
  2082. /*
  2083. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2084. * know that the current directory has changed.
  2085. */
  2086. static int
  2087. docd(const char *dest, int flags)
  2088. {
  2089. const char *dir = 0;
  2090. int err;
  2091. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2092. INTOFF;
  2093. if (!(flags & CD_PHYSICAL)) {
  2094. dir = updatepwd(dest);
  2095. if (dir)
  2096. dest = dir;
  2097. }
  2098. err = chdir(dest);
  2099. if (err)
  2100. goto out;
  2101. setpwd(dir, 1);
  2102. hashcd();
  2103. out:
  2104. INTON;
  2105. return err;
  2106. }
  2107. /*
  2108. * Find out what the current directory is. If we already know the current
  2109. * directory, this routine returns immediately.
  2110. */
  2111. static inline char *
  2112. getpwd(void)
  2113. {
  2114. char *dir = getcwd(0, 0);
  2115. return dir ? dir : nullstr;
  2116. }
  2117. static int
  2118. pwdcmd(int argc, char **argv)
  2119. {
  2120. int flags;
  2121. const char *dir = curdir;
  2122. flags = cdopt();
  2123. if (flags) {
  2124. if (physdir == nullstr)
  2125. setpwd(dir, 0);
  2126. dir = physdir;
  2127. }
  2128. out1fmt(snlfmt, dir);
  2129. return 0;
  2130. }
  2131. static void
  2132. setpwd(const char *val, int setold)
  2133. {
  2134. char *oldcur, *dir;
  2135. oldcur = dir = curdir;
  2136. if (setold) {
  2137. setvar("OLDPWD", oldcur, VEXPORT);
  2138. }
  2139. INTOFF;
  2140. if (physdir != nullstr) {
  2141. if (physdir != oldcur)
  2142. free(physdir);
  2143. physdir = nullstr;
  2144. }
  2145. if (oldcur == val || !val) {
  2146. char *s = getpwd();
  2147. physdir = s;
  2148. if (!val)
  2149. dir = s;
  2150. } else
  2151. dir = savestr(val);
  2152. if (oldcur != dir && oldcur != nullstr) {
  2153. free(oldcur);
  2154. }
  2155. curdir = dir;
  2156. INTON;
  2157. setvar("PWD", dir, VEXPORT);
  2158. }
  2159. /* $NetBSD: error.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
  2160. /*
  2161. * Errors and exceptions.
  2162. */
  2163. /*
  2164. * Code to handle exceptions in C.
  2165. */
  2166. static void exverror(int, const char *, va_list)
  2167. __attribute__((__noreturn__));
  2168. /*
  2169. * Called to raise an exception. Since C doesn't include exceptions, we
  2170. * just do a longjmp to the exception handler. The type of exception is
  2171. * stored in the global variable "exception".
  2172. */
  2173. static void
  2174. exraise(int e)
  2175. {
  2176. #ifdef DEBUG
  2177. if (handler == NULL)
  2178. abort();
  2179. #endif
  2180. INTOFF;
  2181. exception = e;
  2182. longjmp(handler->loc, 1);
  2183. }
  2184. /*
  2185. * Called from trap.c when a SIGINT is received. (If the user specifies
  2186. * that SIGINT is to be trapped or ignored using the trap builtin, then
  2187. * this routine is not called.) Suppressint is nonzero when interrupts
  2188. * are held using the INTOFF macro. (The test for iflag is just
  2189. * defensive programming.)
  2190. */
  2191. static void
  2192. onint(void) {
  2193. int i;
  2194. intpending = 0;
  2195. sigsetmask(0);
  2196. i = EXSIG;
  2197. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  2198. if (!(rootshell && iflag)) {
  2199. signal(SIGINT, SIG_DFL);
  2200. raise(SIGINT);
  2201. }
  2202. i = EXINT;
  2203. }
  2204. exraise(i);
  2205. /* NOTREACHED */
  2206. }
  2207. static void
  2208. exvwarning(const char *msg, va_list ap)
  2209. {
  2210. FILE *errs;
  2211. const char *name;
  2212. const char *fmt;
  2213. errs = stderr;
  2214. name = arg0;
  2215. fmt = "%s: ";
  2216. if (commandname) {
  2217. name = commandname;
  2218. fmt = "%s: %d: ";
  2219. }
  2220. fprintf(errs, fmt, name, startlinno);
  2221. vfprintf(errs, msg, ap);
  2222. outcslow('\n', errs);
  2223. }
  2224. /*
  2225. * Exverror is called to raise the error exception. If the second argument
  2226. * is not NULL then error prints an error message using printf style
  2227. * formatting. It then raises the error exception.
  2228. */
  2229. static void
  2230. exverror(int cond, const char *msg, va_list ap)
  2231. {
  2232. #ifdef DEBUG
  2233. if (msg) {
  2234. TRACE(("exverror(%d, \"", cond));
  2235. TRACEV((msg, ap));
  2236. TRACE(("\") pid=%d\n", getpid()));
  2237. } else
  2238. TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
  2239. if (msg)
  2240. #endif
  2241. exvwarning(msg, ap);
  2242. flushall();
  2243. exraise(cond);
  2244. /* NOTREACHED */
  2245. }
  2246. static void
  2247. error(const char *msg, ...)
  2248. {
  2249. va_list ap;
  2250. va_start(ap, msg);
  2251. exverror(EXERROR, msg, ap);
  2252. /* NOTREACHED */
  2253. va_end(ap);
  2254. }
  2255. static void
  2256. exerror(int cond, const char *msg, ...)
  2257. {
  2258. va_list ap;
  2259. va_start(ap, msg);
  2260. exverror(cond, msg, ap);
  2261. /* NOTREACHED */
  2262. va_end(ap);
  2263. }
  2264. /*
  2265. * error/warning routines for external builtins
  2266. */
  2267. static void
  2268. sh_warnx(const char *fmt, ...)
  2269. {
  2270. va_list ap;
  2271. va_start(ap, fmt);
  2272. exvwarning(fmt, ap);
  2273. va_end(ap);
  2274. }
  2275. /*
  2276. * Return a string describing an error. The returned string may be a
  2277. * pointer to a static buffer that will be overwritten on the next call.
  2278. * Action describes the operation that got the error.
  2279. */
  2280. static const char *
  2281. errmsg(int e, const char *em)
  2282. {
  2283. if(e == ENOENT || e == ENOTDIR) {
  2284. return em;
  2285. }
  2286. return strerror(e);
  2287. }
  2288. /* $NetBSD: eval.c,v 1.71 2003/01/23 03:33:16 rafal Exp $ */
  2289. /*
  2290. * Evaluate a command.
  2291. */
  2292. /* flags in argument to evaltree */
  2293. #define EV_EXIT 01 /* exit after evaluating tree */
  2294. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  2295. #define EV_BACKCMD 04 /* command executing within back quotes */
  2296. static void evalloop(union node *, int);
  2297. static void evalfor(union node *, int);
  2298. static void evalcase(union node *, int);
  2299. static void evalsubshell(union node *, int);
  2300. static void expredir(union node *);
  2301. static void evalpipe(union node *, int);
  2302. static void evalcommand(union node *, int);
  2303. static int evalbltin(const struct builtincmd *, int, char **);
  2304. static int evalfun(struct funcnode *, int, char **, int);
  2305. static void prehash(union node *);
  2306. static int bltincmd(int, char **);
  2307. static const struct builtincmd bltin = {
  2308. "\0\0", bltincmd
  2309. };
  2310. /*
  2311. * Called to reset things after an exception.
  2312. */
  2313. /*
  2314. * The eval commmand.
  2315. */
  2316. static int
  2317. evalcmd(int argc, char **argv)
  2318. {
  2319. char *p;
  2320. char *concat;
  2321. char **ap;
  2322. if (argc > 1) {
  2323. p = argv[1];
  2324. if (argc > 2) {
  2325. STARTSTACKSTR(concat);
  2326. ap = argv + 2;
  2327. for (;;) {
  2328. concat = stputs(p, concat);
  2329. if ((p = *ap++) == NULL)
  2330. break;
  2331. STPUTC(' ', concat);
  2332. }
  2333. STPUTC('\0', concat);
  2334. p = grabstackstr(concat);
  2335. }
  2336. evalstring(p, EV_TESTED);
  2337. }
  2338. return exitstatus;
  2339. }
  2340. /*
  2341. * Execute a command or commands contained in a string.
  2342. */
  2343. static void
  2344. evalstring(char *s, int flag)
  2345. {
  2346. union node *n;
  2347. struct stackmark smark;
  2348. setstackmark(&smark);
  2349. setinputstring(s);
  2350. while ((n = parsecmd(0)) != NEOF) {
  2351. evaltree(n, flag);
  2352. popstackmark(&smark);
  2353. if (evalskip)
  2354. break;
  2355. }
  2356. popfile();
  2357. popstackmark(&smark);
  2358. }
  2359. /*
  2360. * Evaluate a parse tree. The value is left in the global variable
  2361. * exitstatus.
  2362. */
  2363. static void
  2364. evaltree(union node *n, int flags)
  2365. {
  2366. int checkexit = 0;
  2367. void (*evalfn)(union node *, int);
  2368. unsigned isor;
  2369. int status;
  2370. if (n == NULL) {
  2371. TRACE(("evaltree(NULL) called\n"));
  2372. goto out;
  2373. }
  2374. TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
  2375. getpid(), n, n->type, flags));
  2376. switch (n->type) {
  2377. default:
  2378. #ifdef DEBUG
  2379. out1fmt("Node type = %d\n", n->type);
  2380. fflush(stdout);
  2381. break;
  2382. #endif
  2383. case NNOT:
  2384. evaltree(n->nnot.com, EV_TESTED);
  2385. status = !exitstatus;
  2386. goto setstatus;
  2387. case NREDIR:
  2388. expredir(n->nredir.redirect);
  2389. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  2390. if (!status) {
  2391. evaltree(n->nredir.n, flags & EV_TESTED);
  2392. status = exitstatus;
  2393. }
  2394. popredir(0);
  2395. goto setstatus;
  2396. case NCMD:
  2397. evalfn = evalcommand;
  2398. checkexit:
  2399. if (eflag && !(flags & EV_TESTED))
  2400. checkexit = ~0;
  2401. goto calleval;
  2402. case NFOR:
  2403. evalfn = evalfor;
  2404. goto calleval;
  2405. case NWHILE:
  2406. case NUNTIL:
  2407. evalfn = evalloop;
  2408. goto calleval;
  2409. case NSUBSHELL:
  2410. case NBACKGND:
  2411. evalfn = evalsubshell;
  2412. goto calleval;
  2413. case NPIPE:
  2414. evalfn = evalpipe;
  2415. goto checkexit;
  2416. case NCASE:
  2417. evalfn = evalcase;
  2418. goto calleval;
  2419. case NAND:
  2420. case NOR:
  2421. case NSEMI:
  2422. #if NAND + 1 != NOR
  2423. #error NAND + 1 != NOR
  2424. #endif
  2425. #if NOR + 1 != NSEMI
  2426. #error NOR + 1 != NSEMI
  2427. #endif
  2428. isor = n->type - NAND;
  2429. evaltree(
  2430. n->nbinary.ch1,
  2431. (flags | ((isor >> 1) - 1)) & EV_TESTED
  2432. );
  2433. if (!exitstatus == isor)
  2434. break;
  2435. if (!evalskip) {
  2436. n = n->nbinary.ch2;
  2437. evaln:
  2438. evalfn = evaltree;
  2439. calleval:
  2440. evalfn(n, flags);
  2441. break;
  2442. }
  2443. break;
  2444. case NIF:
  2445. evaltree(n->nif.test, EV_TESTED);
  2446. if (evalskip)
  2447. break;
  2448. if (exitstatus == 0) {
  2449. n = n->nif.ifpart;
  2450. goto evaln;
  2451. } else if (n->nif.elsepart) {
  2452. n = n->nif.elsepart;
  2453. goto evaln;
  2454. }
  2455. goto success;
  2456. case NDEFUN:
  2457. defun(n->narg.text, n->narg.next);
  2458. success:
  2459. status = 0;
  2460. setstatus:
  2461. exitstatus = status;
  2462. break;
  2463. }
  2464. out:
  2465. if (pendingsigs)
  2466. dotrap();
  2467. if (flags & EV_EXIT || checkexit & exitstatus)
  2468. exraise(EXEXIT);
  2469. }
  2470. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  2471. static
  2472. #endif
  2473. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  2474. static void
  2475. evalloop(union node *n, int flags)
  2476. {
  2477. int status;
  2478. loopnest++;
  2479. status = 0;
  2480. flags &= EV_TESTED;
  2481. for (;;) {
  2482. int i;
  2483. evaltree(n->nbinary.ch1, EV_TESTED);
  2484. if (evalskip) {
  2485. skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
  2486. evalskip = 0;
  2487. continue;
  2488. }
  2489. if (evalskip == SKIPBREAK && --skipcount <= 0)
  2490. evalskip = 0;
  2491. break;
  2492. }
  2493. i = exitstatus;
  2494. if (n->type != NWHILE)
  2495. i = !i;
  2496. if (i != 0)
  2497. break;
  2498. evaltree(n->nbinary.ch2, flags);
  2499. status = exitstatus;
  2500. if (evalskip)
  2501. goto skipping;
  2502. }
  2503. loopnest--;
  2504. exitstatus = status;
  2505. }
  2506. static void
  2507. evalfor(union node *n, int flags)
  2508. {
  2509. struct arglist arglist;
  2510. union node *argp;
  2511. struct strlist *sp;
  2512. struct stackmark smark;
  2513. setstackmark(&smark);
  2514. arglist.lastp = &arglist.list;
  2515. for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
  2516. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  2517. /* XXX */
  2518. if (evalskip)
  2519. goto out;
  2520. }
  2521. *arglist.lastp = NULL;
  2522. exitstatus = 0;
  2523. loopnest++;
  2524. flags &= EV_TESTED;
  2525. for (sp = arglist.list ; sp ; sp = sp->next) {
  2526. setvar(n->nfor.var, sp->text, 0);
  2527. evaltree(n->nfor.body, flags);
  2528. if (evalskip) {
  2529. if (evalskip == SKIPCONT && --skipcount <= 0) {
  2530. evalskip = 0;
  2531. continue;
  2532. }
  2533. if (evalskip == SKIPBREAK && --skipcount <= 0)
  2534. evalskip = 0;
  2535. break;
  2536. }
  2537. }
  2538. loopnest--;
  2539. out:
  2540. popstackmark(&smark);
  2541. }
  2542. static void
  2543. evalcase(union node *n, int flags)
  2544. {
  2545. union node *cp;
  2546. union node *patp;
  2547. struct arglist arglist;
  2548. struct stackmark smark;
  2549. setstackmark(&smark);
  2550. arglist.lastp = &arglist.list;
  2551. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  2552. exitstatus = 0;
  2553. for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
  2554. for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
  2555. if (casematch(patp, arglist.list->text)) {
  2556. if (evalskip == 0) {
  2557. evaltree(cp->nclist.body, flags);
  2558. }
  2559. goto out;
  2560. }
  2561. }
  2562. }
  2563. out:
  2564. popstackmark(&smark);
  2565. }
  2566. /*
  2567. * Kick off a subshell to evaluate a tree.
  2568. */
  2569. static void
  2570. evalsubshell(union node *n, int flags)
  2571. {
  2572. struct job *jp;
  2573. int backgnd = (n->type == NBACKGND);
  2574. int status;
  2575. expredir(n->nredir.redirect);
  2576. if (!backgnd && flags & EV_EXIT && !trap[0])
  2577. goto nofork;
  2578. INTOFF;
  2579. jp = makejob(n, 1);
  2580. if (forkshell(jp, n, backgnd) == 0) {
  2581. INTON;
  2582. flags |= EV_EXIT;
  2583. if (backgnd)
  2584. flags &=~ EV_TESTED;
  2585. nofork:
  2586. redirect(n->nredir.redirect, 0);
  2587. evaltreenr(n->nredir.n, flags);
  2588. /* never returns */
  2589. }
  2590. status = 0;
  2591. if (! backgnd)
  2592. status = waitforjob(jp);
  2593. exitstatus = status;
  2594. INTON;
  2595. }
  2596. /*
  2597. * Compute the names of the files in a redirection list.
  2598. */
  2599. static void
  2600. expredir(union node *n)
  2601. {
  2602. union node *redir;
  2603. for (redir = n ; redir ; redir = redir->nfile.next) {
  2604. struct arglist fn;
  2605. fn.lastp = &fn.list;
  2606. switch (redir->type) {
  2607. case NFROMTO:
  2608. case NFROM:
  2609. case NTO:
  2610. case NCLOBBER:
  2611. case NAPPEND:
  2612. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  2613. redir->nfile.expfname = fn.list->text;
  2614. break;
  2615. case NFROMFD:
  2616. case NTOFD:
  2617. if (redir->ndup.vname) {
  2618. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  2619. fixredir(redir, fn.list->text, 1);
  2620. }
  2621. break;
  2622. }
  2623. }
  2624. }
  2625. /*
  2626. * Evaluate a pipeline. All the processes in the pipeline are children
  2627. * of the process creating the pipeline. (This differs from some versions
  2628. * of the shell, which make the last process in a pipeline the parent
  2629. * of all the rest.)
  2630. */
  2631. static void
  2632. evalpipe(union node *n, int flags)
  2633. {
  2634. struct job *jp;
  2635. struct nodelist *lp;
  2636. int pipelen;
  2637. int prevfd;
  2638. int pip[2];
  2639. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  2640. pipelen = 0;
  2641. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
  2642. pipelen++;
  2643. flags |= EV_EXIT;
  2644. INTOFF;
  2645. jp = makejob(n, pipelen);
  2646. prevfd = -1;
  2647. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
  2648. prehash(lp->n);
  2649. pip[1] = -1;
  2650. if (lp->next) {
  2651. if (pipe(pip) < 0) {
  2652. close(prevfd);
  2653. error("Pipe call failed");
  2654. }
  2655. }
  2656. if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
  2657. INTON;
  2658. if (pip[1] >= 0) {
  2659. close(pip[0]);
  2660. }
  2661. if (prevfd > 0) {
  2662. dup2(prevfd, 0);
  2663. close(prevfd);
  2664. }
  2665. if (pip[1] > 1) {
  2666. dup2(pip[1], 1);
  2667. close(pip[1]);
  2668. }
  2669. evaltreenr(lp->n, flags);
  2670. /* never returns */
  2671. }
  2672. if (prevfd >= 0)
  2673. close(prevfd);
  2674. prevfd = pip[0];
  2675. close(pip[1]);
  2676. }
  2677. if (n->npipe.backgnd == 0) {
  2678. exitstatus = waitforjob(jp);
  2679. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  2680. }
  2681. INTON;
  2682. }
  2683. /*
  2684. * Execute a command inside back quotes. If it's a builtin command, we
  2685. * want to save its output in a block obtained from malloc. Otherwise
  2686. * we fork off a subprocess and get the output of the command via a pipe.
  2687. * Should be called with interrupts off.
  2688. */
  2689. static void
  2690. evalbackcmd(union node *n, struct backcmd *result)
  2691. {
  2692. int saveherefd;
  2693. result->fd = -1;
  2694. result->buf = NULL;
  2695. result->nleft = 0;
  2696. result->jp = NULL;
  2697. if (n == NULL) {
  2698. goto out;
  2699. }
  2700. saveherefd = herefd;
  2701. herefd = -1;
  2702. {
  2703. int pip[2];
  2704. struct job *jp;
  2705. if (pipe(pip) < 0)
  2706. error("Pipe call failed");
  2707. jp = makejob(n, 1);
  2708. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  2709. FORCEINTON;
  2710. close(pip[0]);
  2711. if (pip[1] != 1) {
  2712. close(1);
  2713. ash_copyfd(pip[1], 1);
  2714. close(pip[1]);
  2715. }
  2716. eflag = 0;
  2717. evaltreenr(n, EV_EXIT);
  2718. /* NOTREACHED */
  2719. }
  2720. close(pip[1]);
  2721. result->fd = pip[0];
  2722. result->jp = jp;
  2723. }
  2724. herefd = saveherefd;
  2725. out:
  2726. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  2727. result->fd, result->buf, result->nleft, result->jp));
  2728. }
  2729. #ifdef BB_ASH_CMDCMD
  2730. static inline char **
  2731. parse_command_args(char **argv, const char **path)
  2732. {
  2733. char *cp, c;
  2734. for (;;) {
  2735. cp = *++argv;
  2736. if (!cp)
  2737. return 0;
  2738. if (*cp++ != '-')
  2739. break;
  2740. if (!(c = *cp++))
  2741. break;
  2742. if (c == '-' && !*cp) {
  2743. argv++;
  2744. break;
  2745. }
  2746. do {
  2747. switch (c) {
  2748. case 'p':
  2749. *path = defpath;
  2750. break;
  2751. default:
  2752. /* run 'typecmd' for other options */
  2753. return 0;
  2754. }
  2755. } while ((c = *cp++));
  2756. }
  2757. return argv;
  2758. }
  2759. #endif
  2760. /*
  2761. * Execute a simple command.
  2762. */
  2763. static void
  2764. evalcommand(union node *cmd, int flags)
  2765. {
  2766. struct stackmark smark;
  2767. union node *argp;
  2768. struct arglist arglist;
  2769. struct arglist varlist;
  2770. char **argv;
  2771. int argc;
  2772. const struct strlist *sp;
  2773. struct cmdentry cmdentry;
  2774. struct job *jp;
  2775. char *lastarg;
  2776. const char *path;
  2777. int spclbltin;
  2778. int cmd_is_exec;
  2779. int status;
  2780. char **nargv;
  2781. /* First expand the arguments. */
  2782. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  2783. setstackmark(&smark);
  2784. back_exitstatus = 0;
  2785. cmdentry.cmdtype = CMDBUILTIN;
  2786. cmdentry.u.cmd = &bltin;
  2787. varlist.lastp = &varlist.list;
  2788. *varlist.lastp = NULL;
  2789. arglist.lastp = &arglist.list;
  2790. *arglist.lastp = NULL;
  2791. argc = 0;
  2792. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  2793. struct strlist **spp;
  2794. spp = arglist.lastp;
  2795. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  2796. for (sp = *spp; sp; sp = sp->next)
  2797. argc++;
  2798. }
  2799. argv = nargv = stalloc(sizeof (char *) * (argc + 1));
  2800. for (sp = arglist.list ; sp ; sp = sp->next) {
  2801. TRACE(("evalcommand arg: %s\n", sp->text));
  2802. *nargv++ = sp->text;
  2803. }
  2804. *nargv = NULL;
  2805. lastarg = NULL;
  2806. if (iflag && funcnest == 0 && argc > 0)
  2807. lastarg = nargv[-1];
  2808. preverrout_fd = 2;
  2809. expredir(cmd->ncmd.redirect);
  2810. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
  2811. path = vpath.text;
  2812. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  2813. struct strlist **spp;
  2814. char *p;
  2815. spp = varlist.lastp;
  2816. expandarg(argp, &varlist, EXP_VARTILDE);
  2817. /*
  2818. * Modify the command lookup path, if a PATH= assignment
  2819. * is present
  2820. */
  2821. p = (*spp)->text;
  2822. if (varequal(p, path))
  2823. path = p;
  2824. }
  2825. /* Print the command if xflag is set. */
  2826. if (xflag) {
  2827. int n;
  2828. const char *p = " %s";
  2829. p++;
  2830. dprintf(preverrout_fd, p, ps4val());
  2831. sp = varlist.list;
  2832. for(n = 0; n < 2; n++) {
  2833. while (sp) {
  2834. dprintf(preverrout_fd, p, sp->text);
  2835. sp = sp->next;
  2836. if(*p == '%') {
  2837. p--;
  2838. }
  2839. }
  2840. sp = arglist.list;
  2841. }
  2842. xwrite(preverrout_fd, "\n", 1);
  2843. }
  2844. cmd_is_exec = 0;
  2845. spclbltin = -1;
  2846. /* Now locate the command. */
  2847. if (argc) {
  2848. const char *oldpath;
  2849. int cmd_flag = DO_ERR;
  2850. path += 5;
  2851. oldpath = path;
  2852. for (;;) {
  2853. find_command(argv[0], &cmdentry, cmd_flag, path);
  2854. if (cmdentry.cmdtype == CMDUNKNOWN) {
  2855. status = 127;
  2856. flushout(stderr);
  2857. goto bail;
  2858. }
  2859. /* implement bltin and command here */
  2860. if (cmdentry.cmdtype != CMDBUILTIN)
  2861. break;
  2862. if (spclbltin < 0)
  2863. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  2864. if (cmdentry.u.cmd == EXECCMD)
  2865. cmd_is_exec++;
  2866. #ifdef BB_ASH_CMDCMD
  2867. if (cmdentry.u.cmd == COMMANDCMD) {
  2868. path = oldpath;
  2869. nargv = parse_command_args(argv, &path);
  2870. if (!nargv)
  2871. break;
  2872. argc -= nargv - argv;
  2873. argv = nargv;
  2874. cmd_flag |= DO_NOFUNC;
  2875. } else
  2876. #endif
  2877. break;
  2878. }
  2879. }
  2880. if (status) {
  2881. /* We have a redirection error. */
  2882. if (spclbltin > 0)
  2883. exraise(EXERROR);
  2884. bail:
  2885. exitstatus = status;
  2886. goto out;
  2887. }
  2888. /* Execute the command. */
  2889. switch (cmdentry.cmdtype) {
  2890. default:
  2891. /* Fork off a child process if necessary. */
  2892. if (!(flags & EV_EXIT) || trap[0]) {
  2893. INTOFF;
  2894. jp = makejob(cmd, 1);
  2895. if (forkshell(jp, cmd, FORK_FG) != 0) {
  2896. exitstatus = waitforjob(jp);
  2897. INTON;
  2898. break;
  2899. }
  2900. FORCEINTON;
  2901. }
  2902. listsetvar(varlist.list, VEXPORT|VSTACK);
  2903. shellexec(argv, path, cmdentry.u.index);
  2904. /* NOTREACHED */
  2905. case CMDBUILTIN:
  2906. cmdenviron = varlist.list;
  2907. if (cmdenviron) {
  2908. struct strlist *list = cmdenviron;
  2909. int i = VNOSET;
  2910. if (spclbltin > 0 || argc == 0) {
  2911. i = 0;
  2912. if (cmd_is_exec && argc > 1)
  2913. i = VEXPORT;
  2914. }
  2915. listsetvar(list, i);
  2916. }
  2917. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  2918. int exit_status;
  2919. int i, j;
  2920. i = exception;
  2921. if (i == EXEXIT)
  2922. goto raise;
  2923. exit_status = 2;
  2924. j = 0;
  2925. if (i == EXINT)
  2926. j = SIGINT;
  2927. if (i == EXSIG)
  2928. j = pendingsigs;
  2929. if (j)
  2930. exit_status = j + 128;
  2931. exitstatus = exit_status;
  2932. if (i == EXINT || spclbltin > 0) {
  2933. raise:
  2934. longjmp(handler->loc, 1);
  2935. }
  2936. FORCEINTON;
  2937. }
  2938. break;
  2939. case CMDFUNCTION:
  2940. listsetvar(varlist.list, 0);
  2941. if (evalfun(cmdentry.u.func, argc, argv, flags))
  2942. goto raise;
  2943. break;
  2944. }
  2945. out:
  2946. popredir(cmd_is_exec);
  2947. if (lastarg)
  2948. /* dsl: I think this is intended to be used to support
  2949. * '_' in 'vi' command mode during line editing...
  2950. * However I implemented that within libedit itself.
  2951. */
  2952. setvar("_", lastarg, 0);
  2953. popstackmark(&smark);
  2954. }
  2955. static int
  2956. evalbltin(const struct builtincmd *cmd, int argc, char **argv) {
  2957. char *volatile savecmdname;
  2958. struct jmploc *volatile savehandler;
  2959. struct jmploc jmploc;
  2960. int i;
  2961. savecmdname = commandname;
  2962. if ((i = setjmp(jmploc.loc)))
  2963. goto cmddone;
  2964. savehandler = handler;
  2965. handler = &jmploc;
  2966. commandname = argv[0];
  2967. argptr = argv + 1;
  2968. optptr = NULL; /* initialize nextopt */
  2969. exitstatus = (*cmd->builtin)(argc, argv);
  2970. flushall();
  2971. cmddone:
  2972. exitstatus |= ferror(stdout);
  2973. commandname = savecmdname;
  2974. exsig = 0;
  2975. handler = savehandler;
  2976. return i;
  2977. }
  2978. static int
  2979. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  2980. {
  2981. volatile struct shparam saveparam;
  2982. struct localvar *volatile savelocalvars;
  2983. struct jmploc *volatile savehandler;
  2984. struct jmploc jmploc;
  2985. int e;
  2986. saveparam = shellparam;
  2987. savelocalvars = localvars;
  2988. if ((e = setjmp(jmploc.loc))) {
  2989. goto funcdone;
  2990. }
  2991. INTOFF;
  2992. savehandler = handler;
  2993. handler = &jmploc;
  2994. localvars = NULL;
  2995. shellparam.malloc = 0;
  2996. func->count++;
  2997. INTON;
  2998. shellparam.nparam = argc - 1;
  2999. shellparam.p = argv + 1;
  3000. #ifdef BB_ASH_GETOPTS
  3001. shellparam.optind = 1;
  3002. shellparam.optoff = -1;
  3003. #endif
  3004. funcnest++;
  3005. evaltree(&func->n, flags & EV_TESTED);
  3006. funcnest--;
  3007. funcdone:
  3008. INTOFF;
  3009. freefunc(func);
  3010. poplocalvars();
  3011. localvars = savelocalvars;
  3012. freeparam(&shellparam);
  3013. shellparam = saveparam;
  3014. handler = savehandler;
  3015. INTON;
  3016. if (evalskip == SKIPFUNC) {
  3017. evalskip = 0;
  3018. skipcount = 0;
  3019. }
  3020. return e;
  3021. }
  3022. /*
  3023. * Search for a command. This is called before we fork so that the
  3024. * location of the command will be available in the parent as well as
  3025. * the child.
  3026. */
  3027. static void
  3028. prehash(union node *n)
  3029. {
  3030. struct cmdentry entry;
  3031. if (n->type == NCMD && n->ncmd.args)
  3032. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  3033. }
  3034. /*
  3035. * Builtin commands. Builtin commands whose functions are closely
  3036. * tied to evaluation are implemented here.
  3037. */
  3038. /*
  3039. * No command given.
  3040. */
  3041. static int
  3042. bltincmd(int argc, char **argv)
  3043. {
  3044. /*
  3045. * Preserve exitstatus of a previous possible redirection
  3046. * as POSIX mandates
  3047. */
  3048. return back_exitstatus;
  3049. }
  3050. /*
  3051. * Handle break and continue commands. Break, continue, and return are
  3052. * all handled by setting the evalskip flag. The evaluation routines
  3053. * above all check this flag, and if it is set they start skipping
  3054. * commands rather than executing them. The variable skipcount is
  3055. * the number of loops to break/continue, or the number of function
  3056. * levels to return. (The latter is always 1.) It should probably
  3057. * be an error to break out of more loops than exist, but it isn't
  3058. * in the standard shell so we don't make it one here.
  3059. */
  3060. static int
  3061. breakcmd(int argc, char **argv)
  3062. {
  3063. int n = argc > 1 ? number(argv[1]) : 1;
  3064. if (n <= 0)
  3065. error(illnum, argv[1]);
  3066. if (n > loopnest)
  3067. n = loopnest;
  3068. if (n > 0) {
  3069. evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
  3070. skipcount = n;
  3071. }
  3072. return 0;
  3073. }
  3074. /*
  3075. * The return command.
  3076. */
  3077. static int
  3078. returncmd(int argc, char **argv)
  3079. {
  3080. int ret = argc > 1 ? number(argv[1]) : exitstatus;
  3081. if (funcnest) {
  3082. evalskip = SKIPFUNC;
  3083. skipcount = 1;
  3084. return ret;
  3085. }
  3086. else {
  3087. /* Do what ksh does; skip the rest of the file */
  3088. evalskip = SKIPFILE;
  3089. skipcount = 1;
  3090. return ret;
  3091. }
  3092. }
  3093. static int
  3094. falsecmd(int argc, char **argv)
  3095. {
  3096. return 1;
  3097. }
  3098. static int
  3099. truecmd(int argc, char **argv)
  3100. {
  3101. return 0;
  3102. }
  3103. static int
  3104. execcmd(int argc, char **argv)
  3105. {
  3106. if (argc > 1) {
  3107. iflag = 0; /* exit on error */
  3108. mflag = 0;
  3109. optschanged();
  3110. shellexec(argv + 1, pathval(), 0);
  3111. }
  3112. return 0;
  3113. }
  3114. /* $NetBSD: exec.c,v 1.35 2003/01/22 20:36:04 dsl Exp $ */
  3115. /*
  3116. * When commands are first encountered, they are entered in a hash table.
  3117. * This ensures that a full path search will not have to be done for them
  3118. * on each invocation.
  3119. *
  3120. * We should investigate converting to a linear search, even though that
  3121. * would make the command name "hash" a misnomer.
  3122. */
  3123. #define CMDTABLESIZE 31 /* should be prime */
  3124. #define ARB 1 /* actual size determined at run time */
  3125. struct tblentry {
  3126. struct tblentry *next; /* next entry in hash chain */
  3127. union param param; /* definition of builtin function */
  3128. short cmdtype; /* index identifying command */
  3129. char rehash; /* if set, cd done since entry created */
  3130. char cmdname[ARB]; /* name of command */
  3131. };
  3132. static struct tblentry *cmdtable[CMDTABLESIZE];
  3133. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  3134. static void tryexec(char *, char **, char **);
  3135. static void clearcmdentry(int);
  3136. static struct tblentry *cmdlookup(const char *, int);
  3137. static void delete_cmd_entry(void);
  3138. /*
  3139. * Exec a program. Never returns. If you change this routine, you may
  3140. * have to change the find_command routine as well.
  3141. */
  3142. static void
  3143. shellexec(char **argv, const char *path, int idx)
  3144. {
  3145. char *cmdname;
  3146. int e;
  3147. char **envp;
  3148. clearredir(1);
  3149. envp = environment();
  3150. if (strchr(argv[0], '/') != NULL
  3151. #ifdef BB_FEATURE_SH_STANDALONE_SHELL
  3152. || find_applet_by_name(argv[0])
  3153. #endif
  3154. ) {
  3155. tryexec(argv[0], argv, envp);
  3156. e = errno;
  3157. } else {
  3158. e = ENOENT;
  3159. while ((cmdname = padvance(&path, argv[0])) != NULL) {
  3160. if (--idx < 0 && pathopt == NULL) {
  3161. tryexec(cmdname, argv, envp);
  3162. if (errno != ENOENT && errno != ENOTDIR)
  3163. e = errno;
  3164. }
  3165. stunalloc(cmdname);
  3166. }
  3167. }
  3168. /* Map to POSIX errors */
  3169. switch (e) {
  3170. case EACCES:
  3171. exerrno = 126;
  3172. break;
  3173. case ENOENT:
  3174. exerrno = 127;
  3175. break;
  3176. default:
  3177. exerrno = 2;
  3178. break;
  3179. }
  3180. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  3181. argv[0], e, suppressint ));
  3182. exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
  3183. /* NOTREACHED */
  3184. }
  3185. static void
  3186. tryexec(char *cmd, char **argv, char **envp)
  3187. {
  3188. int repeated = 0;
  3189. #ifdef BB_FEATURE_SH_STANDALONE_SHELL
  3190. int flg_bb = 0;
  3191. char *name = cmd;
  3192. #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
  3193. name = bb_get_last_path_component(name);
  3194. if(find_applet_by_name(name) != NULL)
  3195. flg_bb = 1;
  3196. #else
  3197. if(strchr(name, '/') == NULL && find_applet_by_name(name) != NULL) {
  3198. flg_bb = 1;
  3199. }
  3200. #endif
  3201. if(flg_bb) {
  3202. char **ap;
  3203. char **new;
  3204. *argv = name;
  3205. if(strcmp(name, "busybox")) {
  3206. for (ap = argv; *ap; ap++);
  3207. ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
  3208. *ap++ = cmd = "/bin/busybox";
  3209. while ((*ap++ = *argv++));
  3210. argv = new;
  3211. repeated++;
  3212. } else {
  3213. cmd = "/bin/busybox";
  3214. }
  3215. }
  3216. #endif
  3217. repeat:
  3218. #ifdef SYSV
  3219. do {
  3220. execve(cmd, argv, envp);
  3221. } while (errno == EINTR);
  3222. #else
  3223. execve(cmd, argv, envp);
  3224. #endif
  3225. if (repeated++) {
  3226. ckfree(argv);
  3227. } else if (errno == ENOEXEC) {
  3228. char **ap;
  3229. char **new;
  3230. for (ap = argv; *ap; ap++)
  3231. ;
  3232. ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
  3233. ap[1] = cmd;
  3234. *ap = cmd = (char *)"/bin/sh";
  3235. ap += 2;
  3236. argv++;
  3237. while ((*ap++ = *argv++))
  3238. ;
  3239. argv = new;
  3240. goto repeat;
  3241. }
  3242. }
  3243. /*
  3244. * Do a path search. The variable path (passed by reference) should be
  3245. * set to the start of the path before the first call; padvance will update
  3246. * this value as it proceeds. Successive calls to padvance will return
  3247. * the possible path expansions in sequence. If an option (indicated by
  3248. * a percent sign) appears in the path entry then the global variable
  3249. * pathopt will be set to point to it; otherwise pathopt will be set to
  3250. * NULL.
  3251. */
  3252. static char *
  3253. padvance(const char **path, const char *name)
  3254. {
  3255. const char *p;
  3256. char *q;
  3257. const char *start;
  3258. size_t len;
  3259. if (*path == NULL)
  3260. return NULL;
  3261. start = *path;
  3262. for (p = start ; *p && *p != ':' && *p != '%' ; p++);
  3263. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  3264. while (stackblocksize() < len)
  3265. growstackblock();
  3266. q = stackblock();
  3267. if (p != start) {
  3268. memcpy(q, start, p - start);
  3269. q += p - start;
  3270. *q++ = '/';
  3271. }
  3272. strcpy(q, name);
  3273. pathopt = NULL;
  3274. if (*p == '%') {
  3275. pathopt = ++p;
  3276. while (*p && *p != ':') p++;
  3277. }
  3278. if (*p == ':')
  3279. *path = p + 1;
  3280. else
  3281. *path = NULL;
  3282. return stalloc(len);
  3283. }
  3284. /*** Command hashing code ***/
  3285. static void
  3286. printentry(struct tblentry *cmdp)
  3287. {
  3288. int idx;
  3289. const char *path;
  3290. char *name;
  3291. idx = cmdp->param.index;
  3292. path = pathval();
  3293. do {
  3294. name = padvance(&path, cmdp->cmdname);
  3295. stunalloc(name);
  3296. } while (--idx >= 0);
  3297. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  3298. }
  3299. static int
  3300. hashcmd(int argc, char **argv)
  3301. {
  3302. struct tblentry **pp;
  3303. struct tblentry *cmdp;
  3304. int c;
  3305. struct cmdentry entry;
  3306. char *name;
  3307. while ((c = nextopt("r")) != '\0') {
  3308. clearcmdentry(0);
  3309. return 0;
  3310. }
  3311. if (*argptr == NULL) {
  3312. for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
  3313. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3314. if (cmdp->cmdtype == CMDNORMAL)
  3315. printentry(cmdp);
  3316. }
  3317. }
  3318. return 0;
  3319. }
  3320. c = 0;
  3321. while ((name = *argptr) != NULL) {
  3322. if ((cmdp = cmdlookup(name, 0)) != NULL
  3323. && (cmdp->cmdtype == CMDNORMAL
  3324. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
  3325. delete_cmd_entry();
  3326. find_command(name, &entry, DO_ERR, pathval());
  3327. if (entry.cmdtype == CMDUNKNOWN)
  3328. c = 1;
  3329. argptr++;
  3330. }
  3331. return c;
  3332. }
  3333. /*
  3334. * Resolve a command name. If you change this routine, you may have to
  3335. * change the shellexec routine as well.
  3336. */
  3337. static void
  3338. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  3339. {
  3340. struct tblentry *cmdp;
  3341. int idx;
  3342. int prev;
  3343. char *fullname;
  3344. struct stat statb;
  3345. int e;
  3346. int updatetbl;
  3347. struct builtincmd *bcmd;
  3348. /* If name contains a slash, don't use PATH or hash table */
  3349. if (strchr(name, '/') != NULL) {
  3350. entry->u.index = -1;
  3351. if (act & DO_ABS) {
  3352. while (stat(name, &statb) < 0) {
  3353. #ifdef SYSV
  3354. if (errno == EINTR)
  3355. continue;
  3356. #endif
  3357. entry->cmdtype = CMDUNKNOWN;
  3358. return;
  3359. }
  3360. }
  3361. entry->cmdtype = CMDNORMAL;
  3362. return;
  3363. }
  3364. #ifdef BB_FEATURE_SH_STANDALONE_SHELL
  3365. if (find_applet_by_name(name)) {
  3366. entry->cmdtype = CMDNORMAL;
  3367. entry->u.index = -1;
  3368. return;
  3369. }
  3370. #endif
  3371. updatetbl = (path == pathval());
  3372. if (!updatetbl) {
  3373. act |= DO_ALTPATH;
  3374. if (strstr(path, "%builtin") != NULL)
  3375. act |= DO_ALTBLTIN;
  3376. }
  3377. /* If name is in the table, check answer will be ok */
  3378. if ((cmdp = cmdlookup(name, 0)) != NULL) {
  3379. int bit;
  3380. switch (cmdp->cmdtype) {
  3381. default:
  3382. #if DEBUG
  3383. abort();
  3384. #endif
  3385. case CMDNORMAL:
  3386. bit = DO_ALTPATH;
  3387. break;
  3388. case CMDFUNCTION:
  3389. bit = DO_NOFUNC;
  3390. break;
  3391. case CMDBUILTIN:
  3392. bit = DO_ALTBLTIN;
  3393. break;
  3394. }
  3395. if (act & bit) {
  3396. updatetbl = 0;
  3397. cmdp = NULL;
  3398. } else if (cmdp->rehash == 0)
  3399. /* if not invalidated by cd, we're done */
  3400. goto success;
  3401. }
  3402. /* If %builtin not in path, check for builtin next */
  3403. bcmd = find_builtin(name);
  3404. if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
  3405. act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
  3406. )))
  3407. goto builtin_success;
  3408. /* We have to search path. */
  3409. prev = -1; /* where to start */
  3410. if (cmdp && cmdp->rehash) { /* doing a rehash */
  3411. if (cmdp->cmdtype == CMDBUILTIN)
  3412. prev = builtinloc;
  3413. else
  3414. prev = cmdp->param.index;
  3415. }
  3416. e = ENOENT;
  3417. idx = -1;
  3418. loop:
  3419. while ((fullname = padvance(&path, name)) != NULL) {
  3420. stunalloc(fullname);
  3421. idx++;
  3422. if (pathopt) {
  3423. if (prefix(pathopt, "builtin")) {
  3424. if (bcmd)
  3425. goto builtin_success;
  3426. continue;
  3427. } else if (!(act & DO_NOFUNC) &&
  3428. prefix(pathopt, "func")) {
  3429. /* handled below */
  3430. } else {
  3431. /* ignore unimplemented options */
  3432. continue;
  3433. }
  3434. }
  3435. /* if rehash, don't redo absolute path names */
  3436. if (fullname[0] == '/' && idx <= prev) {
  3437. if (idx < prev)
  3438. continue;
  3439. TRACE(("searchexec \"%s\": no change\n", name));
  3440. goto success;
  3441. }
  3442. while (stat(fullname, &statb) < 0) {
  3443. #ifdef SYSV
  3444. if (errno == EINTR)
  3445. continue;
  3446. #endif
  3447. if (errno != ENOENT && errno != ENOTDIR)
  3448. e = errno;
  3449. goto loop;
  3450. }
  3451. e = EACCES; /* if we fail, this will be the error */
  3452. if (!S_ISREG(statb.st_mode))
  3453. continue;
  3454. if (pathopt) { /* this is a %func directory */
  3455. stalloc(strlen(fullname) + 1);
  3456. readcmdfile(fullname);
  3457. if ((cmdp = cmdlookup(name, 0)) == NULL ||
  3458. cmdp->cmdtype != CMDFUNCTION)
  3459. error("%s not defined in %s", name, fullname);
  3460. stunalloc(fullname);
  3461. goto success;
  3462. }
  3463. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  3464. if (!updatetbl) {
  3465. entry->cmdtype = CMDNORMAL;
  3466. entry->u.index = idx;
  3467. return;
  3468. }
  3469. INTOFF;
  3470. cmdp = cmdlookup(name, 1);
  3471. cmdp->cmdtype = CMDNORMAL;
  3472. cmdp->param.index = idx;
  3473. INTON;
  3474. goto success;
  3475. }
  3476. /* We failed. If there was an entry for this command, delete it */
  3477. if (cmdp && updatetbl)
  3478. delete_cmd_entry();
  3479. if (act & DO_ERR)
  3480. sh_warnx("%s: %s", name, errmsg(e, E_EXEC));
  3481. entry->cmdtype = CMDUNKNOWN;
  3482. return;
  3483. builtin_success:
  3484. if (!updatetbl) {
  3485. entry->cmdtype = CMDBUILTIN;
  3486. entry->u.cmd = bcmd;
  3487. return;
  3488. }
  3489. INTOFF;
  3490. cmdp = cmdlookup(name, 1);
  3491. cmdp->cmdtype = CMDBUILTIN;
  3492. cmdp->param.cmd = bcmd;
  3493. INTON;
  3494. success:
  3495. cmdp->rehash = 0;
  3496. entry->cmdtype = cmdp->cmdtype;
  3497. entry->u = cmdp->param;
  3498. }
  3499. /*
  3500. * Wrapper around strcmp for qsort/bsearch/...
  3501. */
  3502. static int pstrcmp(const void *a, const void *b)
  3503. {
  3504. return strcmp((const char *) a, (*(const char *const *) b) + 1);
  3505. }
  3506. /*
  3507. * Search the table of builtin commands.
  3508. */
  3509. static struct builtincmd *
  3510. find_builtin(const char *name)
  3511. {
  3512. struct builtincmd *bp;
  3513. bp = bsearch(
  3514. name, builtincmd, NUMBUILTINS, sizeof(struct builtincmd),
  3515. pstrcmp
  3516. );
  3517. return bp;
  3518. }
  3519. /*
  3520. * Called when a cd is done. Marks all commands so the next time they
  3521. * are executed they will be rehashed.
  3522. */
  3523. static void
  3524. hashcd(void)
  3525. {
  3526. struct tblentry **pp;
  3527. struct tblentry *cmdp;
  3528. for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
  3529. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3530. if (cmdp->cmdtype == CMDNORMAL || (
  3531. cmdp->cmdtype == CMDBUILTIN &&
  3532. !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
  3533. builtinloc > 0
  3534. ))
  3535. cmdp->rehash = 1;
  3536. }
  3537. }
  3538. }
  3539. /*
  3540. * Fix command hash table when PATH changed.
  3541. * Called before PATH is changed. The argument is the new value of PATH;
  3542. * pathval() still returns the old value at this point.
  3543. * Called with interrupts off.
  3544. */
  3545. static void
  3546. changepath(const char *newval)
  3547. {
  3548. const char *old, *new;
  3549. int idx;
  3550. int firstchange;
  3551. int idx_bltin;
  3552. old = pathval();
  3553. new = newval;
  3554. firstchange = 9999; /* assume no change */
  3555. idx = 0;
  3556. idx_bltin = -1;
  3557. for (;;) {
  3558. if (*old != *new) {
  3559. firstchange = idx;
  3560. if ((*old == '\0' && *new == ':')
  3561. || (*old == ':' && *new == '\0'))
  3562. firstchange++;
  3563. old = new; /* ignore subsequent differences */
  3564. }
  3565. if (*new == '\0')
  3566. break;
  3567. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  3568. idx_bltin = idx;
  3569. if (*new == ':') {
  3570. idx++;
  3571. }
  3572. new++, old++;
  3573. }
  3574. if (builtinloc < 0 && idx_bltin >= 0)
  3575. builtinloc = idx_bltin; /* zap builtins */
  3576. if (builtinloc >= 0 && idx_bltin < 0)
  3577. firstchange = 0;
  3578. clearcmdentry(firstchange);
  3579. builtinloc = idx_bltin;
  3580. }
  3581. /*
  3582. * Clear out command entries. The argument specifies the first entry in
  3583. * PATH which has changed.
  3584. */
  3585. static void
  3586. clearcmdentry(int firstchange)
  3587. {
  3588. struct tblentry **tblp;
  3589. struct tblentry **pp;
  3590. struct tblentry *cmdp;
  3591. INTOFF;
  3592. for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
  3593. pp = tblp;
  3594. while ((cmdp = *pp) != NULL) {
  3595. if ((cmdp->cmdtype == CMDNORMAL &&
  3596. cmdp->param.index >= firstchange)
  3597. || (cmdp->cmdtype == CMDBUILTIN &&
  3598. builtinloc >= firstchange)) {
  3599. *pp = cmdp->next;
  3600. ckfree(cmdp);
  3601. } else {
  3602. pp = &cmdp->next;
  3603. }
  3604. }
  3605. }
  3606. INTON;
  3607. }
  3608. /*
  3609. * Locate a command in the command hash table. If "add" is nonzero,
  3610. * add the command to the table if it is not already present. The
  3611. * variable "lastcmdentry" is set to point to the address of the link
  3612. * pointing to the entry, so that delete_cmd_entry can delete the
  3613. * entry.
  3614. *
  3615. * Interrupts must be off if called with add != 0.
  3616. */
  3617. static struct tblentry **lastcmdentry;
  3618. static struct tblentry *
  3619. cmdlookup(const char *name, int add)
  3620. {
  3621. unsigned int hashval;
  3622. const char *p;
  3623. struct tblentry *cmdp;
  3624. struct tblentry **pp;
  3625. p = name;
  3626. hashval = (unsigned char)*p << 4;
  3627. while (*p)
  3628. hashval += (unsigned char)*p++;
  3629. hashval &= 0x7FFF;
  3630. pp = &cmdtable[hashval % CMDTABLESIZE];
  3631. for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
  3632. if (equal(cmdp->cmdname, name))
  3633. break;
  3634. pp = &cmdp->next;
  3635. }
  3636. if (add && cmdp == NULL) {
  3637. cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
  3638. + strlen(name) + 1);
  3639. cmdp->next = NULL;
  3640. cmdp->cmdtype = CMDUNKNOWN;
  3641. strcpy(cmdp->cmdname, name);
  3642. }
  3643. lastcmdentry = pp;
  3644. return cmdp;
  3645. }
  3646. /*
  3647. * Delete the command entry returned on the last lookup.
  3648. */
  3649. static void
  3650. delete_cmd_entry(void)
  3651. {
  3652. struct tblentry *cmdp;
  3653. INTOFF;
  3654. cmdp = *lastcmdentry;
  3655. *lastcmdentry = cmdp->next;
  3656. if (cmdp->cmdtype == CMDFUNCTION)
  3657. freefunc(cmdp->param.func);
  3658. ckfree(cmdp);
  3659. INTON;
  3660. }
  3661. /*
  3662. * Add a new command entry, replacing any existing command entry for
  3663. * the same name - except special builtins.
  3664. */
  3665. static inline void
  3666. addcmdentry(char *name, struct cmdentry *entry)
  3667. {
  3668. struct tblentry *cmdp;
  3669. cmdp = cmdlookup(name, 1);
  3670. if (cmdp->cmdtype == CMDFUNCTION) {
  3671. freefunc(cmdp->param.func);
  3672. }
  3673. cmdp->cmdtype = entry->cmdtype;
  3674. cmdp->param = entry->u;
  3675. cmdp->rehash = 0;
  3676. }
  3677. /*
  3678. * Make a copy of a parse tree.
  3679. */
  3680. static inline struct funcnode *
  3681. copyfunc(union node *n)
  3682. {
  3683. struct funcnode *f;
  3684. size_t blocksize;
  3685. funcblocksize = offsetof(struct funcnode, n);
  3686. funcstringsize = 0;
  3687. calcsize(n);
  3688. blocksize = funcblocksize;
  3689. f = ckmalloc(blocksize + funcstringsize);
  3690. funcblock = (char *) f + offsetof(struct funcnode, n);
  3691. funcstring = (char *) f + blocksize;
  3692. copynode(n);
  3693. f->count = 0;
  3694. return f;
  3695. }
  3696. /*
  3697. * Define a shell function.
  3698. */
  3699. static void
  3700. defun(char *name, union node *func)
  3701. {
  3702. struct cmdentry entry;
  3703. INTOFF;
  3704. entry.cmdtype = CMDFUNCTION;
  3705. entry.u.func = copyfunc(func);
  3706. addcmdentry(name, &entry);
  3707. INTON;
  3708. }
  3709. /*
  3710. * Delete a function if it exists.
  3711. */
  3712. static void
  3713. unsetfunc(const char *name)
  3714. {
  3715. struct tblentry *cmdp;
  3716. if ((cmdp = cmdlookup(name, 0)) != NULL &&
  3717. cmdp->cmdtype == CMDFUNCTION)
  3718. delete_cmd_entry();
  3719. }
  3720. /*
  3721. * Locate and print what a word is...
  3722. */
  3723. #ifdef BB_ASH_CMDCMD
  3724. static int
  3725. describe_command(char *command, int describe_command_verbose)
  3726. #else
  3727. #define describe_command_verbose 1
  3728. static int
  3729. describe_command(char *command)
  3730. #endif
  3731. {
  3732. struct cmdentry entry;
  3733. struct tblentry *cmdp;
  3734. #ifdef BB_ASH_ALIAS
  3735. const struct alias *ap;
  3736. #endif
  3737. const char *path = pathval();
  3738. if (describe_command_verbose) {
  3739. out1str(command);
  3740. }
  3741. /* First look at the keywords */
  3742. if (findkwd(command)) {
  3743. out1str(describe_command_verbose ? " is a shell keyword" : command);
  3744. goto out;
  3745. }
  3746. #ifdef BB_ASH_ALIAS
  3747. /* Then look at the aliases */
  3748. if ((ap = lookupalias(command, 0)) != NULL) {
  3749. if (describe_command_verbose) {
  3750. out1fmt(" is an alias for %s", ap->val);
  3751. } else {
  3752. out1str("alias ");
  3753. printalias(ap);
  3754. return 0;
  3755. }
  3756. goto out;
  3757. }
  3758. #endif
  3759. /* Then check if it is a tracked alias */
  3760. if ((cmdp = cmdlookup(command, 0)) != NULL) {
  3761. entry.cmdtype = cmdp->cmdtype;
  3762. entry.u = cmdp->param;
  3763. } else {
  3764. /* Finally use brute force */
  3765. find_command(command, &entry, DO_ABS, path);
  3766. }
  3767. switch (entry.cmdtype) {
  3768. case CMDNORMAL: {
  3769. int j = entry.u.index;
  3770. char *p;
  3771. if (j == -1) {
  3772. p = command;
  3773. } else {
  3774. do {
  3775. p = padvance(&path, command);
  3776. stunalloc(p);
  3777. } while (--j >= 0);
  3778. }
  3779. if (describe_command_verbose) {
  3780. out1fmt(" is%s %s",
  3781. (cmdp ? " a tracked alias for" : nullstr), p
  3782. );
  3783. } else {
  3784. out1str(p);
  3785. }
  3786. break;
  3787. }
  3788. case CMDFUNCTION:
  3789. if (describe_command_verbose) {
  3790. out1str(" is a shell function");
  3791. } else {
  3792. out1str(command);
  3793. }
  3794. break;
  3795. case CMDBUILTIN:
  3796. if (describe_command_verbose) {
  3797. out1fmt(" is a %sshell builtin",
  3798. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  3799. "special " : nullstr
  3800. );
  3801. } else {
  3802. out1str(command);
  3803. }
  3804. break;
  3805. default:
  3806. if (describe_command_verbose) {
  3807. out1str(": not found\n");
  3808. }
  3809. return 127;
  3810. }
  3811. out:
  3812. outstr("\n", stdout);
  3813. return 0;
  3814. }
  3815. static int
  3816. typecmd(int argc, char **argv)
  3817. {
  3818. int i;
  3819. int err = 0;
  3820. for (i = 1; i < argc; i++) {
  3821. #ifdef BB_ASH_CMDCMD
  3822. err |= describe_command(argv[i], 1);
  3823. #else
  3824. err |= describe_command(argv[i]);
  3825. #endif
  3826. }
  3827. return err;
  3828. }
  3829. #ifdef BB_ASH_CMDCMD
  3830. static int
  3831. commandcmd(int argc, char **argv)
  3832. {
  3833. int c;
  3834. int default_path = 0;
  3835. int verify_only = 0;
  3836. int verbose_verify_only = 0;
  3837. while ((c = nextopt("pvV")) != '\0')
  3838. switch (c) {
  3839. default:
  3840. #ifdef DEBUG
  3841. fprintf(stderr,
  3842. "command: nextopt returned character code 0%o\n", c);
  3843. return EX_SOFTWARE;
  3844. #endif
  3845. case 'p':
  3846. default_path = 1;
  3847. break;
  3848. case 'v':
  3849. verify_only = 1;
  3850. break;
  3851. case 'V':
  3852. verbose_verify_only = 1;
  3853. break;
  3854. }
  3855. if (default_path + verify_only + verbose_verify_only > 1 ||
  3856. !*argptr) {
  3857. fprintf(stderr,
  3858. "command [-p] command [arg ...]\n"
  3859. "command {-v|-V} command\n");
  3860. return EX_USAGE;
  3861. }
  3862. if (verify_only || verbose_verify_only) {
  3863. return describe_command(*argptr, verbose_verify_only);
  3864. }
  3865. return 0;
  3866. }
  3867. #endif
  3868. /* $NetBSD: expand.c,v 1.56 2002/11/24 22:35:39 christos Exp $ */
  3869. /*
  3870. * Routines to expand arguments to commands. We have to deal with
  3871. * backquotes, shell variables, and file metacharacters.
  3872. */
  3873. /*
  3874. * _rmescape() flags
  3875. */
  3876. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  3877. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  3878. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  3879. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  3880. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  3881. /*
  3882. * Structure specifying which parts of the string should be searched
  3883. * for IFS characters.
  3884. */
  3885. struct ifsregion {
  3886. struct ifsregion *next; /* next region in list */
  3887. int begoff; /* offset of start of region */
  3888. int endoff; /* offset of end of region */
  3889. int nulonly; /* search for nul bytes only */
  3890. };
  3891. /* output of current string */
  3892. static char *expdest;
  3893. /* list of back quote expressions */
  3894. static struct nodelist *argbackq;
  3895. /* first struct in list of ifs regions */
  3896. static struct ifsregion ifsfirst;
  3897. /* last struct in list */
  3898. static struct ifsregion *ifslastp;
  3899. /* holds expanded arg list */
  3900. static struct arglist exparg;
  3901. static void argstr(char *, int);
  3902. static char *exptilde(char *, char *, int);
  3903. static void expbackq(union node *, int, int);
  3904. static const char *subevalvar(char *, char *, int, int, int, int, int);
  3905. static char *evalvar(char *, int);
  3906. static int varisset(char *, int);
  3907. static void strtodest(const char *, int, int);
  3908. static void memtodest(const char *p, size_t len, int syntax, int quotes);
  3909. static void varvalue(char *, int, int);
  3910. static void recordregion(int, int, int);
  3911. static void removerecordregions(int);
  3912. static void ifsbreakup(char *, struct arglist *);
  3913. static void ifsfree(void);
  3914. static void expandmeta(struct strlist *, int);
  3915. static int patmatch(char *, const char *);
  3916. static int cvtnum(long);
  3917. static size_t esclen(const char *, const char *);
  3918. static char *scanleft(char *, char *, char *, char *, int, int);
  3919. static char *scanright(char *, char *, char *, char *, int, int);
  3920. static void varunset(const char *, const char *, const char *, int)
  3921. __attribute__((__noreturn__));
  3922. #define pmatch(a, b) !fnmatch((a), (b), 0)
  3923. /*
  3924. * Prepare a pattern for a expmeta (internal glob(3)) call.
  3925. *
  3926. * Returns an stalloced string.
  3927. */
  3928. static inline char *
  3929. preglob(const char *pattern, int quoted, int flag) {
  3930. flag |= RMESCAPE_GLOB;
  3931. if (quoted) {
  3932. flag |= RMESCAPE_QUOTED;
  3933. }
  3934. return _rmescapes((char *)pattern, flag);
  3935. }
  3936. static size_t
  3937. esclen(const char *start, const char *p) {
  3938. size_t esc = 0;
  3939. while (p > start && *--p == CTLESC) {
  3940. esc++;
  3941. }
  3942. return esc;
  3943. }
  3944. /*
  3945. * Expand shell variables and backquotes inside a here document.
  3946. */
  3947. static inline void
  3948. expandhere(union node *arg, int fd)
  3949. {
  3950. herefd = fd;
  3951. expandarg(arg, (struct arglist *)NULL, 0);
  3952. xwrite(fd, stackblock(), expdest - (char *)stackblock());
  3953. }
  3954. /*
  3955. * Perform variable substitution and command substitution on an argument,
  3956. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  3957. * perform splitting and file name expansion. When arglist is NULL, perform
  3958. * here document expansion.
  3959. */
  3960. void
  3961. expandarg(union node *arg, struct arglist *arglist, int flag)
  3962. {
  3963. struct strlist *sp;
  3964. char *p;
  3965. argbackq = arg->narg.backquote;
  3966. STARTSTACKSTR(expdest);
  3967. ifsfirst.next = NULL;
  3968. ifslastp = NULL;
  3969. argstr(arg->narg.text, flag);
  3970. if (arglist == NULL) {
  3971. return; /* here document expanded */
  3972. }
  3973. STPUTC('\0', expdest);
  3974. p = grabstackstr(expdest);
  3975. exparg.lastp = &exparg.list;
  3976. /*
  3977. * TODO - EXP_REDIR
  3978. */
  3979. if (flag & EXP_FULL) {
  3980. ifsbreakup(p, &exparg);
  3981. *exparg.lastp = NULL;
  3982. exparg.lastp = &exparg.list;
  3983. expandmeta(exparg.list, flag);
  3984. } else {
  3985. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  3986. rmescapes(p);
  3987. sp = (struct strlist *)stalloc(sizeof (struct strlist));
  3988. sp->text = p;
  3989. *exparg.lastp = sp;
  3990. exparg.lastp = &sp->next;
  3991. }
  3992. if (ifsfirst.next)
  3993. ifsfree();
  3994. *exparg.lastp = NULL;
  3995. if (exparg.list) {
  3996. *arglist->lastp = exparg.list;
  3997. arglist->lastp = exparg.lastp;
  3998. }
  3999. }
  4000. /*
  4001. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  4002. * characters to allow for further processing. Otherwise treat
  4003. * $@ like $* since no splitting will be performed.
  4004. */
  4005. static void
  4006. argstr(char *p, int flag)
  4007. {
  4008. static const char spclchars[] = {
  4009. '=',
  4010. ':',
  4011. CTLQUOTEMARK,
  4012. CTLENDVAR,
  4013. CTLESC,
  4014. CTLVAR,
  4015. CTLBACKQ,
  4016. CTLBACKQ | CTLQUOTE,
  4017. #ifdef BB_ASH_MATH_SUPPORT
  4018. CTLENDARI,
  4019. #endif
  4020. 0
  4021. };
  4022. const char *reject = spclchars;
  4023. int c;
  4024. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  4025. int breakall = flag & EXP_WORD;
  4026. int inquotes;
  4027. size_t length;
  4028. int startloc;
  4029. if (!(flag & EXP_VARTILDE)) {
  4030. reject += 2;
  4031. } else if (flag & EXP_VARTILDE2) {
  4032. reject++;
  4033. }
  4034. inquotes = 0;
  4035. length = 0;
  4036. if (flag & EXP_TILDE) {
  4037. char *q;
  4038. flag &= ~EXP_TILDE;
  4039. tilde:
  4040. q = p;
  4041. if (*q == CTLESC && (flag & EXP_QWORD))
  4042. q++;
  4043. if (*q == '~')
  4044. p = exptilde(p, q, flag);
  4045. }
  4046. start:
  4047. startloc = expdest - (char *)stackblock();
  4048. for (;;) {
  4049. length += strcspn(p + length, reject);
  4050. c = p[length];
  4051. if (c && (!(c & 0x80)
  4052. #ifdef BB_ASH_MATH_SUPPORT
  4053. || c == CTLENDARI
  4054. #endif
  4055. )) {
  4056. /* c == '=' || c == ':' || c == CTLENDARI */
  4057. length++;
  4058. }
  4059. if (length > 0) {
  4060. int newloc;
  4061. expdest = stnputs(p, length, expdest);
  4062. newloc = expdest - (char *)stackblock();
  4063. if (breakall && !inquotes && newloc > startloc) {
  4064. recordregion(startloc, newloc, 0);
  4065. }
  4066. startloc = newloc;
  4067. }
  4068. p += length + 1;
  4069. length = 0;
  4070. switch (c) {
  4071. case '\0':
  4072. goto breakloop;
  4073. case '=':
  4074. if (flag & EXP_VARTILDE2) {
  4075. p--;
  4076. continue;
  4077. }
  4078. flag |= EXP_VARTILDE2;
  4079. reject++;
  4080. /* fall through */
  4081. case ':':
  4082. /*
  4083. * sort of a hack - expand tildes in variable
  4084. * assignments (after the first '=' and after ':'s).
  4085. */
  4086. if (*--p == '~') {
  4087. goto tilde;
  4088. }
  4089. continue;
  4090. }
  4091. switch (c) {
  4092. case CTLENDVAR: /* ??? */
  4093. goto breakloop;
  4094. case CTLQUOTEMARK:
  4095. /* "$@" syntax adherence hack */
  4096. if (
  4097. !inquotes &&
  4098. !memcmp(p, dolatstr, DOLATSTRLEN) &&
  4099. (p[4] == CTLQUOTEMARK || (
  4100. p[4] == CTLENDVAR &&
  4101. p[5] == CTLQUOTEMARK
  4102. ))
  4103. ) {
  4104. p = evalvar(p + 1, flag) + 1;
  4105. goto start;
  4106. }
  4107. inquotes = !inquotes;
  4108. addquote:
  4109. if (quotes) {
  4110. p--;
  4111. length++;
  4112. startloc++;
  4113. }
  4114. break;
  4115. case CTLESC:
  4116. startloc++;
  4117. length++;
  4118. goto addquote;
  4119. case CTLVAR:
  4120. p = evalvar(p, flag);
  4121. goto start;
  4122. case CTLBACKQ:
  4123. c = 0;
  4124. case CTLBACKQ|CTLQUOTE:
  4125. expbackq(argbackq->n, c, quotes);
  4126. argbackq = argbackq->next;
  4127. goto start;
  4128. #ifdef BB_ASH_MATH_SUPPORT
  4129. case CTLENDARI:
  4130. p--;
  4131. expari(quotes);
  4132. goto start;
  4133. #endif
  4134. }
  4135. }
  4136. breakloop:
  4137. ;
  4138. }
  4139. static char *
  4140. exptilde(char *startp, char *p, int flag)
  4141. {
  4142. char c;
  4143. char *name;
  4144. struct passwd *pw;
  4145. const char *home;
  4146. int quotes = flag & (EXP_FULL | EXP_CASE);
  4147. int startloc;
  4148. name = p + 1;
  4149. while ((c = *++p) != '\0') {
  4150. switch(c) {
  4151. case CTLESC:
  4152. return (startp);
  4153. case CTLQUOTEMARK:
  4154. return (startp);
  4155. case ':':
  4156. if (flag & EXP_VARTILDE)
  4157. goto done;
  4158. break;
  4159. case '/':
  4160. case CTLENDVAR:
  4161. goto done;
  4162. }
  4163. }
  4164. done:
  4165. *p = '\0';
  4166. if (*name == '\0') {
  4167. if ((home = lookupvar(homestr)) == NULL)
  4168. goto lose;
  4169. } else {
  4170. if ((pw = getpwnam(name)) == NULL)
  4171. goto lose;
  4172. home = pw->pw_dir;
  4173. }
  4174. if (*home == '\0')
  4175. goto lose;
  4176. *p = c;
  4177. startloc = expdest - (char *)stackblock();
  4178. strtodest(home, SQSYNTAX, quotes);
  4179. recordregion(startloc, expdest - (char *)stackblock(), 0);
  4180. return (p);
  4181. lose:
  4182. *p = c;
  4183. return (startp);
  4184. }
  4185. static void
  4186. removerecordregions(int endoff)
  4187. {
  4188. if (ifslastp == NULL)
  4189. return;
  4190. if (ifsfirst.endoff > endoff) {
  4191. while (ifsfirst.next != NULL) {
  4192. struct ifsregion *ifsp;
  4193. INTOFF;
  4194. ifsp = ifsfirst.next->next;
  4195. ckfree(ifsfirst.next);
  4196. ifsfirst.next = ifsp;
  4197. INTON;
  4198. }
  4199. if (ifsfirst.begoff > endoff)
  4200. ifslastp = NULL;
  4201. else {
  4202. ifslastp = &ifsfirst;
  4203. ifsfirst.endoff = endoff;
  4204. }
  4205. return;
  4206. }
  4207. ifslastp = &ifsfirst;
  4208. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4209. ifslastp=ifslastp->next;
  4210. while (ifslastp->next != NULL) {
  4211. struct ifsregion *ifsp;
  4212. INTOFF;
  4213. ifsp = ifslastp->next->next;
  4214. ckfree(ifslastp->next);
  4215. ifslastp->next = ifsp;
  4216. INTON;
  4217. }
  4218. if (ifslastp->endoff > endoff)
  4219. ifslastp->endoff = endoff;
  4220. }
  4221. #ifdef BB_ASH_MATH_SUPPORT
  4222. /*
  4223. * Expand arithmetic expression. Backup to start of expression,
  4224. * evaluate, place result in (backed up) result, adjust string position.
  4225. */
  4226. void
  4227. expari(int quotes)
  4228. {
  4229. char *p, *start;
  4230. int begoff;
  4231. int flag;
  4232. int len;
  4233. /* ifsfree(); */
  4234. /*
  4235. * This routine is slightly over-complicated for
  4236. * efficiency. Next we scan backwards looking for the
  4237. * start of arithmetic.
  4238. */
  4239. start = stackblock();
  4240. p = expdest - 1;
  4241. *p = '\0';
  4242. p--;
  4243. do {
  4244. int esc;
  4245. while (*p != CTLARI) {
  4246. p--;
  4247. #ifdef DEBUG
  4248. if (p < start) {
  4249. error("missing CTLARI (shouldn't happen)");
  4250. }
  4251. #endif
  4252. }
  4253. esc = esclen(start, p);
  4254. if (!(esc % 2)) {
  4255. break;
  4256. }
  4257. p -= esc + 1;
  4258. } while (1);
  4259. begoff = p - start;
  4260. removerecordregions(begoff);
  4261. flag = p[1];
  4262. expdest = p;
  4263. if (quotes)
  4264. rmescapes(p + 2);
  4265. len = cvtnum(dash_arith(p + 2));
  4266. if (flag != '"')
  4267. recordregion(begoff, begoff + len, 0);
  4268. }
  4269. #endif
  4270. /*
  4271. * Expand stuff in backwards quotes.
  4272. */
  4273. static void
  4274. expbackq(union node *cmd, int quoted, int quotes)
  4275. {
  4276. struct backcmd in;
  4277. int i;
  4278. char buf[128];
  4279. char *p;
  4280. char *dest;
  4281. int startloc;
  4282. int syntax = quoted? DQSYNTAX : BASESYNTAX;
  4283. struct stackmark smark;
  4284. INTOFF;
  4285. setstackmark(&smark);
  4286. dest = expdest;
  4287. startloc = dest - (char *)stackblock();
  4288. grabstackstr(dest);
  4289. evalbackcmd(cmd, (struct backcmd *) &in);
  4290. popstackmark(&smark);
  4291. p = in.buf;
  4292. i = in.nleft;
  4293. if (i == 0)
  4294. goto read;
  4295. for (;;) {
  4296. memtodest(p, i, syntax, quotes);
  4297. read:
  4298. if (in.fd < 0)
  4299. break;
  4300. i = safe_read(in.fd, buf, sizeof buf);
  4301. TRACE(("expbackq: read returns %d\n", i));
  4302. if (i <= 0)
  4303. break;
  4304. p = buf;
  4305. }
  4306. if (in.buf)
  4307. ckfree(in.buf);
  4308. if (in.fd >= 0) {
  4309. close(in.fd);
  4310. back_exitstatus = waitforjob(in.jp);
  4311. }
  4312. INTON;
  4313. /* Eat all trailing newlines */
  4314. dest = expdest;
  4315. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  4316. STUNPUTC(dest);
  4317. expdest = dest;
  4318. if (quoted == 0)
  4319. recordregion(startloc, dest - (char *)stackblock(), 0);
  4320. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  4321. (dest - (char *)stackblock()) - startloc,
  4322. (dest - (char *)stackblock()) - startloc,
  4323. stackblock() + startloc));
  4324. }
  4325. static char *
  4326. scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  4327. int zero)
  4328. {
  4329. char *loc;
  4330. char *loc2;
  4331. char c;
  4332. loc = startp;
  4333. loc2 = rmesc;
  4334. do {
  4335. int match;
  4336. const char *s = loc2;
  4337. c = *loc2;
  4338. if (zero) {
  4339. *loc2 = '\0';
  4340. s = rmesc;
  4341. }
  4342. match = pmatch(str, s);
  4343. *loc2 = c;
  4344. if (match)
  4345. return loc;
  4346. if (quotes && *loc == CTLESC)
  4347. loc++;
  4348. loc++;
  4349. loc2++;
  4350. } while (c);
  4351. return 0;
  4352. }
  4353. static char *
  4354. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  4355. int zero)
  4356. {
  4357. int esc = 0;
  4358. char *loc;
  4359. char *loc2;
  4360. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  4361. int match;
  4362. char c = *loc2;
  4363. const char *s = loc2;
  4364. if (zero) {
  4365. *loc2 = '\0';
  4366. s = rmesc;
  4367. }
  4368. match = pmatch(str, s);
  4369. *loc2 = c;
  4370. if (match)
  4371. return loc;
  4372. loc--;
  4373. if (quotes) {
  4374. if (--esc < 0) {
  4375. esc = esclen(startp, loc);
  4376. }
  4377. if (esc % 2) {
  4378. esc--;
  4379. loc--;
  4380. }
  4381. }
  4382. }
  4383. return 0;
  4384. }
  4385. static const char *
  4386. subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
  4387. {
  4388. char *startp;
  4389. char *loc;
  4390. int saveherefd = herefd;
  4391. struct nodelist *saveargbackq = argbackq;
  4392. int amount;
  4393. char *rmesc, *rmescend;
  4394. int zero;
  4395. char *(*scan)(char *, char *, char *, char *, int , int);
  4396. herefd = -1;
  4397. argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
  4398. STPUTC('\0', expdest);
  4399. herefd = saveherefd;
  4400. argbackq = saveargbackq;
  4401. startp = stackblock() + startloc;
  4402. switch (subtype) {
  4403. case VSASSIGN:
  4404. setvar(str, startp, 0);
  4405. amount = startp - expdest;
  4406. STADJUST(amount, expdest);
  4407. return startp;
  4408. case VSQUESTION:
  4409. varunset(p, str, startp, varflags);
  4410. /* NOTREACHED */
  4411. }
  4412. subtype -= VSTRIMRIGHT;
  4413. #ifdef DEBUG
  4414. if (subtype < 0 || subtype > 3)
  4415. abort();
  4416. #endif
  4417. rmesc = startp;
  4418. rmescend = stackblock() + strloc;
  4419. if (quotes) {
  4420. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  4421. if (rmesc != startp) {
  4422. rmescend = expdest;
  4423. startp = stackblock() + startloc;
  4424. }
  4425. }
  4426. rmescend--;
  4427. str = stackblock() + strloc;
  4428. preglob(str, varflags & VSQUOTE, 0);
  4429. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  4430. zero = subtype >> 1;
  4431. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  4432. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  4433. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  4434. if (loc) {
  4435. if (zero) {
  4436. memmove(startp, loc, str - loc);
  4437. loc = startp + (str - loc) - 1;
  4438. }
  4439. *loc = '\0';
  4440. amount = loc - expdest;
  4441. STADJUST(amount, expdest);
  4442. }
  4443. return loc;
  4444. }
  4445. /*
  4446. * Expand a variable, and return a pointer to the next character in the
  4447. * input string.
  4448. */
  4449. static char *
  4450. evalvar(char *p, int flag)
  4451. {
  4452. int subtype;
  4453. int varflags;
  4454. char *var;
  4455. int patloc;
  4456. int c;
  4457. int set;
  4458. int startloc;
  4459. size_t varlen;
  4460. int easy;
  4461. int quotes;
  4462. int quoted;
  4463. quotes = flag & (EXP_FULL | EXP_CASE);
  4464. varflags = *p++;
  4465. subtype = varflags & VSTYPE;
  4466. quoted = varflags & VSQUOTE;
  4467. var = p;
  4468. easy = (!quoted || (*var == '@' && shellparam.nparam));
  4469. varlen = 0;
  4470. startloc = expdest - (char *)stackblock();
  4471. p = strchr(p, '=') + 1;
  4472. if (!is_name(*var)) {
  4473. set = varisset(var, varflags & VSNUL);
  4474. set--;
  4475. if (subtype == VSPLUS)
  4476. goto vsplus;
  4477. if (++set) {
  4478. varvalue(var, quoted, flag);
  4479. if (subtype == VSLENGTH) {
  4480. varlen =
  4481. expdest - (char *)stackblock() -
  4482. startloc;
  4483. STADJUST(-varlen, expdest);
  4484. goto vslen;
  4485. }
  4486. }
  4487. } else {
  4488. const char *val;
  4489. again:
  4490. /* jump here after setting a variable with ${var=text} */
  4491. val = lookupvar(var);
  4492. set = !val || ((varflags & VSNUL) && !*val);
  4493. if (subtype == VSPLUS)
  4494. goto vsplus;
  4495. if (--set) {
  4496. varlen = strlen(val);
  4497. if (subtype == VSLENGTH)
  4498. goto vslen;
  4499. memtodest(
  4500. val, varlen, quoted ? DQSYNTAX : BASESYNTAX,
  4501. quotes
  4502. );
  4503. }
  4504. }
  4505. if (subtype == VSMINUS) {
  4506. vsplus:
  4507. if (!set) {
  4508. argstr(
  4509. p, flag | EXP_TILDE |
  4510. (quoted ? EXP_QWORD : EXP_WORD)
  4511. );
  4512. goto end;
  4513. }
  4514. if (easy)
  4515. goto record;
  4516. goto end;
  4517. }
  4518. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  4519. if (!set) {
  4520. if (subevalvar(p, var, 0, subtype, startloc,
  4521. varflags, 0)) {
  4522. varflags &= ~VSNUL;
  4523. /*
  4524. * Remove any recorded regions beyond
  4525. * start of variable
  4526. */
  4527. removerecordregions(startloc);
  4528. goto again;
  4529. }
  4530. goto end;
  4531. }
  4532. if (easy)
  4533. goto record;
  4534. goto end;
  4535. }
  4536. if (!set && uflag)
  4537. varunset(p, var, 0, 0);
  4538. if (subtype == VSLENGTH) {
  4539. vslen:
  4540. cvtnum(varlen);
  4541. goto record;
  4542. }
  4543. if (subtype == VSNORMAL) {
  4544. if (!easy)
  4545. goto end;
  4546. record:
  4547. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  4548. goto end;
  4549. }
  4550. #ifdef DEBUG
  4551. switch (subtype) {
  4552. case VSTRIMLEFT:
  4553. case VSTRIMLEFTMAX:
  4554. case VSTRIMRIGHT:
  4555. case VSTRIMRIGHTMAX:
  4556. break;
  4557. default:
  4558. abort();
  4559. }
  4560. #endif
  4561. if (set) {
  4562. /*
  4563. * Terminate the string and start recording the pattern
  4564. * right after it
  4565. */
  4566. STPUTC('\0', expdest);
  4567. patloc = expdest - (char *)stackblock();
  4568. if (subevalvar(p, NULL, patloc, subtype,
  4569. startloc, varflags, quotes) == 0) {
  4570. int amount = expdest - (
  4571. (char *)stackblock() + patloc - 1
  4572. );
  4573. STADJUST(-amount, expdest);
  4574. }
  4575. /* Remove any recorded regions beyond start of variable */
  4576. removerecordregions(startloc);
  4577. goto record;
  4578. }
  4579. end:
  4580. if (subtype != VSNORMAL) { /* skip to end of alternative */
  4581. int nesting = 1;
  4582. for (;;) {
  4583. if ((c = *p++) == CTLESC)
  4584. p++;
  4585. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  4586. if (set)
  4587. argbackq = argbackq->next;
  4588. } else if (c == CTLVAR) {
  4589. if ((*p++ & VSTYPE) != VSNORMAL)
  4590. nesting++;
  4591. } else if (c == CTLENDVAR) {
  4592. if (--nesting == 0)
  4593. break;
  4594. }
  4595. }
  4596. }
  4597. return p;
  4598. }
  4599. /*
  4600. * Test whether a specialized variable is set.
  4601. */
  4602. static int
  4603. varisset(char *name, int nulok)
  4604. {
  4605. if (*name == '!')
  4606. return backgndpid != 0;
  4607. else if (*name == '@' || *name == '*') {
  4608. if (*shellparam.p == NULL)
  4609. return 0;
  4610. if (nulok) {
  4611. char **av;
  4612. for (av = shellparam.p; *av; av++)
  4613. if (**av != '\0')
  4614. return 1;
  4615. return 0;
  4616. }
  4617. } else if (is_digit(*name)) {
  4618. char *ap;
  4619. int num = atoi(name);
  4620. if (num > shellparam.nparam)
  4621. return 0;
  4622. if (num == 0)
  4623. ap = arg0;
  4624. else
  4625. ap = shellparam.p[num - 1];
  4626. if (nulok && (ap == NULL || *ap == '\0'))
  4627. return 0;
  4628. }
  4629. return 1;
  4630. }
  4631. /*
  4632. * Put a string on the stack.
  4633. */
  4634. static void
  4635. memtodest(const char *p, size_t len, int syntax, int quotes) {
  4636. char *q = expdest;
  4637. q = makestrspace(len * 2, q);
  4638. while (len--) {
  4639. int c = *p++;
  4640. if (!c)
  4641. continue;
  4642. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4643. USTPUTC(CTLESC, q);
  4644. USTPUTC(c, q);
  4645. }
  4646. expdest = q;
  4647. }
  4648. static void
  4649. strtodest(const char *p, int syntax, int quotes)
  4650. {
  4651. memtodest(p, strlen(p), syntax, quotes);
  4652. }
  4653. /*
  4654. * Add the value of a specialized variable to the stack string.
  4655. */
  4656. static void
  4657. varvalue(char *name, int quoted, int flags)
  4658. {
  4659. int num;
  4660. char *p;
  4661. int i;
  4662. int sep;
  4663. int sepq = 0;
  4664. char **ap;
  4665. int syntax;
  4666. int allow_split = flags & EXP_FULL;
  4667. int quotes = flags & (EXP_FULL | EXP_CASE);
  4668. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  4669. switch (*name) {
  4670. case '$':
  4671. num = rootpid;
  4672. goto numvar;
  4673. case '?':
  4674. num = exitstatus;
  4675. goto numvar;
  4676. case '#':
  4677. num = shellparam.nparam;
  4678. goto numvar;
  4679. case '!':
  4680. num = backgndpid;
  4681. numvar:
  4682. cvtnum(num);
  4683. break;
  4684. case '-':
  4685. for (i = 0 ; i < NOPTS ; i++) {
  4686. if (optlist[i])
  4687. STPUTC(optletters(i), expdest);
  4688. }
  4689. break;
  4690. case '@':
  4691. if (allow_split && quoted) {
  4692. sep = 1 << CHAR_BIT;
  4693. goto param;
  4694. }
  4695. /* fall through */
  4696. case '*':
  4697. sep = ifsset() ? ifsval()[0] : ' ';
  4698. if (quotes) {
  4699. sepq = (SIT(sep, syntax) == CCTL) || (SIT(sep, syntax) == CBACK);
  4700. }
  4701. param:
  4702. for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
  4703. strtodest(p, syntax, quotes);
  4704. if (*ap && sep) {
  4705. p = expdest;
  4706. if (sepq)
  4707. STPUTC(CTLESC, p);
  4708. STPUTC(sep, p);
  4709. expdest = p;
  4710. }
  4711. }
  4712. break;
  4713. case '0':
  4714. strtodest(arg0, syntax, quotes);
  4715. break;
  4716. default:
  4717. num = atoi(name);
  4718. if (num > 0 && num <= shellparam.nparam) {
  4719. strtodest(shellparam.p[num - 1], syntax, quotes);
  4720. }
  4721. break;
  4722. }
  4723. }
  4724. /*
  4725. * Record the fact that we have to scan this region of the
  4726. * string for IFS characters.
  4727. */
  4728. static void
  4729. recordregion(int start, int end, int nulonly)
  4730. {
  4731. struct ifsregion *ifsp;
  4732. if (ifslastp == NULL) {
  4733. ifsp = &ifsfirst;
  4734. } else {
  4735. INTOFF;
  4736. ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
  4737. ifsp->next = NULL;
  4738. ifslastp->next = ifsp;
  4739. INTON;
  4740. }
  4741. ifslastp = ifsp;
  4742. ifslastp->begoff = start;
  4743. ifslastp->endoff = end;
  4744. ifslastp->nulonly = nulonly;
  4745. }
  4746. /*
  4747. * Break the argument string into pieces based upon IFS and add the
  4748. * strings to the argument list. The regions of the string to be
  4749. * searched for IFS characters have been stored by recordregion.
  4750. */
  4751. static void
  4752. ifsbreakup(char *string, struct arglist *arglist)
  4753. {
  4754. struct ifsregion *ifsp;
  4755. struct strlist *sp;
  4756. char *start;
  4757. char *p;
  4758. char *q;
  4759. const char *ifs, *realifs;
  4760. int ifsspc;
  4761. int nulonly;
  4762. start = string;
  4763. if (ifslastp != NULL) {
  4764. ifsspc = 0;
  4765. nulonly = 0;
  4766. realifs = ifsset() ? ifsval() : defifs;
  4767. ifsp = &ifsfirst;
  4768. do {
  4769. p = string + ifsp->begoff;
  4770. nulonly = ifsp->nulonly;
  4771. ifs = nulonly ? nullstr : realifs;
  4772. ifsspc = 0;
  4773. while (p < string + ifsp->endoff) {
  4774. q = p;
  4775. if (*p == CTLESC)
  4776. p++;
  4777. if (strchr(ifs, *p)) {
  4778. if (!nulonly)
  4779. ifsspc = (strchr(defifs, *p) != NULL);
  4780. /* Ignore IFS whitespace at start */
  4781. if (q == start && ifsspc) {
  4782. p++;
  4783. start = p;
  4784. continue;
  4785. }
  4786. *q = '\0';
  4787. sp = (struct strlist *)stalloc(sizeof *sp);
  4788. sp->text = start;
  4789. *arglist->lastp = sp;
  4790. arglist->lastp = &sp->next;
  4791. p++;
  4792. if (!nulonly) {
  4793. for (;;) {
  4794. if (p >= string + ifsp->endoff) {
  4795. break;
  4796. }
  4797. q = p;
  4798. if (*p == CTLESC)
  4799. p++;
  4800. if (strchr(ifs, *p) == NULL ) {
  4801. p = q;
  4802. break;
  4803. } else if (strchr(defifs, *p) == NULL) {
  4804. if (ifsspc) {
  4805. p++;
  4806. ifsspc = 0;
  4807. } else {
  4808. p = q;
  4809. break;
  4810. }
  4811. } else
  4812. p++;
  4813. }
  4814. }
  4815. start = p;
  4816. } else
  4817. p++;
  4818. }
  4819. } while ((ifsp = ifsp->next) != NULL);
  4820. if (nulonly)
  4821. goto add;
  4822. }
  4823. if (!*start)
  4824. return;
  4825. add:
  4826. sp = (struct strlist *)stalloc(sizeof *sp);
  4827. sp->text = start;
  4828. *arglist->lastp = sp;
  4829. arglist->lastp = &sp->next;
  4830. }
  4831. static void
  4832. ifsfree(void)
  4833. {
  4834. struct ifsregion *p;
  4835. INTOFF;
  4836. p = ifsfirst.next;
  4837. do {
  4838. struct ifsregion *ifsp;
  4839. ifsp = p->next;
  4840. ckfree(p);
  4841. p = ifsp;
  4842. } while (p);
  4843. ifslastp = NULL;
  4844. ifsfirst.next = NULL;
  4845. INTON;
  4846. }
  4847. static void expmeta(char *, char *);
  4848. static struct strlist *expsort(struct strlist *);
  4849. static struct strlist *msort(struct strlist *, int);
  4850. static char *expdir;
  4851. static void
  4852. expandmeta(struct strlist *str, int flag)
  4853. {
  4854. static const char metachars[] = {
  4855. '*', '?', '[', 0
  4856. };
  4857. /* TODO - EXP_REDIR */
  4858. while (str) {
  4859. struct strlist **savelastp;
  4860. struct strlist *sp;
  4861. char *p;
  4862. if (fflag)
  4863. goto nometa;
  4864. if (!strpbrk(str->text, metachars))
  4865. goto nometa;
  4866. savelastp = exparg.lastp;
  4867. INTOFF;
  4868. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  4869. {
  4870. int i = strlen(str->text);
  4871. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  4872. }
  4873. expmeta(expdir, p);
  4874. ckfree(expdir);
  4875. if (p != str->text)
  4876. ckfree(p);
  4877. INTON;
  4878. if (exparg.lastp == savelastp) {
  4879. /*
  4880. * no matches
  4881. */
  4882. nometa:
  4883. *exparg.lastp = str;
  4884. rmescapes(str->text);
  4885. exparg.lastp = &str->next;
  4886. } else {
  4887. *exparg.lastp = NULL;
  4888. *savelastp = sp = expsort(*savelastp);
  4889. while (sp->next != NULL)
  4890. sp = sp->next;
  4891. exparg.lastp = &sp->next;
  4892. }
  4893. str = str->next;
  4894. }
  4895. }
  4896. /*
  4897. * Add a file name to the list.
  4898. */
  4899. static void
  4900. addfname(const char *name)
  4901. {
  4902. struct strlist *sp;
  4903. sp = (struct strlist *)stalloc(sizeof *sp);
  4904. sp->text = sstrdup(name);
  4905. *exparg.lastp = sp;
  4906. exparg.lastp = &sp->next;
  4907. }
  4908. /*
  4909. * Do metacharacter (i.e. *, ?, [...]) expansion.
  4910. */
  4911. static void
  4912. expmeta(char *enddir, char *name)
  4913. {
  4914. char *p;
  4915. const char *cp;
  4916. char *start;
  4917. char *endname;
  4918. int metaflag;
  4919. struct stat statb;
  4920. DIR *dirp;
  4921. struct dirent *dp;
  4922. int atend;
  4923. int matchdot;
  4924. metaflag = 0;
  4925. start = name;
  4926. for (p = name; *p; p++) {
  4927. if (*p == '*' || *p == '?')
  4928. metaflag = 1;
  4929. else if (*p == '[') {
  4930. char *q = p + 1;
  4931. if (*q == '!')
  4932. q++;
  4933. for (;;) {
  4934. if (*q == '\\')
  4935. q++;
  4936. if (*q == '/' || *q == '\0')
  4937. break;
  4938. if (*++q == ']') {
  4939. metaflag = 1;
  4940. break;
  4941. }
  4942. }
  4943. } else if (*p == '\\')
  4944. p++;
  4945. else if (*p == '/') {
  4946. if (metaflag)
  4947. goto out;
  4948. start = p + 1;
  4949. }
  4950. }
  4951. out:
  4952. if (metaflag == 0) { /* we've reached the end of the file name */
  4953. if (enddir != expdir)
  4954. metaflag++;
  4955. p = name;
  4956. do {
  4957. if (*p == '\\')
  4958. p++;
  4959. *enddir++ = *p;
  4960. } while (*p++);
  4961. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  4962. addfname(expdir);
  4963. return;
  4964. }
  4965. endname = p;
  4966. if (name < start) {
  4967. p = name;
  4968. do {
  4969. if (*p == '\\')
  4970. p++;
  4971. *enddir++ = *p++;
  4972. } while (p < start);
  4973. }
  4974. if (enddir == expdir) {
  4975. cp = ".";
  4976. } else if (enddir == expdir + 1 && *expdir == '/') {
  4977. cp = "/";
  4978. } else {
  4979. cp = expdir;
  4980. enddir[-1] = '\0';
  4981. }
  4982. if ((dirp = opendir(cp)) == NULL)
  4983. return;
  4984. if (enddir != expdir)
  4985. enddir[-1] = '/';
  4986. if (*endname == 0) {
  4987. atend = 1;
  4988. } else {
  4989. atend = 0;
  4990. *endname++ = '\0';
  4991. }
  4992. matchdot = 0;
  4993. p = start;
  4994. if (*p == '\\')
  4995. p++;
  4996. if (*p == '.')
  4997. matchdot++;
  4998. while (! intpending && (dp = readdir(dirp)) != NULL) {
  4999. if (dp->d_name[0] == '.' && ! matchdot)
  5000. continue;
  5001. if (pmatch(start, dp->d_name)) {
  5002. if (atend) {
  5003. scopy(dp->d_name, enddir);
  5004. addfname(expdir);
  5005. } else {
  5006. for (p = enddir, cp = dp->d_name;
  5007. (*p++ = *cp++) != '\0';)
  5008. continue;
  5009. p[-1] = '/';
  5010. expmeta(p, endname);
  5011. }
  5012. }
  5013. }
  5014. closedir(dirp);
  5015. if (! atend)
  5016. endname[-1] = '/';
  5017. }
  5018. /*
  5019. * Sort the results of file name expansion. It calculates the number of
  5020. * strings to sort and then calls msort (short for merge sort) to do the
  5021. * work.
  5022. */
  5023. static struct strlist *
  5024. expsort(struct strlist *str)
  5025. {
  5026. int len;
  5027. struct strlist *sp;
  5028. len = 0;
  5029. for (sp = str ; sp ; sp = sp->next)
  5030. len++;
  5031. return msort(str, len);
  5032. }
  5033. static struct strlist *
  5034. msort(struct strlist *list, int len)
  5035. {
  5036. struct strlist *p, *q = NULL;
  5037. struct strlist **lpp;
  5038. int half;
  5039. int n;
  5040. if (len <= 1)
  5041. return list;
  5042. half = len >> 1;
  5043. p = list;
  5044. for (n = half ; --n >= 0 ; ) {
  5045. q = p;
  5046. p = p->next;
  5047. }
  5048. q->next = NULL; /* terminate first half of list */
  5049. q = msort(list, half); /* sort first half of list */
  5050. p = msort(p, len - half); /* sort second half */
  5051. lpp = &list;
  5052. for (;;) {
  5053. #ifdef BB_LOCALE_SUPPORT
  5054. if (strcoll(p->text, q->text) < 0)
  5055. #else
  5056. if (strcmp(p->text, q->text) < 0)
  5057. #endif
  5058. {
  5059. *lpp = p;
  5060. lpp = &p->next;
  5061. if ((p = *lpp) == NULL) {
  5062. *lpp = q;
  5063. break;
  5064. }
  5065. } else {
  5066. *lpp = q;
  5067. lpp = &q->next;
  5068. if ((q = *lpp) == NULL) {
  5069. *lpp = p;
  5070. break;
  5071. }
  5072. }
  5073. }
  5074. return list;
  5075. }
  5076. /*
  5077. * Returns true if the pattern matches the string.
  5078. */
  5079. static inline int
  5080. patmatch(char *pattern, const char *string)
  5081. {
  5082. return pmatch(preglob(pattern, 0, 0), string);
  5083. }
  5084. /*
  5085. * Remove any CTLESC characters from a string.
  5086. */
  5087. static char *
  5088. _rmescapes(char *str, int flag)
  5089. {
  5090. char *p, *q, *r;
  5091. static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
  5092. unsigned inquotes;
  5093. int notescaped;
  5094. int globbing;
  5095. p = strpbrk(str, qchars);
  5096. if (!p) {
  5097. return str;
  5098. }
  5099. q = p;
  5100. r = str;
  5101. if (flag & RMESCAPE_ALLOC) {
  5102. size_t len = p - str;
  5103. size_t fulllen = len + strlen(p) + 1;
  5104. if (flag & RMESCAPE_GROW) {
  5105. r = makestrspace(fulllen, expdest);
  5106. } else if (flag & RMESCAPE_HEAP) {
  5107. r = ckmalloc(fulllen);
  5108. } else {
  5109. r = stalloc(fulllen);
  5110. }
  5111. q = r;
  5112. if (len > 0) {
  5113. q = mempcpy(q, str, len);
  5114. }
  5115. }
  5116. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  5117. globbing = flag & RMESCAPE_GLOB;
  5118. notescaped = globbing;
  5119. while (*p) {
  5120. if (*p == CTLQUOTEMARK) {
  5121. inquotes = ~inquotes;
  5122. p++;
  5123. notescaped = globbing;
  5124. continue;
  5125. }
  5126. if (*p == '\\') {
  5127. /* naked back slash */
  5128. notescaped = 0;
  5129. goto copy;
  5130. }
  5131. if (*p == CTLESC) {
  5132. p++;
  5133. if (notescaped && inquotes && *p != '/') {
  5134. *q++ = '\\';
  5135. }
  5136. }
  5137. notescaped = globbing;
  5138. copy:
  5139. *q++ = *p++;
  5140. }
  5141. *q = '\0';
  5142. if (flag & RMESCAPE_GROW) {
  5143. expdest = r;
  5144. STADJUST(q - r + 1, expdest);
  5145. }
  5146. return r;
  5147. }
  5148. /*
  5149. * See if a pattern matches in a case statement.
  5150. */
  5151. int
  5152. casematch(union node *pattern, char *val)
  5153. {
  5154. struct stackmark smark;
  5155. int result;
  5156. setstackmark(&smark);
  5157. argbackq = pattern->narg.backquote;
  5158. STARTSTACKSTR(expdest);
  5159. ifslastp = NULL;
  5160. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  5161. STACKSTRNUL(expdest);
  5162. result = patmatch(stackblock(), val);
  5163. popstackmark(&smark);
  5164. return result;
  5165. }
  5166. /*
  5167. * Our own itoa().
  5168. */
  5169. static int
  5170. cvtnum(long num)
  5171. {
  5172. int len;
  5173. expdest = makestrspace(32, expdest);
  5174. len = fmtstr(expdest, 32, "%ld", num);
  5175. STADJUST(len, expdest);
  5176. return len;
  5177. }
  5178. static void
  5179. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5180. {
  5181. const char *msg;
  5182. const char *tail;
  5183. tail = nullstr;
  5184. msg = "parameter not set";
  5185. if (umsg) {
  5186. if (*end == CTLENDVAR) {
  5187. if (varflags & VSNUL)
  5188. tail = " or null";
  5189. } else
  5190. msg = umsg;
  5191. }
  5192. error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5193. }
  5194. /* $NetBSD: input.c,v 1.37 2002/11/24 22:35:40 christos Exp $ */
  5195. /*
  5196. * This implements the input routines used by the parser.
  5197. */
  5198. #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
  5199. #define IBUFSIZ (BUFSIZ + 1)
  5200. static void pushfile(void);
  5201. /*
  5202. * Read a line from the script.
  5203. */
  5204. static inline char *
  5205. pfgets(char *line, int len)
  5206. {
  5207. char *p = line;
  5208. int nleft = len;
  5209. int c;
  5210. while (--nleft > 0) {
  5211. c = pgetc2();
  5212. if (c == PEOF) {
  5213. if (p == line)
  5214. return NULL;
  5215. break;
  5216. }
  5217. *p++ = c;
  5218. if (c == '\n')
  5219. break;
  5220. }
  5221. *p = '\0';
  5222. return line;
  5223. }
  5224. /*
  5225. * Read a character from the script, returning PEOF on end of file.
  5226. * Nul characters in the input are silently discarded.
  5227. */
  5228. #define pgetc_as_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
  5229. #ifdef BB_ASH_OPTIMIZE_FOR_SIZE
  5230. #define pgetc_macro() pgetc()
  5231. static int
  5232. pgetc(void)
  5233. {
  5234. return pgetc_as_macro();
  5235. }
  5236. #else
  5237. #define pgetc_macro() pgetc_as_macro()
  5238. static int
  5239. pgetc(void)
  5240. {
  5241. return pgetc_macro();
  5242. }
  5243. #endif
  5244. /*
  5245. * Same as pgetc(), but ignores PEOA.
  5246. */
  5247. #ifdef BB_ASH_ALIAS
  5248. static int pgetc2(void)
  5249. {
  5250. int c;
  5251. do {
  5252. c = pgetc_macro();
  5253. } while (c == PEOA);
  5254. return c;
  5255. }
  5256. #else
  5257. static inline int pgetc2(void)
  5258. {
  5259. return pgetc_macro();
  5260. }
  5261. #endif
  5262. #ifdef BB_FEATURE_COMMAND_EDITING
  5263. static const char *cmdedit_prompt;
  5264. static inline void putprompt(const char *s)
  5265. {
  5266. cmdedit_prompt = s;
  5267. }
  5268. #else
  5269. static inline void putprompt(const char *s)
  5270. {
  5271. out2str(s);
  5272. }
  5273. #endif
  5274. static inline int
  5275. preadfd(void)
  5276. {
  5277. int nr;
  5278. char *buf = parsefile->buf;
  5279. parsenextc = buf;
  5280. retry:
  5281. #ifdef BB_FEATURE_COMMAND_EDITING
  5282. if (!iflag || parsefile->fd)
  5283. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  5284. else {
  5285. nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
  5286. if(nr == 0) {
  5287. /* Ctrl+C presend */
  5288. raise(SIGINT);
  5289. goto retry;
  5290. }
  5291. if(nr < 0) {
  5292. /* Ctrl+D presend */
  5293. nr = 0;
  5294. }
  5295. }
  5296. #else
  5297. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  5298. #endif
  5299. if (nr < 0) {
  5300. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  5301. int flags = fcntl(0, F_GETFL, 0);
  5302. if (flags >= 0 && flags & O_NONBLOCK) {
  5303. flags &=~ O_NONBLOCK;
  5304. if (fcntl(0, F_SETFL, flags) >= 0) {
  5305. out2str("sh: turning off NDELAY mode\n");
  5306. goto retry;
  5307. }
  5308. }
  5309. }
  5310. }
  5311. return nr;
  5312. }
  5313. /*
  5314. * Refill the input buffer and return the next input character:
  5315. *
  5316. * 1) If a string was pushed back on the input, pop it;
  5317. * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
  5318. * from a string so we can't refill the buffer, return EOF.
  5319. * 3) If the is more stuff in this buffer, use it else call read to fill it.
  5320. * 4) Process input up to the next newline, deleting nul characters.
  5321. */
  5322. int
  5323. preadbuffer(void)
  5324. {
  5325. char *p, *q;
  5326. int more;
  5327. char savec;
  5328. while (parsefile->strpush) {
  5329. #ifdef BB_ASH_ALIAS
  5330. if (parsenleft == -1 && parsefile->strpush->ap &&
  5331. parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
  5332. return PEOA;
  5333. }
  5334. #endif
  5335. popstring();
  5336. if (--parsenleft >= 0)
  5337. return (*parsenextc++);
  5338. }
  5339. if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
  5340. return PEOF;
  5341. flushall();
  5342. again:
  5343. if (parselleft <= 0) {
  5344. if ((parselleft = preadfd()) <= 0) {
  5345. parselleft = parsenleft = EOF_NLEFT;
  5346. return PEOF;
  5347. }
  5348. }
  5349. q = p = parsenextc;
  5350. /* delete nul characters */
  5351. for (more = 1; more;) {
  5352. switch (*p) {
  5353. case '\0':
  5354. p++; /* Skip nul */
  5355. goto check;
  5356. case '\n':
  5357. parsenleft = q - parsenextc;
  5358. more = 0; /* Stop processing here */
  5359. break;
  5360. }
  5361. *q++ = *p++;
  5362. check:
  5363. if (--parselleft <= 0 && more) {
  5364. parsenleft = q - parsenextc - 1;
  5365. if (parsenleft < 0)
  5366. goto again;
  5367. more = 0;
  5368. }
  5369. }
  5370. savec = *q;
  5371. *q = '\0';
  5372. if (vflag) {
  5373. out2str(parsenextc);
  5374. }
  5375. *q = savec;
  5376. return *parsenextc++;
  5377. }
  5378. /*
  5379. * Undo the last call to pgetc. Only one character may be pushed back.
  5380. * PEOF may be pushed back.
  5381. */
  5382. void
  5383. pungetc(void)
  5384. {
  5385. parsenleft++;
  5386. parsenextc--;
  5387. }
  5388. /*
  5389. * Push a string back onto the input at this current parsefile level.
  5390. * We handle aliases this way.
  5391. */
  5392. void
  5393. pushstring(char *s, void *ap)
  5394. {
  5395. struct strpush *sp;
  5396. size_t len;
  5397. len = strlen(s);
  5398. INTOFF;
  5399. /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
  5400. if (parsefile->strpush) {
  5401. sp = ckmalloc(sizeof (struct strpush));
  5402. sp->prev = parsefile->strpush;
  5403. parsefile->strpush = sp;
  5404. } else
  5405. sp = parsefile->strpush = &(parsefile->basestrpush);
  5406. sp->prevstring = parsenextc;
  5407. sp->prevnleft = parsenleft;
  5408. #ifdef BB_ASH_ALIAS
  5409. sp->ap = (struct alias *)ap;
  5410. if (ap) {
  5411. ((struct alias *)ap)->flag |= ALIASINUSE;
  5412. sp->string = s;
  5413. }
  5414. #endif
  5415. parsenextc = s;
  5416. parsenleft = len;
  5417. INTON;
  5418. }
  5419. void
  5420. popstring(void)
  5421. {
  5422. struct strpush *sp = parsefile->strpush;
  5423. INTOFF;
  5424. #ifdef BB_ASH_ALIAS
  5425. if (sp->ap) {
  5426. if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
  5427. checkkwd |= CHKALIAS;
  5428. }
  5429. if (sp->string != sp->ap->val) {
  5430. ckfree(sp->string);
  5431. }
  5432. sp->ap->flag &= ~ALIASINUSE;
  5433. if (sp->ap->flag & ALIASDEAD) {
  5434. unalias(sp->ap->name);
  5435. }
  5436. }
  5437. #endif
  5438. parsenextc = sp->prevstring;
  5439. parsenleft = sp->prevnleft;
  5440. /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
  5441. parsefile->strpush = sp->prev;
  5442. if (sp != &(parsefile->basestrpush))
  5443. ckfree(sp);
  5444. INTON;
  5445. }
  5446. /*
  5447. * Set the input to take input from a file. If push is set, push the
  5448. * old input onto the stack first.
  5449. */
  5450. void
  5451. setinputfile(const char *fname, int push)
  5452. {
  5453. int fd;
  5454. int fd2;
  5455. INTOFF;
  5456. if ((fd = open(fname, O_RDONLY)) < 0)
  5457. error("Can't open %s", fname);
  5458. if (fd < 10) {
  5459. fd2 = ash_copyfd(fd, 10);
  5460. close(fd);
  5461. if (fd2 < 0)
  5462. error("Out of file descriptors");
  5463. fd = fd2;
  5464. }
  5465. setinputfd(fd, push);
  5466. INTON;
  5467. }
  5468. /*
  5469. * Like setinputfile, but takes an open file descriptor. Call this with
  5470. * interrupts off.
  5471. */
  5472. static void
  5473. setinputfd(int fd, int push)
  5474. {
  5475. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  5476. if (push) {
  5477. pushfile();
  5478. parsefile->buf = 0;
  5479. }
  5480. parsefile->fd = fd;
  5481. if (parsefile->buf == NULL)
  5482. parsefile->buf = ckmalloc(IBUFSIZ);
  5483. parselleft = parsenleft = 0;
  5484. plinno = 1;
  5485. }
  5486. /*
  5487. * Like setinputfile, but takes input from a string.
  5488. */
  5489. static void
  5490. setinputstring(char *string)
  5491. {
  5492. INTOFF;
  5493. pushfile();
  5494. parsenextc = string;
  5495. parsenleft = strlen(string);
  5496. parsefile->buf = NULL;
  5497. plinno = 1;
  5498. INTON;
  5499. }
  5500. /*
  5501. * To handle the "." command, a stack of input files is used. Pushfile
  5502. * adds a new entry to the stack and popfile restores the previous level.
  5503. */
  5504. static void
  5505. pushfile(void)
  5506. {
  5507. struct parsefile *pf;
  5508. parsefile->nleft = parsenleft;
  5509. parsefile->lleft = parselleft;
  5510. parsefile->nextc = parsenextc;
  5511. parsefile->linno = plinno;
  5512. pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
  5513. pf->prev = parsefile;
  5514. pf->fd = -1;
  5515. pf->strpush = NULL;
  5516. pf->basestrpush.prev = NULL;
  5517. parsefile = pf;
  5518. }
  5519. static void
  5520. popfile(void)
  5521. {
  5522. struct parsefile *pf = parsefile;
  5523. INTOFF;
  5524. if (pf->fd >= 0)
  5525. close(pf->fd);
  5526. if (pf->buf)
  5527. ckfree(pf->buf);
  5528. while (pf->strpush)
  5529. popstring();
  5530. parsefile = pf->prev;
  5531. ckfree(pf);
  5532. parsenleft = parsefile->nleft;
  5533. parselleft = parsefile->lleft;
  5534. parsenextc = parsefile->nextc;
  5535. plinno = parsefile->linno;
  5536. INTON;
  5537. }
  5538. /*
  5539. * Return to top level.
  5540. */
  5541. static void
  5542. popallfiles(void)
  5543. {
  5544. while (parsefile != &basepf)
  5545. popfile();
  5546. }
  5547. /*
  5548. * Close the file(s) that the shell is reading commands from. Called
  5549. * after a fork is done.
  5550. */
  5551. static void
  5552. closescript(void)
  5553. {
  5554. popallfiles();
  5555. if (parsefile->fd > 0) {
  5556. close(parsefile->fd);
  5557. parsefile->fd = 0;
  5558. }
  5559. }
  5560. /* $NetBSD: jobs.c,v 1.56 2002/11/25 12:13:03 agc Exp $ */
  5561. /* mode flags for set_curjob */
  5562. #define CUR_DELETE 2
  5563. #define CUR_RUNNING 1
  5564. #define CUR_STOPPED 0
  5565. /* mode flags for dowait */
  5566. #define DOWAIT_NORMAL 0
  5567. #define DOWAIT_BLOCK 1
  5568. /* array of jobs */
  5569. static struct job *jobtab;
  5570. /* size of array */
  5571. static unsigned njobs;
  5572. #if JOBS
  5573. /* pgrp of shell on invocation */
  5574. static int initialpgrp;
  5575. static int ttyfd = -1;
  5576. #endif
  5577. /* current job */
  5578. static struct job *curjob;
  5579. /* number of presumed living untracked jobs */
  5580. static int jobless;
  5581. static void set_curjob(struct job *, unsigned);
  5582. #if JOBS
  5583. static int restartjob(struct job *, int);
  5584. static void xtcsetpgrp(int, pid_t);
  5585. static char *commandtext(union node *);
  5586. static void cmdlist(union node *, int);
  5587. static void cmdtxt(union node *);
  5588. static void cmdputs(const char *);
  5589. static void showpipe(struct job *, FILE *);
  5590. #endif
  5591. static int sprint_status(char *, int, int);
  5592. static void freejob(struct job *);
  5593. static struct job *getjob(const char *, int);
  5594. static struct job *growjobtab(void);
  5595. static void forkchild(struct job *, union node *, int);
  5596. static void forkparent(struct job *, union node *, int, pid_t);
  5597. static int dowait(int, struct job *);
  5598. static int getstatus(struct job *);
  5599. static void
  5600. set_curjob(struct job *jp, unsigned mode)
  5601. {
  5602. struct job *jp1;
  5603. struct job **jpp, **curp;
  5604. /* first remove from list */
  5605. jpp = curp = &curjob;
  5606. do {
  5607. jp1 = *jpp;
  5608. if (jp1 == jp)
  5609. break;
  5610. jpp = &jp1->prev_job;
  5611. } while (1);
  5612. *jpp = jp1->prev_job;
  5613. /* Then re-insert in correct position */
  5614. jpp = curp;
  5615. switch (mode) {
  5616. default:
  5617. #ifdef DEBUG
  5618. abort();
  5619. #endif
  5620. case CUR_DELETE:
  5621. /* job being deleted */
  5622. break;
  5623. case CUR_RUNNING:
  5624. /* newly created job or backgrounded job,
  5625. put after all stopped jobs. */
  5626. do {
  5627. jp1 = *jpp;
  5628. #ifdef JOBS
  5629. if (!jp1 || jp1->state != JOBSTOPPED)
  5630. #endif
  5631. break;
  5632. jpp = &jp1->prev_job;
  5633. } while (1);
  5634. /* FALLTHROUGH */
  5635. #ifdef JOBS
  5636. case CUR_STOPPED:
  5637. #endif
  5638. /* newly stopped job - becomes curjob */
  5639. jp->prev_job = *jpp;
  5640. *jpp = jp;
  5641. break;
  5642. }
  5643. }
  5644. #if JOBS
  5645. /*
  5646. * Turn job control on and off.
  5647. *
  5648. * Note: This code assumes that the third arg to ioctl is a character
  5649. * pointer, which is true on Berkeley systems but not System V. Since
  5650. * System V doesn't have job control yet, this isn't a problem now.
  5651. *
  5652. * Called with interrupts off.
  5653. */
  5654. void
  5655. setjobctl(int on)
  5656. {
  5657. int fd;
  5658. int pgrp;
  5659. if (on == jobctl || rootshell == 0)
  5660. return;
  5661. if (on) {
  5662. int ofd;
  5663. ofd = fd = open(_PATH_TTY, O_RDWR);
  5664. if (fd < 0) {
  5665. fd += 3;
  5666. while (!isatty(fd) && --fd >= 0)
  5667. ;
  5668. }
  5669. fd = fcntl(fd, F_DUPFD, 10);
  5670. close(ofd);
  5671. if (fd < 0)
  5672. goto out;
  5673. fcntl(fd, F_SETFD, FD_CLOEXEC);
  5674. do { /* while we are in the background */
  5675. if ((pgrp = tcgetpgrp(fd)) < 0) {
  5676. out:
  5677. sh_warnx("can't access tty; job control turned off");
  5678. mflag = on = 0;
  5679. goto close;
  5680. }
  5681. if (pgrp == getpgrp())
  5682. break;
  5683. killpg(0, SIGTTIN);
  5684. } while (1);
  5685. initialpgrp = pgrp;
  5686. setsignal(SIGTSTP);
  5687. setsignal(SIGTTOU);
  5688. setsignal(SIGTTIN);
  5689. pgrp = rootpid;
  5690. setpgid(0, pgrp);
  5691. xtcsetpgrp(fd, pgrp);
  5692. } else {
  5693. /* turning job control off */
  5694. fd = ttyfd;
  5695. pgrp = initialpgrp;
  5696. xtcsetpgrp(fd, pgrp);
  5697. setpgid(0, pgrp);
  5698. setsignal(SIGTSTP);
  5699. setsignal(SIGTTOU);
  5700. setsignal(SIGTTIN);
  5701. close:
  5702. close(fd);
  5703. fd = -1;
  5704. }
  5705. ttyfd = fd;
  5706. jobctl = on;
  5707. }
  5708. static int
  5709. killcmd(int argc, char **argv)
  5710. {
  5711. int signo = -1;
  5712. int list = 0;
  5713. int i;
  5714. pid_t pid;
  5715. struct job *jp;
  5716. if (argc <= 1) {
  5717. usage:
  5718. error(
  5719. "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
  5720. "kill -l [exitstatus]"
  5721. );
  5722. }
  5723. if (**++argv == '-') {
  5724. signo = decode_signal(*argv + 1, 1);
  5725. if (signo < 0) {
  5726. int c;
  5727. while ((c = nextopt("ls:")) != '\0')
  5728. switch (c) {
  5729. default:
  5730. #ifdef DEBUG
  5731. abort();
  5732. #endif
  5733. case 'l':
  5734. list = 1;
  5735. break;
  5736. case 's':
  5737. signo = decode_signal(optionarg, 1);
  5738. if (signo < 0) {
  5739. error(
  5740. "invalid signal number or name: %s",
  5741. optionarg
  5742. );
  5743. }
  5744. break;
  5745. }
  5746. argv = argptr;
  5747. } else
  5748. argv++;
  5749. }
  5750. if (!list && signo < 0)
  5751. signo = SIGTERM;
  5752. if ((signo < 0 || !*argv) ^ list) {
  5753. goto usage;
  5754. }
  5755. if (list) {
  5756. const char *name;
  5757. if (!*argv) {
  5758. for (i = 1; i < NSIG; i++) {
  5759. name = u_signal_names(0, &i, 1);
  5760. if (name)
  5761. out1fmt(snlfmt, name);
  5762. }
  5763. return 0;
  5764. }
  5765. name = u_signal_names(*argptr, &signo, -1);
  5766. if (name)
  5767. out1fmt(snlfmt, name);
  5768. else
  5769. error("invalid signal number or exit status: %s", *argptr);
  5770. return 0;
  5771. }
  5772. i = 0;
  5773. do {
  5774. if (**argv == '%') {
  5775. jp = getjob(*argv, 0);
  5776. pid = -jp->ps[0].pid;
  5777. } else
  5778. pid = number(*argv);
  5779. if (kill(pid, signo) != 0) {
  5780. sh_warnx("%m\n");
  5781. i = 1;
  5782. }
  5783. } while (*++argv);
  5784. return i;
  5785. }
  5786. #endif /* JOBS */
  5787. #if defined(JOBS) || defined(DEBUG)
  5788. static int
  5789. jobno(const struct job *jp)
  5790. {
  5791. return jp - jobtab + 1;
  5792. }
  5793. #endif
  5794. #ifdef JOBS
  5795. static int
  5796. fgcmd(int argc, char **argv)
  5797. {
  5798. struct job *jp;
  5799. FILE *out;
  5800. int mode;
  5801. int retval;
  5802. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  5803. nextopt(nullstr);
  5804. argv = argptr;
  5805. out = stdout;
  5806. do {
  5807. jp = getjob(*argv, 1);
  5808. if (mode == FORK_BG) {
  5809. set_curjob(jp, CUR_RUNNING);
  5810. fprintf(out, "[%d] ", jobno(jp));
  5811. }
  5812. outstr(jp->ps->cmd, out);
  5813. showpipe(jp, out);
  5814. retval = restartjob(jp, mode);
  5815. } while (*argv && *++argv);
  5816. return retval;
  5817. }
  5818. static int bgcmd(int, char **) __attribute__((__alias__("fgcmd")));
  5819. static int
  5820. restartjob(struct job *jp, int mode)
  5821. {
  5822. struct procstat *ps;
  5823. int i;
  5824. int status;
  5825. pid_t pgid;
  5826. INTOFF;
  5827. if (jp->state == JOBDONE)
  5828. goto out;
  5829. jp->state = JOBRUNNING;
  5830. pgid = jp->ps->pid;
  5831. if (mode == FORK_FG)
  5832. xtcsetpgrp(ttyfd, pgid);
  5833. killpg(pgid, SIGCONT);
  5834. ps = jp->ps;
  5835. i = jp->nprocs;
  5836. do {
  5837. if (WIFSTOPPED(ps->status)) {
  5838. ps->status = -1;
  5839. }
  5840. } while (ps++, --i);
  5841. out:
  5842. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  5843. INTON;
  5844. return status;
  5845. }
  5846. #endif
  5847. static int
  5848. sprint_status(char *s, int status, int sigonly)
  5849. {
  5850. int col;
  5851. int st;
  5852. col = 0;
  5853. if (!WIFEXITED(status)) {
  5854. #if JOBS
  5855. if (WIFSTOPPED(status))
  5856. st = WSTOPSIG(status);
  5857. else
  5858. #endif
  5859. st = WTERMSIG(status);
  5860. if (sigonly) {
  5861. if (st == SIGINT || st == SIGPIPE)
  5862. goto out;
  5863. #if JOBS
  5864. if (WIFSTOPPED(status))
  5865. goto out;
  5866. #endif
  5867. }
  5868. st &= 0x7f;
  5869. col = fmtstr(s, 32, strsignal(st));
  5870. if (WCOREDUMP(status)) {
  5871. col += fmtstr(s + col, 16, " (core dumped)");
  5872. }
  5873. } else if (!sigonly) {
  5874. st = WEXITSTATUS(status);
  5875. if (st)
  5876. col = fmtstr(s, 16, "Done(%d)", st);
  5877. else
  5878. col = fmtstr(s, 16, "Done");
  5879. }
  5880. out:
  5881. return col;
  5882. }
  5883. #if JOBS
  5884. static void
  5885. showjob(FILE *out, struct job *jp, int mode)
  5886. {
  5887. struct procstat *ps;
  5888. struct procstat *psend;
  5889. int col;
  5890. int indent;
  5891. char s[80];
  5892. ps = jp->ps;
  5893. if (mode & SHOW_PGID) {
  5894. /* just output process (group) id of pipeline */
  5895. fprintf(out, "%d\n", ps->pid);
  5896. return;
  5897. }
  5898. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  5899. indent = col;
  5900. if (jp == curjob)
  5901. s[col - 2] = '+';
  5902. else if (curjob && jp == curjob->prev_job)
  5903. s[col - 2] = '-';
  5904. if (mode & SHOW_PID)
  5905. col += fmtstr(s + col, 16, "%d ", ps->pid);
  5906. psend = ps + jp->nprocs;
  5907. if (jp->state == JOBRUNNING) {
  5908. scopy("Running", s + col);
  5909. col += strlen("Running");
  5910. } else {
  5911. int status = psend[-1].status;
  5912. #if JOBS
  5913. if (jp->state == JOBSTOPPED)
  5914. status = jp->stopstatus;
  5915. #endif
  5916. col += sprint_status(s + col, status, 0);
  5917. }
  5918. goto start;
  5919. do {
  5920. /* for each process */
  5921. col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
  5922. start:
  5923. fprintf(out, "%s%*c%s",
  5924. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  5925. );
  5926. if (!(mode & SHOW_PID)) {
  5927. showpipe(jp, out);
  5928. break;
  5929. }
  5930. if (++ps == psend) {
  5931. outcslow('\n', out);
  5932. break;
  5933. }
  5934. } while (1);
  5935. jp->changed = 0;
  5936. if (jp->state == JOBDONE) {
  5937. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  5938. freejob(jp);
  5939. }
  5940. }
  5941. static int
  5942. jobscmd(int argc, char **argv)
  5943. {
  5944. int mode, m;
  5945. FILE *out;
  5946. mode = 0;
  5947. while ((m = nextopt("lp")))
  5948. if (m == 'l')
  5949. mode = SHOW_PID;
  5950. else
  5951. mode = SHOW_PGID;
  5952. out = stdout;
  5953. argv = argptr;
  5954. if (*argv)
  5955. do
  5956. showjob(out, getjob(*argv,0), mode);
  5957. while (*++argv);
  5958. else
  5959. showjobs(out, mode);
  5960. return 0;
  5961. }
  5962. /*
  5963. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  5964. * statuses have changed since the last call to showjobs.
  5965. */
  5966. static void
  5967. showjobs(FILE *out, int mode)
  5968. {
  5969. struct job *jp;
  5970. TRACE(("showjobs(%x) called\n", mode));
  5971. /* If not even one one job changed, there is nothing to do */
  5972. while (dowait(DOWAIT_NORMAL, NULL) > 0)
  5973. continue;
  5974. for (jp = curjob; jp; jp = jp->prev_job) {
  5975. if (!(mode & SHOW_CHANGED) || jp->changed)
  5976. showjob(out, jp, mode);
  5977. }
  5978. }
  5979. #endif /* JOBS */
  5980. /*
  5981. * Mark a job structure as unused.
  5982. */
  5983. static void
  5984. freejob(struct job *jp)
  5985. {
  5986. struct procstat *ps;
  5987. int i;
  5988. INTOFF;
  5989. for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
  5990. if (ps->cmd != nullstr)
  5991. ckfree(ps->cmd);
  5992. }
  5993. if (jp->ps != &jp->ps0)
  5994. ckfree(jp->ps);
  5995. jp->used = 0;
  5996. set_curjob(jp, CUR_DELETE);
  5997. INTON;
  5998. }
  5999. static int
  6000. waitcmd(int argc, char **argv)
  6001. {
  6002. struct job *job;
  6003. int retval;
  6004. struct job *jp;
  6005. EXSIGON();
  6006. nextopt(nullstr);
  6007. retval = 0;
  6008. argv = argptr;
  6009. if (!*argv) {
  6010. /* wait for all jobs */
  6011. for (;;) {
  6012. jp = curjob;
  6013. while (1) {
  6014. if (!jp) {
  6015. /* no running procs */
  6016. goto out;
  6017. }
  6018. if (jp->state == JOBRUNNING)
  6019. break;
  6020. jp->waited = 1;
  6021. jp = jp->prev_job;
  6022. }
  6023. dowait(DOWAIT_BLOCK, 0);
  6024. }
  6025. }
  6026. retval = 127;
  6027. do {
  6028. if (**argv != '%') {
  6029. pid_t pid = number(*argv);
  6030. job = curjob;
  6031. goto start;
  6032. do {
  6033. if (job->ps[job->nprocs - 1].pid == pid)
  6034. break;
  6035. job = job->prev_job;
  6036. start:
  6037. if (!job)
  6038. goto repeat;
  6039. } while (1);
  6040. } else
  6041. job = getjob(*argv, 0);
  6042. /* loop until process terminated or stopped */
  6043. while (job->state == JOBRUNNING)
  6044. dowait(DOWAIT_BLOCK, 0);
  6045. job->waited = 1;
  6046. retval = getstatus(job);
  6047. repeat:
  6048. ;
  6049. } while (*++argv);
  6050. out:
  6051. return retval;
  6052. }
  6053. /*
  6054. * Convert a job name to a job structure.
  6055. */
  6056. static struct job *
  6057. getjob(const char *name, int getctl)
  6058. {
  6059. struct job *jp;
  6060. struct job *found;
  6061. const char *err_msg = "No such job: %s";
  6062. unsigned num;
  6063. int c;
  6064. const char *p;
  6065. char *(*match)(const char *, const char *);
  6066. jp = curjob;
  6067. p = name;
  6068. if (!p)
  6069. goto currentjob;
  6070. if (*p != '%')
  6071. goto err;
  6072. c = *++p;
  6073. if (!c)
  6074. goto currentjob;
  6075. if (!p[1]) {
  6076. if (c == '+' || c == '%') {
  6077. currentjob:
  6078. err_msg = "No current job";
  6079. goto check;
  6080. } else if (c == '-') {
  6081. if (jp)
  6082. jp = jp->prev_job;
  6083. err_msg = "No previous job";
  6084. check:
  6085. if (!jp)
  6086. goto err;
  6087. goto gotit;
  6088. }
  6089. }
  6090. if (is_number(p)) {
  6091. num = atoi(p);
  6092. if (num < njobs) {
  6093. jp = jobtab + num - 1;
  6094. if (jp->used)
  6095. goto gotit;
  6096. goto err;
  6097. }
  6098. }
  6099. match = prefix;
  6100. if (*p == '?') {
  6101. match = strstr;
  6102. p++;
  6103. }
  6104. found = 0;
  6105. while (1) {
  6106. if (!jp)
  6107. goto err;
  6108. if (match(jp->ps[0].cmd, p)) {
  6109. if (found)
  6110. goto err;
  6111. found = jp;
  6112. err_msg = "%s: ambiguous";
  6113. }
  6114. jp = jp->prev_job;
  6115. }
  6116. gotit:
  6117. #if JOBS
  6118. err_msg = "job %s not created under job control";
  6119. if (getctl && jp->jobctl == 0)
  6120. goto err;
  6121. #endif
  6122. return jp;
  6123. err:
  6124. error(err_msg, name);
  6125. }
  6126. /*
  6127. * Return a new job structure.
  6128. * Called with interrupts off.
  6129. */
  6130. static struct job *
  6131. makejob(union node *node, int nprocs)
  6132. {
  6133. int i;
  6134. struct job *jp;
  6135. for (i = njobs, jp = jobtab ; ; jp++) {
  6136. if (--i < 0) {
  6137. jp = growjobtab();
  6138. break;
  6139. }
  6140. if (jp->used == 0)
  6141. break;
  6142. if (jp->state != JOBDONE || !jp->waited)
  6143. continue;
  6144. #if JOBS
  6145. if (jobctl)
  6146. continue;
  6147. #endif
  6148. freejob(jp);
  6149. break;
  6150. }
  6151. memset(jp, 0, sizeof(*jp));
  6152. #if JOBS
  6153. if (jobctl)
  6154. jp->jobctl = 1;
  6155. #endif
  6156. jp->prev_job = curjob;
  6157. curjob = jp;
  6158. jp->used = 1;
  6159. jp->ps = &jp->ps0;
  6160. if (nprocs > 1) {
  6161. jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
  6162. }
  6163. TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
  6164. jobno(jp)));
  6165. return jp;
  6166. }
  6167. static struct job *
  6168. growjobtab(void)
  6169. {
  6170. size_t len;
  6171. ptrdiff_t offset;
  6172. struct job *jp, *jq;
  6173. len = njobs * sizeof(*jp);
  6174. jq = jobtab;
  6175. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  6176. offset = (char *)jp - (char *)jq;
  6177. if (offset) {
  6178. /* Relocate pointers */
  6179. size_t l = len;
  6180. jq = (struct job *)((char *)jq + l);
  6181. while (l) {
  6182. l -= sizeof(*jp);
  6183. jq--;
  6184. #define joff(p) ((struct job *)((char *)(p) + l))
  6185. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  6186. if (likely(joff(jp)->ps == &jq->ps0))
  6187. jmove(joff(jp)->ps);
  6188. if (joff(jp)->prev_job)
  6189. jmove(joff(jp)->prev_job);
  6190. }
  6191. if (curjob)
  6192. jmove(curjob);
  6193. #undef joff
  6194. #undef jmove
  6195. }
  6196. njobs += 4;
  6197. jobtab = jp;
  6198. jp = (struct job *)((char *)jp + len);
  6199. jq = jp + 3;
  6200. do {
  6201. jq->used = 0;
  6202. } while (--jq >= jp);
  6203. return jp;
  6204. }
  6205. /*
  6206. * Fork off a subshell. If we are doing job control, give the subshell its
  6207. * own process group. Jp is a job structure that the job is to be added to.
  6208. * N is the command that will be evaluated by the child. Both jp and n may
  6209. * be NULL. The mode parameter can be one of the following:
  6210. * FORK_FG - Fork off a foreground process.
  6211. * FORK_BG - Fork off a background process.
  6212. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  6213. * process group even if job control is on.
  6214. *
  6215. * When job control is turned off, background processes have their standard
  6216. * input redirected to /dev/null (except for the second and later processes
  6217. * in a pipeline).
  6218. *
  6219. * Called with interrupts off.
  6220. */
  6221. static inline void
  6222. forkchild(struct job *jp, union node *n, int mode)
  6223. {
  6224. int wasroot;
  6225. TRACE(("Child shell %d\n", getpid()));
  6226. wasroot = rootshell;
  6227. rootshell = 0;
  6228. closescript();
  6229. clear_traps();
  6230. #if JOBS
  6231. /* do job control only in root shell */
  6232. jobctl = 0;
  6233. if (mode != FORK_NOJOB && jp->jobctl && wasroot) {
  6234. pid_t pgrp;
  6235. if (jp->nprocs == 0)
  6236. pgrp = getpid();
  6237. else
  6238. pgrp = jp->ps[0].pid;
  6239. /* This can fail because we are doing it in the parent also */
  6240. (void)setpgid(0, pgrp);
  6241. if (mode == FORK_FG)
  6242. xtcsetpgrp(ttyfd, pgrp);
  6243. setsignal(SIGTSTP);
  6244. setsignal(SIGTTOU);
  6245. } else
  6246. #endif
  6247. if (mode == FORK_BG) {
  6248. ignoresig(SIGINT);
  6249. ignoresig(SIGQUIT);
  6250. if (jp->nprocs == 0) {
  6251. close(0);
  6252. if (open(_PATH_DEVNULL, O_RDONLY) != 0)
  6253. error("Can't open %s", _PATH_DEVNULL);
  6254. }
  6255. }
  6256. if (wasroot && iflag) {
  6257. setsignal(SIGINT);
  6258. setsignal(SIGQUIT);
  6259. setsignal(SIGTERM);
  6260. }
  6261. for (jp = curjob; jp; jp = jp->prev_job)
  6262. freejob(jp);
  6263. jobless = 0;
  6264. }
  6265. static inline void
  6266. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  6267. {
  6268. TRACE(("In parent shell: child = %d\n", pid));
  6269. if (!jp) {
  6270. while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
  6271. jobless++;
  6272. return;
  6273. }
  6274. #if JOBS
  6275. if (mode != FORK_NOJOB && jp->jobctl) {
  6276. int pgrp;
  6277. if (jp->nprocs == 0)
  6278. pgrp = pid;
  6279. else
  6280. pgrp = jp->ps[0].pid;
  6281. /* This can fail because we are doing it in the child also */
  6282. (void)setpgid(pid, pgrp);
  6283. }
  6284. #endif
  6285. if (mode == FORK_BG) {
  6286. backgndpid = pid; /* set $! */
  6287. set_curjob(jp, CUR_RUNNING);
  6288. }
  6289. if (jp) {
  6290. struct procstat *ps = &jp->ps[jp->nprocs++];
  6291. ps->pid = pid;
  6292. ps->status = -1;
  6293. ps->cmd = nullstr;
  6294. #if JOBS
  6295. if (jobctl && n)
  6296. ps->cmd = commandtext(n);
  6297. #endif
  6298. }
  6299. }
  6300. static int
  6301. forkshell(struct job *jp, union node *n, int mode)
  6302. {
  6303. int pid;
  6304. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  6305. pid = fork();
  6306. if (pid < 0) {
  6307. TRACE(("Fork failed, errno=%d", errno));
  6308. if (jp)
  6309. freejob(jp);
  6310. error("Cannot fork");
  6311. }
  6312. if (pid == 0)
  6313. forkchild(jp, n, mode);
  6314. else
  6315. forkparent(jp, n, mode, pid);
  6316. return pid;
  6317. }
  6318. /*
  6319. * Wait for job to finish.
  6320. *
  6321. * Under job control we have the problem that while a child process is
  6322. * running interrupts generated by the user are sent to the child but not
  6323. * to the shell. This means that an infinite loop started by an inter-
  6324. * active user may be hard to kill. With job control turned off, an
  6325. * interactive user may place an interactive program inside a loop. If
  6326. * the interactive program catches interrupts, the user doesn't want
  6327. * these interrupts to also abort the loop. The approach we take here
  6328. * is to have the shell ignore interrupt signals while waiting for a
  6329. * forground process to terminate, and then send itself an interrupt
  6330. * signal if the child process was terminated by an interrupt signal.
  6331. * Unfortunately, some programs want to do a bit of cleanup and then
  6332. * exit on interrupt; unless these processes terminate themselves by
  6333. * sending a signal to themselves (instead of calling exit) they will
  6334. * confuse this approach.
  6335. *
  6336. * Called with interrupts off.
  6337. */
  6338. int
  6339. waitforjob(struct job *jp)
  6340. {
  6341. int st;
  6342. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  6343. while (jp->state == JOBRUNNING) {
  6344. dowait(DOWAIT_BLOCK, jp);
  6345. }
  6346. st = getstatus(jp);
  6347. #if JOBS
  6348. if (jp->jobctl) {
  6349. xtcsetpgrp(ttyfd, rootpid);
  6350. /*
  6351. * This is truly gross.
  6352. * If we're doing job control, then we did a TIOCSPGRP which
  6353. * caused us (the shell) to no longer be in the controlling
  6354. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  6355. * intuit from the subprocess exit status whether a SIGINT
  6356. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  6357. */
  6358. if (jp->sigint)
  6359. raise(SIGINT);
  6360. }
  6361. if (jp->state == JOBDONE)
  6362. #endif
  6363. freejob(jp);
  6364. return st;
  6365. }
  6366. /*
  6367. * Do a wait system call. If job control is compiled in, we accept
  6368. * stopped processes. If block is zero, we return a value of zero
  6369. * rather than blocking.
  6370. *
  6371. * System V doesn't have a non-blocking wait system call. It does
  6372. * have a SIGCLD signal that is sent to a process when one of it's
  6373. * children dies. The obvious way to use SIGCLD would be to install
  6374. * a handler for SIGCLD which simply bumped a counter when a SIGCLD
  6375. * was received, and have waitproc bump another counter when it got
  6376. * the status of a process. Waitproc would then know that a wait
  6377. * system call would not block if the two counters were different.
  6378. * This approach doesn't work because if a process has children that
  6379. * have not been waited for, System V will send it a SIGCLD when it
  6380. * installs a signal handler for SIGCLD. What this means is that when
  6381. * a child exits, the shell will be sent SIGCLD signals continuously
  6382. * until is runs out of stack space, unless it does a wait call before
  6383. * restoring the signal handler. The code below takes advantage of
  6384. * this (mis)feature by installing a signal handler for SIGCLD and
  6385. * then checking to see whether it was called. If there are any
  6386. * children to be waited for, it will be.
  6387. *
  6388. * If neither SYSV nor BSD is defined, we don't implement nonblocking
  6389. * waits at all. In this case, the user will not be informed when
  6390. * a background process until the next time she runs a real program
  6391. * (as opposed to running a builtin command or just typing return),
  6392. * and the jobs command may give out of date information.
  6393. */
  6394. static inline int
  6395. waitproc(int block, int *status)
  6396. {
  6397. int flags = 0;
  6398. #if JOBS
  6399. if (jobctl)
  6400. flags |= WUNTRACED;
  6401. #endif
  6402. if (block == 0)
  6403. flags |= WNOHANG;
  6404. return wait3(status, flags, (struct rusage *)NULL);
  6405. }
  6406. /*
  6407. * Wait for a process to terminate.
  6408. */
  6409. static int
  6410. dowait(int block, struct job *job)
  6411. {
  6412. int pid;
  6413. int status;
  6414. struct job *jp;
  6415. struct job *thisjob;
  6416. int state;
  6417. TRACE(("dowait(%d) called\n", block));
  6418. pid = waitproc(block, &status);
  6419. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  6420. if (pid <= 0)
  6421. return pid;
  6422. INTOFF;
  6423. thisjob = NULL;
  6424. for (jp = curjob; jp; jp = jp->prev_job) {
  6425. struct procstat *sp;
  6426. struct procstat *spend;
  6427. if (jp->state == JOBDONE)
  6428. continue;
  6429. state = JOBDONE;
  6430. spend = jp->ps + jp->nprocs;
  6431. sp = jp->ps;
  6432. do {
  6433. if (sp->pid == pid) {
  6434. TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status));
  6435. sp->status = status;
  6436. thisjob = jp;
  6437. }
  6438. if (sp->status == -1)
  6439. state = JOBRUNNING;
  6440. #ifdef JOBS
  6441. if (state == JOBRUNNING)
  6442. continue;
  6443. if (WIFSTOPPED(sp->status)) {
  6444. jp->stopstatus = sp->status;
  6445. state = JOBSTOPPED;
  6446. }
  6447. #endif
  6448. } while (++sp < spend);
  6449. if (thisjob)
  6450. goto gotjob;
  6451. }
  6452. #ifdef JOBS
  6453. if (!WIFSTOPPED(status))
  6454. #endif
  6455. jobless--;
  6456. goto out;
  6457. gotjob:
  6458. if (state != JOBRUNNING) {
  6459. thisjob->changed = 1;
  6460. if (thisjob->state != state) {
  6461. TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state));
  6462. thisjob->state = state;
  6463. #ifdef JOBS
  6464. if (state == JOBSTOPPED) {
  6465. set_curjob(thisjob, CUR_STOPPED);
  6466. }
  6467. #endif
  6468. }
  6469. }
  6470. out:
  6471. INTON;
  6472. if (thisjob && thisjob == job) {
  6473. char s[48 + 1];
  6474. int len;
  6475. len = sprint_status(s, status, 1);
  6476. if (len) {
  6477. s[len] = '\n';
  6478. s[len + 1] = 0;
  6479. out2str(s);
  6480. }
  6481. }
  6482. return pid;
  6483. }
  6484. /*
  6485. * return 1 if there are stopped jobs, otherwise 0
  6486. */
  6487. int
  6488. stoppedjobs(void)
  6489. {
  6490. struct job *jp;
  6491. int retval;
  6492. retval = 0;
  6493. if (job_warning)
  6494. goto out;
  6495. jp = curjob;
  6496. if (jp && jp->state == JOBSTOPPED) {
  6497. out2str("You have stopped jobs.\n");
  6498. job_warning = 2;
  6499. retval++;
  6500. }
  6501. out:
  6502. return retval;
  6503. }
  6504. /*
  6505. * Return a string identifying a command (to be printed by the
  6506. * jobs command).
  6507. */
  6508. #if JOBS
  6509. static char *cmdnextc;
  6510. static char *
  6511. commandtext(union node *n)
  6512. {
  6513. char *name;
  6514. STARTSTACKSTR(cmdnextc);
  6515. cmdtxt(n);
  6516. name = stackblock();
  6517. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  6518. name, cmdnextc, cmdnextc));
  6519. return savestr(name);
  6520. }
  6521. static void
  6522. cmdtxt(union node *n)
  6523. {
  6524. union node *np;
  6525. struct nodelist *lp;
  6526. const char *p;
  6527. char s[2];
  6528. switch (n->type) {
  6529. default:
  6530. #if DEBUG
  6531. abort();
  6532. #endif
  6533. case NPIPE:
  6534. lp = n->npipe.cmdlist;
  6535. for (;;) {
  6536. cmdtxt(lp->n);
  6537. lp = lp->next;
  6538. if (!lp)
  6539. break;
  6540. cmdputs(" | ");
  6541. }
  6542. break;
  6543. case NSEMI:
  6544. p = "; ";
  6545. goto binop;
  6546. case NAND:
  6547. p = " && ";
  6548. goto binop;
  6549. case NOR:
  6550. p = " || ";
  6551. binop:
  6552. cmdtxt(n->nbinary.ch1);
  6553. cmdputs(p);
  6554. n = n->nbinary.ch2;
  6555. goto donode;
  6556. case NREDIR:
  6557. case NBACKGND:
  6558. n = n->nredir.n;
  6559. goto donode;
  6560. case NNOT:
  6561. cmdputs("!");
  6562. n = n->nnot.com;
  6563. donode:
  6564. cmdtxt(n);
  6565. break;
  6566. case NIF:
  6567. cmdputs("if ");
  6568. cmdtxt(n->nif.test);
  6569. cmdputs("; then ");
  6570. n = n->nif.ifpart;
  6571. if (n->nif.elsepart) {
  6572. cmdtxt(n);
  6573. cmdputs("; else ");
  6574. n = n->nif.elsepart;
  6575. }
  6576. p = "; fi";
  6577. goto dotail;
  6578. case NSUBSHELL:
  6579. cmdputs("(");
  6580. n = n->nredir.n;
  6581. p = ")";
  6582. goto dotail;
  6583. case NWHILE:
  6584. p = "while ";
  6585. goto until;
  6586. case NUNTIL:
  6587. p = "until ";
  6588. until:
  6589. cmdputs(p);
  6590. cmdtxt(n->nbinary.ch1);
  6591. n = n->nbinary.ch2;
  6592. p = "; done";
  6593. dodo:
  6594. cmdputs("; do ");
  6595. dotail:
  6596. cmdtxt(n);
  6597. goto dotail2;
  6598. case NFOR:
  6599. cmdputs("for ");
  6600. cmdputs(n->nfor.var);
  6601. cmdputs(" in ");
  6602. cmdlist(n->nfor.args, 1);
  6603. n = n->nfor.body;
  6604. p = "; done";
  6605. goto dodo;
  6606. case NDEFUN:
  6607. cmdputs(n->narg.text);
  6608. p = "() { ... }";
  6609. goto dotail2;
  6610. case NCMD:
  6611. cmdlist(n->ncmd.args, 1);
  6612. cmdlist(n->ncmd.redirect, 0);
  6613. break;
  6614. case NARG:
  6615. p = n->narg.text;
  6616. dotail2:
  6617. cmdputs(p);
  6618. break;
  6619. case NHERE:
  6620. case NXHERE:
  6621. p = "<<...";
  6622. goto dotail2;
  6623. case NCASE:
  6624. cmdputs("case ");
  6625. cmdputs(n->ncase.expr->narg.text);
  6626. cmdputs(" in ");
  6627. for (np = n->ncase.cases; np; np = np->nclist.next) {
  6628. cmdtxt(np->nclist.pattern);
  6629. cmdputs(") ");
  6630. cmdtxt(np->nclist.body);
  6631. cmdputs(";; ");
  6632. }
  6633. p = "esac";
  6634. goto dotail2;
  6635. case NTO:
  6636. p = ">";
  6637. goto redir;
  6638. case NCLOBBER:
  6639. p = ">|";
  6640. goto redir;
  6641. case NAPPEND:
  6642. p = ">>";
  6643. goto redir;
  6644. case NTOFD:
  6645. p = ">&";
  6646. goto redir;
  6647. case NFROM:
  6648. p = "<";
  6649. goto redir;
  6650. case NFROMFD:
  6651. p = "<&";
  6652. goto redir;
  6653. case NFROMTO:
  6654. p = "<>";
  6655. redir:
  6656. s[0] = n->nfile.fd + '0';
  6657. s[1] = '\0';
  6658. cmdputs(s);
  6659. cmdputs(p);
  6660. if (n->type == NTOFD || n->type == NFROMFD) {
  6661. s[0] = n->ndup.dupfd + '0';
  6662. p = s;
  6663. goto dotail2;
  6664. } else {
  6665. n = n->nfile.fname;
  6666. goto donode;
  6667. }
  6668. }
  6669. }
  6670. static void
  6671. cmdlist(union node *np, int sep)
  6672. {
  6673. for (; np; np = np->narg.next) {
  6674. if (!sep)
  6675. cmdputs(spcstr);
  6676. cmdtxt(np);
  6677. if (sep && np->narg.next)
  6678. cmdputs(spcstr);
  6679. }
  6680. }
  6681. static void
  6682. cmdputs(const char *s)
  6683. {
  6684. const char *p, *str;
  6685. char c, cc[2] = " ";
  6686. char *nextc;
  6687. int subtype = 0;
  6688. int quoted = 0;
  6689. static const char *const vstype[16] = {
  6690. nullstr, "}", "-", "+", "?", "=",
  6691. "#", "##", "%", "%%"
  6692. };
  6693. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  6694. p = s;
  6695. while ((c = *p++) != 0) {
  6696. str = 0;
  6697. switch (c) {
  6698. case CTLESC:
  6699. c = *p++;
  6700. break;
  6701. case CTLVAR:
  6702. subtype = *p++;
  6703. if ((subtype & VSTYPE) == VSLENGTH)
  6704. str = "${#";
  6705. else
  6706. str = "${";
  6707. if (!(subtype & VSQUOTE) != !(quoted & 1)) {
  6708. quoted ^= 1;
  6709. c = '"';
  6710. } else
  6711. goto dostr;
  6712. break;
  6713. case CTLENDVAR:
  6714. quoted >>= 1;
  6715. subtype = 0;
  6716. if (quoted & 1) {
  6717. str = "\"}";
  6718. goto dostr;
  6719. }
  6720. c = '}';
  6721. break;
  6722. case CTLBACKQ:
  6723. str = "$(...)";
  6724. goto dostr;
  6725. case CTLBACKQ+CTLQUOTE:
  6726. str = "\"$(...)\"";
  6727. goto dostr;
  6728. #ifdef BB_ASH_MATH_SUPPORT
  6729. case CTLARI:
  6730. str = "$((";
  6731. goto dostr;
  6732. case CTLENDARI:
  6733. str = "))";
  6734. goto dostr;
  6735. #endif
  6736. case CTLQUOTEMARK:
  6737. quoted ^= 1;
  6738. c = '"';
  6739. break;
  6740. case '=':
  6741. if (subtype == 0)
  6742. break;
  6743. str = vstype[subtype & VSTYPE];
  6744. if (subtype & VSNUL)
  6745. c = ':';
  6746. else
  6747. c = *str++;
  6748. if (c != '}')
  6749. quoted <<= 1;
  6750. break;
  6751. case '\'':
  6752. case '\\':
  6753. case '"':
  6754. case '$':
  6755. /* These can only happen inside quotes */
  6756. cc[0] = c;
  6757. str = cc;
  6758. c = '\\';
  6759. break;
  6760. default:
  6761. break;
  6762. }
  6763. USTPUTC(c, nextc);
  6764. if (!str)
  6765. continue;
  6766. dostr:
  6767. while ((c = *str++)) {
  6768. USTPUTC(c, nextc);
  6769. }
  6770. }
  6771. if (quoted & 1) {
  6772. USTPUTC('"', nextc);
  6773. }
  6774. *nextc = 0;
  6775. cmdnextc = nextc;
  6776. }
  6777. static void
  6778. showpipe(struct job *jp, FILE *out)
  6779. {
  6780. struct procstat *sp;
  6781. struct procstat *spend;
  6782. spend = jp->ps + jp->nprocs;
  6783. for (sp = jp->ps + 1; sp < spend; sp++)
  6784. fprintf(out, " | %s", sp->cmd);
  6785. outcslow('\n', out);
  6786. flushall();
  6787. }
  6788. static void
  6789. xtcsetpgrp(int fd, pid_t pgrp)
  6790. {
  6791. if (tcsetpgrp(fd, pgrp))
  6792. error("Cannot set tty process group (%m)");
  6793. }
  6794. #endif /* JOBS */
  6795. static int
  6796. getstatus(struct job *job) {
  6797. int status;
  6798. int retval;
  6799. status = job->ps[job->nprocs - 1].status;
  6800. retval = WEXITSTATUS(status);
  6801. if (!WIFEXITED(status)) {
  6802. #if JOBS
  6803. retval = WSTOPSIG(status);
  6804. if (!WIFSTOPPED(status))
  6805. #endif
  6806. {
  6807. /* XXX: limits number of signals */
  6808. retval = WTERMSIG(status);
  6809. #if JOBS
  6810. if (retval == SIGINT)
  6811. job->sigint = 1;
  6812. #endif
  6813. }
  6814. retval += 128;
  6815. }
  6816. TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
  6817. jobno(job), job->nprocs, status, retval));
  6818. return retval;
  6819. }
  6820. #ifdef BB_ASH_MAIL
  6821. /* $NetBSD: mail.c,v 1.15 2002/11/24 22:35:40 christos Exp $ */
  6822. /*
  6823. * Routines to check for mail. (Perhaps make part of main.c?)
  6824. */
  6825. #define MAXMBOXES 10
  6826. /* times of mailboxes */
  6827. static time_t mailtime[MAXMBOXES];
  6828. /* Set if MAIL or MAILPATH is changed. */
  6829. static int mail_var_path_changed;
  6830. /*
  6831. * Print appropriate message(s) if mail has arrived.
  6832. * If mail_var_path_changed is set,
  6833. * then the value of MAIL has mail_var_path_changed,
  6834. * so we just update the values.
  6835. */
  6836. static void
  6837. chkmail(void)
  6838. {
  6839. const char *mpath;
  6840. char *p;
  6841. char *q;
  6842. time_t *mtp;
  6843. struct stackmark smark;
  6844. struct stat statb;
  6845. setstackmark(&smark);
  6846. mpath = mpathset() ? mpathval() : mailval();
  6847. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  6848. p = padvance(&mpath, nullstr);
  6849. if (p == NULL)
  6850. break;
  6851. if (*p == '\0')
  6852. continue;
  6853. for (q = p ; *q ; q++);
  6854. #ifdef DEBUG
  6855. if (q[-1] != '/')
  6856. abort();
  6857. #endif
  6858. q[-1] = '\0'; /* delete trailing '/' */
  6859. if (stat(p, &statb) < 0) {
  6860. *mtp = 0;
  6861. continue;
  6862. }
  6863. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  6864. fprintf(
  6865. stderr, snlfmt,
  6866. pathopt ? pathopt : "you have mail"
  6867. );
  6868. }
  6869. *mtp = statb.st_mtime;
  6870. }
  6871. mail_var_path_changed = 0;
  6872. popstackmark(&smark);
  6873. }
  6874. static void
  6875. changemail(const char *val)
  6876. {
  6877. mail_var_path_changed++;
  6878. }
  6879. #endif /* BB_ASH_MAIL */
  6880. /* $NetBSD: main.c,v 1.46 2002/12/11 19:12:18 christos Exp $ */
  6881. #if PROFILE
  6882. static short profile_buf[16384];
  6883. extern int etext();
  6884. #endif
  6885. static int isloginsh;
  6886. static void read_profile(const char *);
  6887. /*
  6888. * Main routine. We initialize things, parse the arguments, execute
  6889. * profiles if we're a login shell, and then call cmdloop to execute
  6890. * commands. The setjmp call sets up the location to jump to when an
  6891. * exception occurs. When an exception occurs the variable "state"
  6892. * is used to figure out how far we had gotten.
  6893. */
  6894. int
  6895. ash_main(int argc, char **argv)
  6896. {
  6897. char *shinit;
  6898. volatile int state;
  6899. struct jmploc jmploc;
  6900. struct stackmark smark;
  6901. #ifdef __GLIBC__
  6902. dash_errno = __errno_location();
  6903. #endif
  6904. #if PROFILE
  6905. monitor(4, etext, profile_buf, sizeof profile_buf, 50);
  6906. #endif
  6907. state = 0;
  6908. if (setjmp(jmploc.loc)) {
  6909. int status;
  6910. int e;
  6911. reset();
  6912. e = exception;
  6913. switch (exception) {
  6914. case EXEXEC:
  6915. status = exerrno;
  6916. break;
  6917. case EXERROR:
  6918. status = 2;
  6919. break;
  6920. default:
  6921. status = exitstatus;
  6922. break;
  6923. }
  6924. exitstatus = status;
  6925. if (e == EXEXIT || state == 0 || iflag == 0 || ! rootshell)
  6926. exitshell();
  6927. if (e == EXINT) {
  6928. outcslow('\n', stderr);
  6929. }
  6930. popstackmark(&smark);
  6931. FORCEINTON; /* enable interrupts */
  6932. if (state == 1)
  6933. goto state1;
  6934. else if (state == 2)
  6935. goto state2;
  6936. else if (state == 3)
  6937. goto state3;
  6938. else
  6939. goto state4;
  6940. }
  6941. handler = &jmploc;
  6942. #ifdef DEBUG
  6943. opentrace();
  6944. trputs("Shell args: "); trargs(argv);
  6945. #endif
  6946. rootpid = getpid();
  6947. rootshell = 1;
  6948. init();
  6949. setstackmark(&smark);
  6950. procargs(argc, argv);
  6951. #ifdef BB_FEATURE_COMMAND_SAVEHISTORY
  6952. if ( iflag ) {
  6953. const char *hp = lookupvar("HISTFILE");
  6954. if(hp == NULL ) {
  6955. hp = lookupvar("HOME");
  6956. if(hp != NULL) {
  6957. char *defhp = concat_path_file(hp, ".ash_history");
  6958. setvar("HISTFILE", defhp, 0);
  6959. free(defhp);
  6960. }
  6961. }
  6962. }
  6963. #endif
  6964. if (argv[0] && argv[0][0] == '-')
  6965. isloginsh = 1;
  6966. if (isloginsh) {
  6967. state = 1;
  6968. read_profile("/etc/profile");
  6969. state1:
  6970. state = 2;
  6971. read_profile(".profile");
  6972. }
  6973. state2:
  6974. state = 3;
  6975. if (
  6976. #ifndef linux
  6977. getuid() == geteuid() && getgid() == getegid() &&
  6978. #endif
  6979. iflag
  6980. ) {
  6981. if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
  6982. read_profile(shinit);
  6983. }
  6984. }
  6985. state3:
  6986. state = 4;
  6987. if (minusc)
  6988. evalstring(minusc, 0);
  6989. if (sflag || minusc == NULL) {
  6990. #ifdef BB_FEATURE_COMMAND_SAVEHISTORY
  6991. if ( iflag ) {
  6992. const char *hp = lookupvar("HISTFILE");
  6993. if(hp != NULL )
  6994. load_history ( hp );
  6995. }
  6996. #endif
  6997. state4: /* XXX ??? - why isn't this before the "if" statement */
  6998. cmdloop(1);
  6999. }
  7000. #if PROFILE
  7001. monitor(0);
  7002. #endif
  7003. #if GPROF
  7004. {
  7005. extern void _mcleanup(void);
  7006. _mcleanup();
  7007. }
  7008. #endif
  7009. exitshell();
  7010. /* NOTREACHED */
  7011. }
  7012. /*
  7013. * Read and execute commands. "Top" is nonzero for the top level command
  7014. * loop; it turns on prompting if the shell is interactive.
  7015. */
  7016. static void
  7017. cmdloop(int top)
  7018. {
  7019. union node *n;
  7020. struct stackmark smark;
  7021. int inter;
  7022. int numeof = 0;
  7023. TRACE(("cmdloop(%d) called\n", top));
  7024. setstackmark(&smark);
  7025. for (;;) {
  7026. if (pendingsigs)
  7027. dotrap();
  7028. #if JOBS
  7029. if (jobctl)
  7030. showjobs(stderr, SHOW_CHANGED);
  7031. #endif
  7032. inter = 0;
  7033. if (iflag && top) {
  7034. inter++;
  7035. #ifdef BB_ASH_MAIL
  7036. chkmail();
  7037. #endif
  7038. }
  7039. n = parsecmd(inter);
  7040. /* showtree(n); DEBUG */
  7041. if (n == NEOF) {
  7042. if (!top || numeof >= 50)
  7043. break;
  7044. if (!stoppedjobs()) {
  7045. if (!Iflag)
  7046. break;
  7047. out2str("\nUse \"exit\" to leave shell.\n");
  7048. }
  7049. numeof++;
  7050. } else if (n != NULL && nflag == 0) {
  7051. job_warning = (job_warning == 2) ? 1 : 0;
  7052. numeof = 0;
  7053. evaltree(n, 0);
  7054. }
  7055. popstackmark(&smark);
  7056. setstackmark(&smark);
  7057. if (evalskip == SKIPFILE) {
  7058. evalskip = 0;
  7059. break;
  7060. }
  7061. }
  7062. popstackmark(&smark);
  7063. }
  7064. /*
  7065. * Read /etc/profile or .profile. Return on error.
  7066. */
  7067. static void
  7068. read_profile(const char *name)
  7069. {
  7070. int fd;
  7071. int xflag_set = 0;
  7072. int vflag_set = 0;
  7073. INTOFF;
  7074. if ((fd = open(name, O_RDONLY)) >= 0)
  7075. setinputfd(fd, 1);
  7076. INTON;
  7077. if (fd < 0)
  7078. return;
  7079. /* -q turns off -x and -v just when executing init files */
  7080. if (qflag) {
  7081. if (xflag)
  7082. xflag = 0, xflag_set = 1;
  7083. if (vflag)
  7084. vflag = 0, vflag_set = 1;
  7085. }
  7086. cmdloop(0);
  7087. if (qflag) {
  7088. if (xflag_set)
  7089. xflag = 1;
  7090. if (vflag_set)
  7091. vflag = 1;
  7092. }
  7093. popfile();
  7094. }
  7095. /*
  7096. * Read a file containing shell functions.
  7097. */
  7098. static void
  7099. readcmdfile(char *name)
  7100. {
  7101. int fd;
  7102. INTOFF;
  7103. if ((fd = open(name, O_RDONLY)) >= 0)
  7104. setinputfd(fd, 1);
  7105. else
  7106. error("Can't open %s", name);
  7107. INTON;
  7108. cmdloop(0);
  7109. popfile();
  7110. }
  7111. /*
  7112. * Take commands from a file. To be compatible we should do a path
  7113. * search for the file, which is necessary to find sub-commands.
  7114. */
  7115. static inline char *
  7116. find_dot_file(char *name)
  7117. {
  7118. char *fullname;
  7119. const char *path = pathval();
  7120. struct stat statb;
  7121. /* don't try this for absolute or relative paths */
  7122. if (strchr(name, '/'))
  7123. return name;
  7124. while ((fullname = padvance(&path, name)) != NULL) {
  7125. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  7126. /*
  7127. * Don't bother freeing here, since it will
  7128. * be freed by the caller.
  7129. */
  7130. return fullname;
  7131. }
  7132. stunalloc(fullname);
  7133. }
  7134. /* not found in the PATH */
  7135. error(not_found_msg, name);
  7136. /* NOTREACHED */
  7137. }
  7138. int
  7139. dotcmd(int argc, char **argv)
  7140. {
  7141. exitstatus = 0;
  7142. if (argc >= 2) { /* That's what SVR2 does */
  7143. char *fullname;
  7144. struct stackmark smark;
  7145. setstackmark(&smark);
  7146. fullname = find_dot_file(argv[1]);
  7147. setinputfile(fullname, 1);
  7148. commandname = fullname;
  7149. cmdloop(0);
  7150. popfile();
  7151. popstackmark(&smark);
  7152. }
  7153. return exitstatus;
  7154. }
  7155. static int
  7156. exitcmd(int argc, char **argv)
  7157. {
  7158. if (stoppedjobs())
  7159. return 0;
  7160. if (argc > 1)
  7161. exitstatus = number(argv[1]);
  7162. exraise(EXEXIT);
  7163. /* NOTREACHED */
  7164. }
  7165. /* $NetBSD: memalloc.c,v 1.27 2003/01/22 20:36:04 dsl Exp $ */
  7166. /*
  7167. * Same for malloc, realloc, but returns an error when out of space.
  7168. */
  7169. static pointer
  7170. ckrealloc(pointer p, size_t nbytes)
  7171. {
  7172. p = realloc(p, nbytes);
  7173. if (p == NULL)
  7174. error(memory_exhausted);
  7175. return p;
  7176. }
  7177. static pointer
  7178. ckmalloc(size_t nbytes)
  7179. {
  7180. return ckrealloc(NULL, nbytes);
  7181. }
  7182. /*
  7183. * Make a copy of a string in safe storage.
  7184. */
  7185. static char *
  7186. savestr(const char *s)
  7187. {
  7188. char *p = strdup(s);
  7189. if (!p)
  7190. error(memory_exhausted);
  7191. return p;
  7192. }
  7193. /*
  7194. * Parse trees for commands are allocated in lifo order, so we use a stack
  7195. * to make this more efficient, and also to avoid all sorts of exception
  7196. * handling code to handle interrupts in the middle of a parse.
  7197. *
  7198. * The size 504 was chosen because the Ultrix malloc handles that size
  7199. * well.
  7200. */
  7201. static pointer
  7202. stalloc(size_t nbytes)
  7203. {
  7204. char *p;
  7205. size_t aligned;
  7206. aligned = SHELL_ALIGN(nbytes);
  7207. if (aligned > stacknleft) {
  7208. size_t len;
  7209. size_t blocksize;
  7210. struct stack_block *sp;
  7211. blocksize = aligned;
  7212. if (blocksize < MINSIZE)
  7213. blocksize = MINSIZE;
  7214. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  7215. if (len < blocksize)
  7216. error(memory_exhausted);
  7217. INTOFF;
  7218. sp = ckmalloc(len);
  7219. sp->prev = stackp;
  7220. stacknxt = sp->space;
  7221. stacknleft = blocksize;
  7222. sstrend = stacknxt + blocksize;
  7223. stackp = sp;
  7224. INTON;
  7225. }
  7226. p = stacknxt;
  7227. stacknxt += aligned;
  7228. stacknleft -= aligned;
  7229. return p;
  7230. }
  7231. void
  7232. stunalloc(pointer p)
  7233. {
  7234. #ifdef DEBUG
  7235. if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
  7236. write(2, "stunalloc\n", 10);
  7237. abort();
  7238. }
  7239. #endif
  7240. stacknleft += stacknxt - (char *)p;
  7241. stacknxt = p;
  7242. }
  7243. void
  7244. setstackmark(struct stackmark *mark)
  7245. {
  7246. mark->stackp = stackp;
  7247. mark->stacknxt = stacknxt;
  7248. mark->stacknleft = stacknleft;
  7249. mark->marknext = markp;
  7250. markp = mark;
  7251. }
  7252. void
  7253. popstackmark(struct stackmark *mark)
  7254. {
  7255. struct stack_block *sp;
  7256. INTOFF;
  7257. markp = mark->marknext;
  7258. while (stackp != mark->stackp) {
  7259. sp = stackp;
  7260. stackp = sp->prev;
  7261. ckfree(sp);
  7262. }
  7263. stacknxt = mark->stacknxt;
  7264. stacknleft = mark->stacknleft;
  7265. sstrend = mark->stacknxt + mark->stacknleft;
  7266. INTON;
  7267. }
  7268. /*
  7269. * When the parser reads in a string, it wants to stick the string on the
  7270. * stack and only adjust the stack pointer when it knows how big the
  7271. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  7272. * of space on top of the stack and stackblocklen returns the length of
  7273. * this block. Growstackblock will grow this space by at least one byte,
  7274. * possibly moving it (like realloc). Grabstackblock actually allocates the
  7275. * part of the block that has been used.
  7276. */
  7277. void
  7278. growstackblock(void)
  7279. {
  7280. size_t newlen;
  7281. newlen = stacknleft * 2;
  7282. if (newlen < stacknleft)
  7283. error(memory_exhausted);
  7284. if (newlen < 128)
  7285. newlen += 128;
  7286. if (stacknxt == stackp->space && stackp != &stackbase) {
  7287. struct stack_block *oldstackp;
  7288. struct stackmark *xmark;
  7289. struct stack_block *sp;
  7290. struct stack_block *prevstackp;
  7291. size_t grosslen;
  7292. INTOFF;
  7293. oldstackp = stackp;
  7294. sp = stackp;
  7295. prevstackp = sp->prev;
  7296. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  7297. sp = ckrealloc((pointer)sp, grosslen);
  7298. sp->prev = prevstackp;
  7299. stackp = sp;
  7300. stacknxt = sp->space;
  7301. stacknleft = newlen;
  7302. sstrend = sp->space + newlen;
  7303. /*
  7304. * Stack marks pointing to the start of the old block
  7305. * must be relocated to point to the new block
  7306. */
  7307. xmark = markp;
  7308. while (xmark != NULL && xmark->stackp == oldstackp) {
  7309. xmark->stackp = stackp;
  7310. xmark->stacknxt = stacknxt;
  7311. xmark->stacknleft = stacknleft;
  7312. xmark = xmark->marknext;
  7313. }
  7314. INTON;
  7315. } else {
  7316. char *oldspace = stacknxt;
  7317. int oldlen = stacknleft;
  7318. char *p = stalloc(newlen);
  7319. /* free the space we just allocated */
  7320. stacknxt = memcpy(p, oldspace, oldlen);
  7321. stacknleft += newlen;
  7322. }
  7323. }
  7324. static inline void
  7325. grabstackblock(size_t len)
  7326. {
  7327. len = SHELL_ALIGN(len);
  7328. stacknxt += len;
  7329. stacknleft -= len;
  7330. }
  7331. /*
  7332. * The following routines are somewhat easier to use than the above.
  7333. * The user declares a variable of type STACKSTR, which may be declared
  7334. * to be a register. The macro STARTSTACKSTR initializes things. Then
  7335. * the user uses the macro STPUTC to add characters to the string. In
  7336. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  7337. * grown as necessary. When the user is done, she can just leave the
  7338. * string there and refer to it using stackblock(). Or she can allocate
  7339. * the space for it using grabstackstr(). If it is necessary to allow
  7340. * someone else to use the stack temporarily and then continue to grow
  7341. * the string, the user should use grabstack to allocate the space, and
  7342. * then call ungrabstr(p) to return to the previous mode of operation.
  7343. *
  7344. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  7345. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  7346. * is space for at least one character.
  7347. */
  7348. void *
  7349. growstackstr(void)
  7350. {
  7351. size_t len = stackblocksize();
  7352. if (herefd >= 0 && len >= 1024) {
  7353. xwrite(herefd, stackblock(), len);
  7354. return stackblock();
  7355. }
  7356. growstackblock();
  7357. return stackblock() + len;
  7358. }
  7359. /*
  7360. * Called from CHECKSTRSPACE.
  7361. */
  7362. char *
  7363. makestrspace(size_t newlen, char *p)
  7364. {
  7365. size_t len = p - stacknxt;
  7366. size_t size = stackblocksize();
  7367. for (;;) {
  7368. size_t nleft;
  7369. size = stackblocksize();
  7370. nleft = size - len;
  7371. if (nleft >= newlen)
  7372. break;
  7373. growstackblock();
  7374. }
  7375. return stackblock() + len;
  7376. }
  7377. char *
  7378. stnputs(const char *s, size_t n, char *p)
  7379. {
  7380. p = makestrspace(n, p);
  7381. p = mempcpy(p, s, n);
  7382. return p;
  7383. }
  7384. char *
  7385. stputs(const char *s, char *p)
  7386. {
  7387. return stnputs(s, strlen(s), p);
  7388. }
  7389. /* $NetBSD: mystring.c,v 1.15 2002/11/24 22:35:42 christos Exp $ */
  7390. /*
  7391. * String functions.
  7392. *
  7393. * number(s) Convert a string of digits to an integer.
  7394. * is_number(s) Return true if s is a string of digits.
  7395. */
  7396. /*
  7397. * prefix -- see if pfx is a prefix of string.
  7398. */
  7399. char *
  7400. prefix(const char *string, const char *pfx)
  7401. {
  7402. while (*pfx) {
  7403. if (*pfx++ != *string++)
  7404. return 0;
  7405. }
  7406. return (char *) string;
  7407. }
  7408. /*
  7409. * Convert a string of digits to an integer, printing an error message on
  7410. * failure.
  7411. */
  7412. int
  7413. number(const char *s)
  7414. {
  7415. if (! is_number(s))
  7416. error(illnum, s);
  7417. return atoi(s);
  7418. }
  7419. /*
  7420. * Check for a valid number. This should be elsewhere.
  7421. */
  7422. int
  7423. is_number(const char *p)
  7424. {
  7425. do {
  7426. if (! is_digit(*p))
  7427. return 0;
  7428. } while (*++p != '\0');
  7429. return 1;
  7430. }
  7431. /*
  7432. * Produce a possibly single quoted string suitable as input to the shell.
  7433. * The return string is allocated on the stack.
  7434. */
  7435. char *
  7436. single_quote(const char *s) {
  7437. char *p;
  7438. STARTSTACKSTR(p);
  7439. do {
  7440. char *q;
  7441. size_t len;
  7442. len = strchrnul(s, '\'') - s;
  7443. q = p = makestrspace(len + 3, p);
  7444. *q++ = '\'';
  7445. q = mempcpy(q, s, len);
  7446. *q++ = '\'';
  7447. s += len;
  7448. STADJUST(q - p, p);
  7449. len = strspn(s, "'");
  7450. if (!len)
  7451. break;
  7452. q = p = makestrspace(len + 3, p);
  7453. *q++ = '"';
  7454. q = mempcpy(q, s, len);
  7455. *q++ = '"';
  7456. s += len;
  7457. STADJUST(q - p, p);
  7458. } while (*s);
  7459. USTPUTC(0, p);
  7460. return stackblock();
  7461. }
  7462. /*
  7463. * Like strdup but works with the ash stack.
  7464. */
  7465. char *
  7466. sstrdup(const char *p)
  7467. {
  7468. size_t len = strlen(p) + 1;
  7469. return memcpy(stalloc(len), p, len);
  7470. }
  7471. static void
  7472. calcsize(union node *n)
  7473. {
  7474. if (n == NULL)
  7475. return;
  7476. funcblocksize += nodesize[n->type];
  7477. switch (n->type) {
  7478. case NCMD:
  7479. calcsize(n->ncmd.redirect);
  7480. calcsize(n->ncmd.args);
  7481. calcsize(n->ncmd.assign);
  7482. break;
  7483. case NPIPE:
  7484. sizenodelist(n->npipe.cmdlist);
  7485. break;
  7486. case NREDIR:
  7487. case NBACKGND:
  7488. case NSUBSHELL:
  7489. calcsize(n->nredir.redirect);
  7490. calcsize(n->nredir.n);
  7491. break;
  7492. case NAND:
  7493. case NOR:
  7494. case NSEMI:
  7495. case NWHILE:
  7496. case NUNTIL:
  7497. calcsize(n->nbinary.ch2);
  7498. calcsize(n->nbinary.ch1);
  7499. break;
  7500. case NIF:
  7501. calcsize(n->nif.elsepart);
  7502. calcsize(n->nif.ifpart);
  7503. calcsize(n->nif.test);
  7504. break;
  7505. case NFOR:
  7506. funcstringsize += strlen(n->nfor.var) + 1;
  7507. calcsize(n->nfor.body);
  7508. calcsize(n->nfor.args);
  7509. break;
  7510. case NCASE:
  7511. calcsize(n->ncase.cases);
  7512. calcsize(n->ncase.expr);
  7513. break;
  7514. case NCLIST:
  7515. calcsize(n->nclist.body);
  7516. calcsize(n->nclist.pattern);
  7517. calcsize(n->nclist.next);
  7518. break;
  7519. case NDEFUN:
  7520. case NARG:
  7521. sizenodelist(n->narg.backquote);
  7522. funcstringsize += strlen(n->narg.text) + 1;
  7523. calcsize(n->narg.next);
  7524. break;
  7525. case NTO:
  7526. case NCLOBBER:
  7527. case NFROM:
  7528. case NFROMTO:
  7529. case NAPPEND:
  7530. calcsize(n->nfile.fname);
  7531. calcsize(n->nfile.next);
  7532. break;
  7533. case NTOFD:
  7534. case NFROMFD:
  7535. calcsize(n->ndup.vname);
  7536. calcsize(n->ndup.next);
  7537. break;
  7538. case NHERE:
  7539. case NXHERE:
  7540. calcsize(n->nhere.doc);
  7541. calcsize(n->nhere.next);
  7542. break;
  7543. case NNOT:
  7544. calcsize(n->nnot.com);
  7545. break;
  7546. };
  7547. }
  7548. static void
  7549. sizenodelist(struct nodelist *lp)
  7550. {
  7551. while (lp) {
  7552. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7553. calcsize(lp->n);
  7554. lp = lp->next;
  7555. }
  7556. }
  7557. static union node *
  7558. copynode(union node *n)
  7559. {
  7560. union node *new;
  7561. if (n == NULL)
  7562. return NULL;
  7563. new = funcblock;
  7564. funcblock = (char *) funcblock + nodesize[n->type];
  7565. switch (n->type) {
  7566. case NCMD:
  7567. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7568. new->ncmd.args = copynode(n->ncmd.args);
  7569. new->ncmd.assign = copynode(n->ncmd.assign);
  7570. break;
  7571. case NPIPE:
  7572. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7573. new->npipe.backgnd = n->npipe.backgnd;
  7574. break;
  7575. case NREDIR:
  7576. case NBACKGND:
  7577. case NSUBSHELL:
  7578. new->nredir.redirect = copynode(n->nredir.redirect);
  7579. new->nredir.n = copynode(n->nredir.n);
  7580. break;
  7581. case NAND:
  7582. case NOR:
  7583. case NSEMI:
  7584. case NWHILE:
  7585. case NUNTIL:
  7586. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7587. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7588. break;
  7589. case NIF:
  7590. new->nif.elsepart = copynode(n->nif.elsepart);
  7591. new->nif.ifpart = copynode(n->nif.ifpart);
  7592. new->nif.test = copynode(n->nif.test);
  7593. break;
  7594. case NFOR:
  7595. new->nfor.var = nodesavestr(n->nfor.var);
  7596. new->nfor.body = copynode(n->nfor.body);
  7597. new->nfor.args = copynode(n->nfor.args);
  7598. break;
  7599. case NCASE:
  7600. new->ncase.cases = copynode(n->ncase.cases);
  7601. new->ncase.expr = copynode(n->ncase.expr);
  7602. break;
  7603. case NCLIST:
  7604. new->nclist.body = copynode(n->nclist.body);
  7605. new->nclist.pattern = copynode(n->nclist.pattern);
  7606. new->nclist.next = copynode(n->nclist.next);
  7607. break;
  7608. case NDEFUN:
  7609. case NARG:
  7610. new->narg.backquote = copynodelist(n->narg.backquote);
  7611. new->narg.text = nodesavestr(n->narg.text);
  7612. new->narg.next = copynode(n->narg.next);
  7613. break;
  7614. case NTO:
  7615. case NCLOBBER:
  7616. case NFROM:
  7617. case NFROMTO:
  7618. case NAPPEND:
  7619. new->nfile.fname = copynode(n->nfile.fname);
  7620. new->nfile.fd = n->nfile.fd;
  7621. new->nfile.next = copynode(n->nfile.next);
  7622. break;
  7623. case NTOFD:
  7624. case NFROMFD:
  7625. new->ndup.vname = copynode(n->ndup.vname);
  7626. new->ndup.dupfd = n->ndup.dupfd;
  7627. new->ndup.fd = n->ndup.fd;
  7628. new->ndup.next = copynode(n->ndup.next);
  7629. break;
  7630. case NHERE:
  7631. case NXHERE:
  7632. new->nhere.doc = copynode(n->nhere.doc);
  7633. new->nhere.fd = n->nhere.fd;
  7634. new->nhere.next = copynode(n->nhere.next);
  7635. break;
  7636. case NNOT:
  7637. new->nnot.com = copynode(n->nnot.com);
  7638. break;
  7639. };
  7640. new->type = n->type;
  7641. return new;
  7642. }
  7643. static struct nodelist *
  7644. copynodelist(struct nodelist *lp)
  7645. {
  7646. struct nodelist *start;
  7647. struct nodelist **lpp;
  7648. lpp = &start;
  7649. while (lp) {
  7650. *lpp = funcblock;
  7651. funcblock = (char *) funcblock +
  7652. SHELL_ALIGN(sizeof(struct nodelist));
  7653. (*lpp)->n = copynode(lp->n);
  7654. lp = lp->next;
  7655. lpp = &(*lpp)->next;
  7656. }
  7657. *lpp = NULL;
  7658. return start;
  7659. }
  7660. static char *
  7661. nodesavestr(char *s)
  7662. {
  7663. char *rtn = funcstring;
  7664. funcstring = stpcpy(funcstring, s) + 1;
  7665. return rtn;
  7666. }
  7667. /*
  7668. * Free a parse tree.
  7669. */
  7670. static void
  7671. freefunc(struct funcnode *f)
  7672. {
  7673. if (f && --f->count < 0)
  7674. ckfree(f);
  7675. }
  7676. static void options(int);
  7677. static void setoption(int, int);
  7678. /*
  7679. * Process the shell command line arguments.
  7680. */
  7681. void
  7682. procargs(int argc, char **argv)
  7683. {
  7684. int i;
  7685. const char *xminusc;
  7686. char **xargv;
  7687. xargv = argv;
  7688. arg0 = xargv[0];
  7689. if (argc > 0)
  7690. xargv++;
  7691. for (i = 0; i < NOPTS; i++)
  7692. optlist[i] = 2;
  7693. argptr = xargv;
  7694. options(1);
  7695. xargv = argptr;
  7696. xminusc = minusc;
  7697. if (*xargv == NULL) {
  7698. if (xminusc)
  7699. error("-c requires an argument");
  7700. sflag = 1;
  7701. }
  7702. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  7703. iflag = 1;
  7704. if (mflag == 2)
  7705. mflag = iflag;
  7706. for (i = 0; i < NOPTS; i++)
  7707. if (optlist[i] == 2)
  7708. optlist[i] = 0;
  7709. #if DEBUG == 2
  7710. debug = 1;
  7711. #endif
  7712. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  7713. if (xminusc) {
  7714. minusc = *xargv++;
  7715. if (*xargv)
  7716. goto setarg0;
  7717. } else if (!sflag) {
  7718. setinputfile(*xargv, 0);
  7719. setarg0:
  7720. arg0 = *xargv++;
  7721. commandname = arg0;
  7722. }
  7723. shellparam.p = xargv;
  7724. #ifdef BB_ASH_GETOPTS
  7725. shellparam.optind = 1;
  7726. shellparam.optoff = -1;
  7727. #endif
  7728. /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
  7729. while (*xargv) {
  7730. shellparam.nparam++;
  7731. xargv++;
  7732. }
  7733. optschanged();
  7734. }
  7735. void
  7736. optschanged(void)
  7737. {
  7738. #ifdef DEBUG
  7739. opentrace();
  7740. #endif
  7741. setinteractive(iflag);
  7742. setjobctl(mflag);
  7743. }
  7744. static inline void
  7745. minus_o(char *name, int val)
  7746. {
  7747. int i;
  7748. if (name == NULL) {
  7749. out1str("Current option settings\n");
  7750. for (i = 0; i < NOPTS; i++)
  7751. out1fmt("%-16s%s\n", optnames(i),
  7752. optlist[i] ? "on" : "off");
  7753. } else {
  7754. for (i = 0; i < NOPTS; i++)
  7755. if (equal(name, optnames(i))) {
  7756. optlist[i] = val;
  7757. return;
  7758. }
  7759. error("Illegal option -o %s", name);
  7760. }
  7761. }
  7762. /*
  7763. * Process shell options. The global variable argptr contains a pointer
  7764. * to the argument list; we advance it past the options.
  7765. */
  7766. static void
  7767. options(int cmdline)
  7768. {
  7769. char *p;
  7770. int val;
  7771. int c;
  7772. if (cmdline)
  7773. minusc = NULL;
  7774. while ((p = *argptr) != NULL) {
  7775. argptr++;
  7776. if ((c = *p++) == '-') {
  7777. val = 1;
  7778. if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
  7779. if (!cmdline) {
  7780. /* "-" means turn off -x and -v */
  7781. if (p[0] == '\0')
  7782. xflag = vflag = 0;
  7783. /* "--" means reset params */
  7784. else if (*argptr == NULL)
  7785. setparam(argptr);
  7786. }
  7787. break; /* "-" or "--" terminates options */
  7788. }
  7789. } else if (c == '+') {
  7790. val = 0;
  7791. } else {
  7792. argptr--;
  7793. break;
  7794. }
  7795. while ((c = *p++) != '\0') {
  7796. if (c == 'c' && cmdline) {
  7797. minusc = p; /* command is after shell args*/
  7798. } else if (c == 'o') {
  7799. minus_o(*argptr, val);
  7800. if (*argptr)
  7801. argptr++;
  7802. } else if (cmdline && (c == '-')) { // long options
  7803. if (strcmp(p, "login") == 0)
  7804. isloginsh = 1;
  7805. break;
  7806. } else {
  7807. setoption(c, val);
  7808. }
  7809. }
  7810. }
  7811. }
  7812. static void
  7813. setoption(int flag, int val)
  7814. {
  7815. int i;
  7816. for (i = 0; i < NOPTS; i++)
  7817. if (optletters(i) == flag) {
  7818. optlist[i] = val;
  7819. return;
  7820. }
  7821. error("Illegal option -%c", flag);
  7822. /* NOTREACHED */
  7823. }
  7824. /*
  7825. * Set the shell parameters.
  7826. */
  7827. void
  7828. setparam(char **argv)
  7829. {
  7830. char **newparam;
  7831. char **ap;
  7832. int nparam;
  7833. for (nparam = 0 ; argv[nparam] ; nparam++);
  7834. ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
  7835. while (*argv) {
  7836. *ap++ = savestr(*argv++);
  7837. }
  7838. *ap = NULL;
  7839. freeparam(&shellparam);
  7840. shellparam.malloc = 1;
  7841. shellparam.nparam = nparam;
  7842. shellparam.p = newparam;
  7843. #ifdef BB_ASH_GETOPTS
  7844. shellparam.optind = 1;
  7845. shellparam.optoff = -1;
  7846. #endif
  7847. }
  7848. /*
  7849. * Free the list of positional parameters.
  7850. */
  7851. void
  7852. freeparam(volatile struct shparam *param)
  7853. {
  7854. char **ap;
  7855. if (param->malloc) {
  7856. for (ap = param->p ; *ap ; ap++)
  7857. ckfree(*ap);
  7858. ckfree(param->p);
  7859. }
  7860. }
  7861. /*
  7862. * The shift builtin command.
  7863. */
  7864. int
  7865. shiftcmd(int argc, char **argv)
  7866. {
  7867. int n;
  7868. char **ap1, **ap2;
  7869. n = 1;
  7870. if (argc > 1)
  7871. n = number(argv[1]);
  7872. if (n > shellparam.nparam)
  7873. error("can't shift that many");
  7874. INTOFF;
  7875. shellparam.nparam -= n;
  7876. for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
  7877. if (shellparam.malloc)
  7878. ckfree(*ap1);
  7879. }
  7880. ap2 = shellparam.p;
  7881. while ((*ap2++ = *ap1++) != NULL);
  7882. #ifdef BB_ASH_GETOPTS
  7883. shellparam.optind = 1;
  7884. shellparam.optoff = -1;
  7885. #endif
  7886. INTON;
  7887. return 0;
  7888. }
  7889. /*
  7890. * The set command builtin.
  7891. */
  7892. int
  7893. setcmd(int argc, char **argv)
  7894. {
  7895. if (argc == 1)
  7896. return showvars(nullstr, 0, VUNSET);
  7897. INTOFF;
  7898. options(0);
  7899. optschanged();
  7900. if (*argptr != NULL) {
  7901. setparam(argptr);
  7902. }
  7903. INTON;
  7904. return 0;
  7905. }
  7906. #ifdef BB_ASH_GETOPTS
  7907. static void
  7908. getoptsreset(value)
  7909. const char *value;
  7910. {
  7911. shellparam.optind = number(value);
  7912. shellparam.optoff = -1;
  7913. }
  7914. #endif
  7915. #ifdef BB_LOCALE_SUPPORT
  7916. static void change_lc_all(const char *value)
  7917. {
  7918. if (value != 0 && *value != 0)
  7919. setlocale(LC_ALL, value);
  7920. }
  7921. static void change_lc_ctype(const char *value)
  7922. {
  7923. if (value != 0 && *value != 0)
  7924. setlocale(LC_CTYPE, value);
  7925. }
  7926. #endif
  7927. #ifdef BB_ASH_GETOPTS
  7928. static int
  7929. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  7930. {
  7931. char *p, *q;
  7932. char c = '?';
  7933. int done = 0;
  7934. int err = 0;
  7935. char s[12];
  7936. char **optnext;
  7937. if(*param_optind < 1)
  7938. return 1;
  7939. optnext = optfirst + *param_optind - 1;
  7940. if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
  7941. p = NULL;
  7942. else
  7943. p = optnext[-1] + *optoff;
  7944. if (p == NULL || *p == '\0') {
  7945. /* Current word is done, advance */
  7946. p = *optnext;
  7947. if (p == NULL || *p != '-' || *++p == '\0') {
  7948. atend:
  7949. p = NULL;
  7950. done = 1;
  7951. goto out;
  7952. }
  7953. optnext++;
  7954. if (p[0] == '-' && p[1] == '\0') /* check for "--" */
  7955. goto atend;
  7956. }
  7957. c = *p++;
  7958. for (q = optstr; *q != c; ) {
  7959. if (*q == '\0') {
  7960. if (optstr[0] == ':') {
  7961. s[0] = c;
  7962. s[1] = '\0';
  7963. err |= setvarsafe("OPTARG", s, 0);
  7964. } else {
  7965. fprintf(stderr, "Illegal option -%c\n", c);
  7966. (void) unsetvar("OPTARG");
  7967. }
  7968. c = '?';
  7969. goto out;
  7970. }
  7971. if (*++q == ':')
  7972. q++;
  7973. }
  7974. if (*++q == ':') {
  7975. if (*p == '\0' && (p = *optnext) == NULL) {
  7976. if (optstr[0] == ':') {
  7977. s[0] = c;
  7978. s[1] = '\0';
  7979. err |= setvarsafe("OPTARG", s, 0);
  7980. c = ':';
  7981. } else {
  7982. fprintf(stderr, "No arg for -%c option\n", c);
  7983. (void) unsetvar("OPTARG");
  7984. c = '?';
  7985. }
  7986. goto out;
  7987. }
  7988. if (p == *optnext)
  7989. optnext++;
  7990. err |= setvarsafe("OPTARG", p, 0);
  7991. p = NULL;
  7992. } else
  7993. err |= setvarsafe("OPTARG", nullstr, 0);
  7994. out:
  7995. *optoff = p ? p - *(optnext - 1) : -1;
  7996. *param_optind = optnext - optfirst + 1;
  7997. fmtstr(s, sizeof(s), "%d", *param_optind);
  7998. err |= setvarsafe("OPTIND", s, VNOFUNC);
  7999. s[0] = c;
  8000. s[1] = '\0';
  8001. err |= setvarsafe(optvar, s, 0);
  8002. if (err) {
  8003. *param_optind = 1;
  8004. *optoff = -1;
  8005. flushall();
  8006. exraise(EXERROR);
  8007. }
  8008. return done;
  8009. }
  8010. /*
  8011. * The getopts builtin. Shellparam.optnext points to the next argument
  8012. * to be processed. Shellparam.optptr points to the next character to
  8013. * be processed in the current argument. If shellparam.optnext is NULL,
  8014. * then it's the first time getopts has been called.
  8015. */
  8016. int
  8017. getoptscmd(int argc, char **argv)
  8018. {
  8019. char **optbase;
  8020. if (argc < 3)
  8021. error("Usage: getopts optstring var [arg]");
  8022. else if (argc == 3) {
  8023. optbase = shellparam.p;
  8024. if (shellparam.optind > shellparam.nparam + 1) {
  8025. shellparam.optind = 1;
  8026. shellparam.optoff = -1;
  8027. }
  8028. }
  8029. else {
  8030. optbase = &argv[3];
  8031. if (shellparam.optind > argc - 2) {
  8032. shellparam.optind = 1;
  8033. shellparam.optoff = -1;
  8034. }
  8035. }
  8036. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  8037. &shellparam.optoff);
  8038. }
  8039. #endif /* BB_ASH_GETOPTS */
  8040. /*
  8041. * XXX - should get rid of. have all builtins use getopt(3). the
  8042. * library getopt must have the BSD extension static variable "optreset"
  8043. * otherwise it can't be used within the shell safely.
  8044. *
  8045. * Standard option processing (a la getopt) for builtin routines. The
  8046. * only argument that is passed to nextopt is the option string; the
  8047. * other arguments are unnecessary. It return the character, or '\0' on
  8048. * end of input.
  8049. */
  8050. static int
  8051. nextopt(const char *optstring)
  8052. {
  8053. char *p;
  8054. const char *q;
  8055. char c;
  8056. if ((p = optptr) == NULL || *p == '\0') {
  8057. p = *argptr;
  8058. if (p == NULL || *p != '-' || *++p == '\0')
  8059. return '\0';
  8060. argptr++;
  8061. if (p[0] == '-' && p[1] == '\0') /* check for "--" */
  8062. return '\0';
  8063. }
  8064. c = *p++;
  8065. for (q = optstring ; *q != c ; ) {
  8066. if (*q == '\0')
  8067. error("Illegal option -%c", c);
  8068. if (*++q == ':')
  8069. q++;
  8070. }
  8071. if (*++q == ':') {
  8072. if (*p == '\0' && (p = *argptr++) == NULL)
  8073. error("No arg for -%c option", c);
  8074. optionarg = p;
  8075. p = NULL;
  8076. }
  8077. optptr = p;
  8078. return c;
  8079. }
  8080. /* $NetBSD: output.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
  8081. void
  8082. outstr(const char *p, FILE *file)
  8083. {
  8084. INTOFF;
  8085. fputs(p, file);
  8086. INTON;
  8087. }
  8088. void
  8089. flushall(void)
  8090. {
  8091. INTOFF;
  8092. fflush(stdout);
  8093. fflush(stderr);
  8094. INTON;
  8095. }
  8096. void
  8097. flushout(FILE *dest)
  8098. {
  8099. INTOFF;
  8100. fflush(dest);
  8101. INTON;
  8102. }
  8103. static void
  8104. outcslow(int c, FILE *dest)
  8105. {
  8106. INTOFF;
  8107. putc(c, dest);
  8108. fflush(dest);
  8109. INTON;
  8110. }
  8111. static int
  8112. out1fmt(const char *fmt, ...)
  8113. {
  8114. va_list ap;
  8115. int r;
  8116. INTOFF;
  8117. va_start(ap, fmt);
  8118. r = vprintf(fmt, ap);
  8119. va_end(ap);
  8120. INTON;
  8121. return r;
  8122. }
  8123. int
  8124. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  8125. {
  8126. va_list ap;
  8127. int ret;
  8128. va_start(ap, fmt);
  8129. INTOFF;
  8130. ret = vsnprintf(outbuf, length, fmt, ap);
  8131. va_end(ap);
  8132. INTON;
  8133. return ret;
  8134. }
  8135. /*
  8136. * Version of write which resumes after a signal is caught.
  8137. */
  8138. static void
  8139. xwrite(int fd, const void *p, size_t n)
  8140. {
  8141. ssize_t i;
  8142. do {
  8143. i = full_write(fd, p, n);
  8144. } while (i < 0 && errno == EINTR);
  8145. }
  8146. /* $NetBSD: parser.c,v 1.54 2002/11/24 22:35:42 christos Exp $ */
  8147. /*
  8148. * Shell command parser.
  8149. */
  8150. #define EOFMARKLEN 79
  8151. struct heredoc {
  8152. struct heredoc *next; /* next here document in list */
  8153. union node *here; /* redirection node */
  8154. char *eofmark; /* string indicating end of input */
  8155. int striptabs; /* if set, strip leading tabs */
  8156. };
  8157. static struct heredoc *heredoclist; /* list of here documents to read */
  8158. static union node *list(int);
  8159. static union node *andor(void);
  8160. static union node *pipeline(void);
  8161. static union node *command(void);
  8162. static union node *simplecmd(void);
  8163. static union node *makename(void);
  8164. static void parsefname(void);
  8165. static void parseheredoc(void);
  8166. static char peektoken(void);
  8167. static int readtoken(void);
  8168. static int xxreadtoken(void);
  8169. static int readtoken1(int firstc, int syntax, char *eofmark, int striptabs);
  8170. static int noexpand(char *);
  8171. static void synexpect(int) __attribute__((__noreturn__));
  8172. static void synerror(const char *) __attribute__((__noreturn__));
  8173. static void setprompt(int);
  8174. static inline int
  8175. goodname(const char *p)
  8176. {
  8177. return !*endofname(p);
  8178. }
  8179. static inline int
  8180. isassignment(const char *p)
  8181. {
  8182. const char *q = endofname(p);
  8183. if (p == q)
  8184. return 0;
  8185. return *q == '=';
  8186. }
  8187. /*
  8188. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  8189. * valid parse tree indicating a blank line.)
  8190. */
  8191. union node *
  8192. parsecmd(int interact)
  8193. {
  8194. int t;
  8195. tokpushback = 0;
  8196. doprompt = interact;
  8197. if (doprompt)
  8198. setprompt(doprompt);
  8199. needprompt = 0;
  8200. t = readtoken();
  8201. if (t == TEOF)
  8202. return NEOF;
  8203. if (t == TNL)
  8204. return NULL;
  8205. tokpushback++;
  8206. return list(1);
  8207. }
  8208. static union node *
  8209. list(int nlflag)
  8210. {
  8211. union node *n1, *n2, *n3;
  8212. int tok;
  8213. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8214. if (nlflag == 2 && peektoken())
  8215. return NULL;
  8216. n1 = NULL;
  8217. for (;;) {
  8218. n2 = andor();
  8219. tok = readtoken();
  8220. if (tok == TBACKGND) {
  8221. if (n2->type == NPIPE) {
  8222. n2->npipe.backgnd = 1;
  8223. } else {
  8224. if (n2->type != NREDIR) {
  8225. n3 = stalloc(sizeof(struct nredir));
  8226. n3->nredir.n = n2;
  8227. n3->nredir.redirect = NULL;
  8228. n2 = n3;
  8229. }
  8230. n2->type = NBACKGND;
  8231. }
  8232. }
  8233. if (n1 == NULL) {
  8234. n1 = n2;
  8235. }
  8236. else {
  8237. n3 = (union node *)stalloc(sizeof (struct nbinary));
  8238. n3->type = NSEMI;
  8239. n3->nbinary.ch1 = n1;
  8240. n3->nbinary.ch2 = n2;
  8241. n1 = n3;
  8242. }
  8243. switch (tok) {
  8244. case TBACKGND:
  8245. case TSEMI:
  8246. tok = readtoken();
  8247. /* fall through */
  8248. case TNL:
  8249. if (tok == TNL) {
  8250. parseheredoc();
  8251. if (nlflag == 1)
  8252. return n1;
  8253. } else {
  8254. tokpushback++;
  8255. }
  8256. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8257. if (peektoken())
  8258. return n1;
  8259. break;
  8260. case TEOF:
  8261. if (heredoclist)
  8262. parseheredoc();
  8263. else
  8264. pungetc(); /* push back EOF on input */
  8265. return n1;
  8266. default:
  8267. if (nlflag == 1)
  8268. synexpect(-1);
  8269. tokpushback++;
  8270. return n1;
  8271. }
  8272. }
  8273. }
  8274. static union node *
  8275. andor(void)
  8276. {
  8277. union node *n1, *n2, *n3;
  8278. int t;
  8279. n1 = pipeline();
  8280. for (;;) {
  8281. if ((t = readtoken()) == TAND) {
  8282. t = NAND;
  8283. } else if (t == TOR) {
  8284. t = NOR;
  8285. } else {
  8286. tokpushback++;
  8287. return n1;
  8288. }
  8289. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8290. n2 = pipeline();
  8291. n3 = (union node *)stalloc(sizeof (struct nbinary));
  8292. n3->type = t;
  8293. n3->nbinary.ch1 = n1;
  8294. n3->nbinary.ch2 = n2;
  8295. n1 = n3;
  8296. }
  8297. }
  8298. static union node *
  8299. pipeline(void)
  8300. {
  8301. union node *n1, *n2, *pipenode;
  8302. struct nodelist *lp, *prev;
  8303. int negate;
  8304. negate = 0;
  8305. TRACE(("pipeline: entered\n"));
  8306. if (readtoken() == TNOT) {
  8307. negate = !negate;
  8308. checkkwd = CHKKWD | CHKALIAS;
  8309. } else
  8310. tokpushback++;
  8311. n1 = command();
  8312. if (readtoken() == TPIPE) {
  8313. pipenode = (union node *)stalloc(sizeof (struct npipe));
  8314. pipenode->type = NPIPE;
  8315. pipenode->npipe.backgnd = 0;
  8316. lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  8317. pipenode->npipe.cmdlist = lp;
  8318. lp->n = n1;
  8319. do {
  8320. prev = lp;
  8321. lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  8322. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8323. lp->n = command();
  8324. prev->next = lp;
  8325. } while (readtoken() == TPIPE);
  8326. lp->next = NULL;
  8327. n1 = pipenode;
  8328. }
  8329. tokpushback++;
  8330. if (negate) {
  8331. n2 = (union node *)stalloc(sizeof (struct nnot));
  8332. n2->type = NNOT;
  8333. n2->nnot.com = n1;
  8334. return n2;
  8335. } else
  8336. return n1;
  8337. }
  8338. static union node *
  8339. command(void)
  8340. {
  8341. union node *n1, *n2;
  8342. union node *ap, **app;
  8343. union node *cp, **cpp;
  8344. union node *redir, **rpp;
  8345. union node **rpp2;
  8346. int t;
  8347. redir = NULL;
  8348. rpp2 = &redir;
  8349. switch (readtoken()) {
  8350. default:
  8351. synexpect(-1);
  8352. /* NOTREACHED */
  8353. case TIF:
  8354. n1 = (union node *)stalloc(sizeof (struct nif));
  8355. n1->type = NIF;
  8356. n1->nif.test = list(0);
  8357. if (readtoken() != TTHEN)
  8358. synexpect(TTHEN);
  8359. n1->nif.ifpart = list(0);
  8360. n2 = n1;
  8361. while (readtoken() == TELIF) {
  8362. n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
  8363. n2 = n2->nif.elsepart;
  8364. n2->type = NIF;
  8365. n2->nif.test = list(0);
  8366. if (readtoken() != TTHEN)
  8367. synexpect(TTHEN);
  8368. n2->nif.ifpart = list(0);
  8369. }
  8370. if (lasttoken == TELSE)
  8371. n2->nif.elsepart = list(0);
  8372. else {
  8373. n2->nif.elsepart = NULL;
  8374. tokpushback++;
  8375. }
  8376. t = TFI;
  8377. break;
  8378. case TWHILE:
  8379. case TUNTIL: {
  8380. int got;
  8381. n1 = (union node *)stalloc(sizeof (struct nbinary));
  8382. n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
  8383. n1->nbinary.ch1 = list(0);
  8384. if ((got=readtoken()) != TDO) {
  8385. TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
  8386. synexpect(TDO);
  8387. }
  8388. n1->nbinary.ch2 = list(0);
  8389. t = TDONE;
  8390. break;
  8391. }
  8392. case TFOR:
  8393. if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
  8394. synerror("Bad for loop variable");
  8395. n1 = (union node *)stalloc(sizeof (struct nfor));
  8396. n1->type = NFOR;
  8397. n1->nfor.var = wordtext;
  8398. checkkwd = CHKKWD | CHKALIAS;
  8399. if (readtoken() == TIN) {
  8400. app = &ap;
  8401. while (readtoken() == TWORD) {
  8402. n2 = (union node *)stalloc(sizeof (struct narg));
  8403. n2->type = NARG;
  8404. n2->narg.text = wordtext;
  8405. n2->narg.backquote = backquotelist;
  8406. *app = n2;
  8407. app = &n2->narg.next;
  8408. }
  8409. *app = NULL;
  8410. n1->nfor.args = ap;
  8411. if (lasttoken != TNL && lasttoken != TSEMI)
  8412. synexpect(-1);
  8413. } else {
  8414. n2 = (union node *)stalloc(sizeof (struct narg));
  8415. n2->type = NARG;
  8416. n2->narg.text = (char *)dolatstr;
  8417. n2->narg.backquote = NULL;
  8418. n2->narg.next = NULL;
  8419. n1->nfor.args = n2;
  8420. /*
  8421. * Newline or semicolon here is optional (but note
  8422. * that the original Bourne shell only allowed NL).
  8423. */
  8424. if (lasttoken != TNL && lasttoken != TSEMI)
  8425. tokpushback++;
  8426. }
  8427. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8428. if (readtoken() != TDO)
  8429. synexpect(TDO);
  8430. n1->nfor.body = list(0);
  8431. t = TDONE;
  8432. break;
  8433. case TCASE:
  8434. n1 = (union node *)stalloc(sizeof (struct ncase));
  8435. n1->type = NCASE;
  8436. if (readtoken() != TWORD)
  8437. synexpect(TWORD);
  8438. n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
  8439. n2->type = NARG;
  8440. n2->narg.text = wordtext;
  8441. n2->narg.backquote = backquotelist;
  8442. n2->narg.next = NULL;
  8443. do {
  8444. checkkwd = CHKKWD | CHKALIAS;
  8445. } while (readtoken() == TNL);
  8446. if (lasttoken != TIN)
  8447. synexpect(TIN);
  8448. cpp = &n1->ncase.cases;
  8449. next_case:
  8450. checkkwd = CHKNL | CHKKWD;
  8451. t = readtoken();
  8452. while(t != TESAC) {
  8453. if (lasttoken == TLP)
  8454. readtoken();
  8455. *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
  8456. cp->type = NCLIST;
  8457. app = &cp->nclist.pattern;
  8458. for (;;) {
  8459. *app = ap = (union node *)stalloc(sizeof (struct narg));
  8460. ap->type = NARG;
  8461. ap->narg.text = wordtext;
  8462. ap->narg.backquote = backquotelist;
  8463. if (readtoken() != TPIPE)
  8464. break;
  8465. app = &ap->narg.next;
  8466. readtoken();
  8467. }
  8468. ap->narg.next = NULL;
  8469. if (lasttoken != TRP)
  8470. synexpect(TRP);
  8471. cp->nclist.body = list(2);
  8472. cpp = &cp->nclist.next;
  8473. checkkwd = CHKNL | CHKKWD;
  8474. if ((t = readtoken()) != TESAC) {
  8475. if (t != TENDCASE)
  8476. synexpect(TENDCASE);
  8477. else
  8478. goto next_case;
  8479. }
  8480. }
  8481. *cpp = NULL;
  8482. goto redir;
  8483. case TLP:
  8484. n1 = (union node *)stalloc(sizeof (struct nredir));
  8485. n1->type = NSUBSHELL;
  8486. n1->nredir.n = list(0);
  8487. n1->nredir.redirect = NULL;
  8488. t = TRP;
  8489. break;
  8490. case TBEGIN:
  8491. n1 = list(0);
  8492. t = TEND;
  8493. break;
  8494. case TWORD:
  8495. case TREDIR:
  8496. tokpushback++;
  8497. return simplecmd();
  8498. }
  8499. if (readtoken() != t)
  8500. synexpect(t);
  8501. redir:
  8502. /* Now check for redirection which may follow command */
  8503. checkkwd = CHKKWD | CHKALIAS;
  8504. rpp = rpp2;
  8505. while (readtoken() == TREDIR) {
  8506. *rpp = n2 = redirnode;
  8507. rpp = &n2->nfile.next;
  8508. parsefname();
  8509. }
  8510. tokpushback++;
  8511. *rpp = NULL;
  8512. if (redir) {
  8513. if (n1->type != NSUBSHELL) {
  8514. n2 = (union node *)stalloc(sizeof (struct nredir));
  8515. n2->type = NREDIR;
  8516. n2->nredir.n = n1;
  8517. n1 = n2;
  8518. }
  8519. n1->nredir.redirect = redir;
  8520. }
  8521. return n1;
  8522. }
  8523. static union node *
  8524. simplecmd(void) {
  8525. union node *args, **app;
  8526. union node *n = NULL;
  8527. union node *vars, **vpp;
  8528. union node **rpp, *redir;
  8529. int savecheckkwd;
  8530. args = NULL;
  8531. app = &args;
  8532. vars = NULL;
  8533. vpp = &vars;
  8534. redir = NULL;
  8535. rpp = &redir;
  8536. savecheckkwd = CHKALIAS;
  8537. for (;;) {
  8538. checkkwd = savecheckkwd;
  8539. switch (readtoken()) {
  8540. case TWORD:
  8541. n = (union node *)stalloc(sizeof (struct narg));
  8542. n->type = NARG;
  8543. n->narg.text = wordtext;
  8544. n->narg.backquote = backquotelist;
  8545. if (savecheckkwd && isassignment(wordtext)) {
  8546. *vpp = n;
  8547. vpp = &n->narg.next;
  8548. } else {
  8549. *app = n;
  8550. app = &n->narg.next;
  8551. savecheckkwd = 0;
  8552. }
  8553. break;
  8554. case TREDIR:
  8555. *rpp = n = redirnode;
  8556. rpp = &n->nfile.next;
  8557. parsefname(); /* read name of redirection file */
  8558. break;
  8559. case TLP:
  8560. if (
  8561. args && app == &args->narg.next &&
  8562. !vars && !redir
  8563. ) {
  8564. struct builtincmd *bcmd;
  8565. const char *name;
  8566. /* We have a function */
  8567. if (readtoken() != TRP)
  8568. synexpect(TRP);
  8569. name = n->narg.text;
  8570. if (
  8571. !goodname(name) || (
  8572. (bcmd = find_builtin(name)) &&
  8573. IS_BUILTIN_SPECIAL(bcmd)
  8574. )
  8575. )
  8576. synerror("Bad function name");
  8577. n->type = NDEFUN;
  8578. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8579. n->narg.next = command();
  8580. return n;
  8581. }
  8582. /* fall through */
  8583. default:
  8584. tokpushback++;
  8585. goto out;
  8586. }
  8587. }
  8588. out:
  8589. *app = NULL;
  8590. *vpp = NULL;
  8591. *rpp = NULL;
  8592. n = (union node *)stalloc(sizeof (struct ncmd));
  8593. n->type = NCMD;
  8594. n->ncmd.args = args;
  8595. n->ncmd.assign = vars;
  8596. n->ncmd.redirect = redir;
  8597. return n;
  8598. }
  8599. static union node *
  8600. makename(void)
  8601. {
  8602. union node *n;
  8603. n = (union node *)stalloc(sizeof (struct narg));
  8604. n->type = NARG;
  8605. n->narg.next = NULL;
  8606. n->narg.text = wordtext;
  8607. n->narg.backquote = backquotelist;
  8608. return n;
  8609. }
  8610. void fixredir(union node *n, const char *text, int err)
  8611. {
  8612. TRACE(("Fix redir %s %d\n", text, err));
  8613. if (!err)
  8614. n->ndup.vname = NULL;
  8615. if (is_digit(text[0]) && text[1] == '\0')
  8616. n->ndup.dupfd = digit_val(text[0]);
  8617. else if (text[0] == '-' && text[1] == '\0')
  8618. n->ndup.dupfd = -1;
  8619. else {
  8620. if (err)
  8621. synerror("Bad fd number");
  8622. else
  8623. n->ndup.vname = makename();
  8624. }
  8625. }
  8626. static void
  8627. parsefname(void)
  8628. {
  8629. union node *n = redirnode;
  8630. if (readtoken() != TWORD)
  8631. synexpect(-1);
  8632. if (n->type == NHERE) {
  8633. struct heredoc *here = heredoc;
  8634. struct heredoc *p;
  8635. int i;
  8636. if (quoteflag == 0)
  8637. n->type = NXHERE;
  8638. TRACE(("Here document %d\n", n->type));
  8639. if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  8640. synerror("Illegal eof marker for << redirection");
  8641. rmescapes(wordtext);
  8642. here->eofmark = wordtext;
  8643. here->next = NULL;
  8644. if (heredoclist == NULL)
  8645. heredoclist = here;
  8646. else {
  8647. for (p = heredoclist ; p->next ; p = p->next);
  8648. p->next = here;
  8649. }
  8650. } else if (n->type == NTOFD || n->type == NFROMFD) {
  8651. fixredir(n, wordtext, 0);
  8652. } else {
  8653. n->nfile.fname = makename();
  8654. }
  8655. }
  8656. /*
  8657. * Input any here documents.
  8658. */
  8659. static void
  8660. parseheredoc(void)
  8661. {
  8662. struct heredoc *here;
  8663. union node *n;
  8664. here = heredoclist;
  8665. heredoclist = 0;
  8666. while (here) {
  8667. if (needprompt) {
  8668. setprompt(2);
  8669. needprompt = 0;
  8670. }
  8671. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  8672. here->eofmark, here->striptabs);
  8673. n = (union node *)stalloc(sizeof (struct narg));
  8674. n->narg.type = NARG;
  8675. n->narg.next = NULL;
  8676. n->narg.text = wordtext;
  8677. n->narg.backquote = backquotelist;
  8678. here->here->nhere.doc = n;
  8679. here = here->next;
  8680. }
  8681. }
  8682. static char peektoken(void)
  8683. {
  8684. int t;
  8685. t = readtoken();
  8686. tokpushback++;
  8687. return tokname_array[t][0];
  8688. }
  8689. static int
  8690. readtoken(void)
  8691. {
  8692. int t;
  8693. #ifdef DEBUG
  8694. int alreadyseen = tokpushback;
  8695. #endif
  8696. #ifdef BB_ASH_ALIAS
  8697. top:
  8698. #endif
  8699. t = xxreadtoken();
  8700. /*
  8701. * eat newlines
  8702. */
  8703. if (checkkwd & CHKNL) {
  8704. while (t == TNL) {
  8705. parseheredoc();
  8706. t = xxreadtoken();
  8707. }
  8708. }
  8709. if (t != TWORD || quoteflag) {
  8710. goto out;
  8711. }
  8712. /*
  8713. * check for keywords
  8714. */
  8715. if (checkkwd & CHKKWD) {
  8716. const char *const *pp;
  8717. if ((pp = findkwd(wordtext))) {
  8718. lasttoken = t = pp - tokname_array;
  8719. TRACE(("keyword %s recognized\n", tokname(t)));
  8720. goto out;
  8721. }
  8722. }
  8723. if (checkkwd & CHKALIAS) {
  8724. #ifdef BB_ASH_ALIAS
  8725. struct alias *ap;
  8726. if ((ap = lookupalias(wordtext, 1)) != NULL) {
  8727. if (*ap->val) {
  8728. pushstring(ap->val, ap);
  8729. }
  8730. goto top;
  8731. }
  8732. #endif
  8733. }
  8734. out:
  8735. checkkwd = 0;
  8736. #ifdef DEBUG
  8737. if (!alreadyseen)
  8738. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  8739. else
  8740. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  8741. #endif
  8742. return (t);
  8743. }
  8744. /*
  8745. * Read the next input token.
  8746. * If the token is a word, we set backquotelist to the list of cmds in
  8747. * backquotes. We set quoteflag to true if any part of the word was
  8748. * quoted.
  8749. * If the token is TREDIR, then we set redirnode to a structure containing
  8750. * the redirection.
  8751. * In all cases, the variable startlinno is set to the number of the line
  8752. * on which the token starts.
  8753. *
  8754. * [Change comment: here documents and internal procedures]
  8755. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  8756. * word parsing code into a separate routine. In this case, readtoken
  8757. * doesn't need to have any internal procedures, but parseword does.
  8758. * We could also make parseoperator in essence the main routine, and
  8759. * have parseword (readtoken1?) handle both words and redirection.]
  8760. */
  8761. #define NEW_xxreadtoken
  8762. #ifdef NEW_xxreadtoken
  8763. /* singles must be first! */
  8764. static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
  8765. static const char xxreadtoken_tokens[] = {
  8766. TNL, TLP, TRP, /* only single occurrence allowed */
  8767. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  8768. TEOF, /* corresponds to trailing nul */
  8769. TAND, TOR, TENDCASE, /* if double occurrence */
  8770. };
  8771. #define xxreadtoken_doubles \
  8772. (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
  8773. #define xxreadtoken_singles \
  8774. (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
  8775. static int xxreadtoken()
  8776. {
  8777. int c;
  8778. if (tokpushback) {
  8779. tokpushback = 0;
  8780. return lasttoken;
  8781. }
  8782. if (needprompt) {
  8783. setprompt(2);
  8784. needprompt = 0;
  8785. }
  8786. startlinno = plinno;
  8787. for (;;) { /* until token or start of word found */
  8788. c = pgetc_macro();
  8789. if ((c != ' ') && (c != '\t')
  8790. #ifdef BB_ASH_ALIAS
  8791. && (c != PEOA)
  8792. #endif
  8793. ) {
  8794. if (c == '#') {
  8795. while ((c = pgetc()) != '\n' && c != PEOF);
  8796. pungetc();
  8797. } else if (c == '\\') {
  8798. if (pgetc() != '\n') {
  8799. pungetc();
  8800. goto READTOKEN1;
  8801. }
  8802. startlinno = ++plinno;
  8803. if (doprompt)
  8804. setprompt(2);
  8805. } else {
  8806. const char *p
  8807. = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  8808. if (c != PEOF) {
  8809. if (c == '\n') {
  8810. plinno++;
  8811. needprompt = doprompt;
  8812. }
  8813. p = strchr(xxreadtoken_chars, c);
  8814. if (p == NULL) {
  8815. READTOKEN1:
  8816. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  8817. }
  8818. if (p - xxreadtoken_chars >= xxreadtoken_singles) {
  8819. if (pgetc() == *p) { /* double occurrence? */
  8820. p += xxreadtoken_doubles + 1;
  8821. } else {
  8822. pungetc();
  8823. }
  8824. }
  8825. }
  8826. return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  8827. }
  8828. }
  8829. }
  8830. }
  8831. #else
  8832. #define RETURN(token) return lasttoken = token
  8833. static int
  8834. xxreadtoken(void)
  8835. {
  8836. int c;
  8837. if (tokpushback) {
  8838. tokpushback = 0;
  8839. return lasttoken;
  8840. }
  8841. if (needprompt) {
  8842. setprompt(2);
  8843. needprompt = 0;
  8844. }
  8845. startlinno = plinno;
  8846. for (;;) { /* until token or start of word found */
  8847. c = pgetc_macro();
  8848. switch (c) {
  8849. case ' ': case '\t':
  8850. #ifdef BB_ASH_ALIAS
  8851. case PEOA:
  8852. #endif
  8853. continue;
  8854. case '#':
  8855. while ((c = pgetc()) != '\n' && c != PEOF);
  8856. pungetc();
  8857. continue;
  8858. case '\\':
  8859. if (pgetc() == '\n') {
  8860. startlinno = ++plinno;
  8861. if (doprompt)
  8862. setprompt(2);
  8863. continue;
  8864. }
  8865. pungetc();
  8866. goto breakloop;
  8867. case '\n':
  8868. plinno++;
  8869. needprompt = doprompt;
  8870. RETURN(TNL);
  8871. case PEOF:
  8872. RETURN(TEOF);
  8873. case '&':
  8874. if (pgetc() == '&')
  8875. RETURN(TAND);
  8876. pungetc();
  8877. RETURN(TBACKGND);
  8878. case '|':
  8879. if (pgetc() == '|')
  8880. RETURN(TOR);
  8881. pungetc();
  8882. RETURN(TPIPE);
  8883. case ';':
  8884. if (pgetc() == ';')
  8885. RETURN(TENDCASE);
  8886. pungetc();
  8887. RETURN(TSEMI);
  8888. case '(':
  8889. RETURN(TLP);
  8890. case ')':
  8891. RETURN(TRP);
  8892. default:
  8893. goto breakloop;
  8894. }
  8895. }
  8896. breakloop:
  8897. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  8898. #undef RETURN
  8899. }
  8900. #endif /* NEW_xxreadtoken */
  8901. /*
  8902. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  8903. * is not NULL, read a here document. In the latter case, eofmark is the
  8904. * word which marks the end of the document and striptabs is true if
  8905. * leading tabs should be stripped from the document. The argument firstc
  8906. * is the first character of the input token or document.
  8907. *
  8908. * Because C does not have internal subroutines, I have simulated them
  8909. * using goto's to implement the subroutine linkage. The following macros
  8910. * will run code that appears at the end of readtoken1.
  8911. */
  8912. #define CHECKEND() {goto checkend; checkend_return:;}
  8913. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  8914. #define PARSESUB() {goto parsesub; parsesub_return:;}
  8915. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  8916. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  8917. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  8918. static int
  8919. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  8920. {
  8921. int c = firstc;
  8922. char *out;
  8923. int len;
  8924. char line[EOFMARKLEN + 1];
  8925. struct nodelist *bqlist;
  8926. int quotef;
  8927. int dblquote;
  8928. int varnest; /* levels of variables expansion */
  8929. int arinest; /* levels of arithmetic expansion */
  8930. int parenlevel; /* levels of parens in arithmetic */
  8931. int dqvarnest; /* levels of variables expansion within double quotes */
  8932. int oldstyle;
  8933. int prevsyntax; /* syntax before arithmetic */
  8934. #if __GNUC__
  8935. /* Avoid longjmp clobbering */
  8936. (void) &out;
  8937. (void) &quotef;
  8938. (void) &dblquote;
  8939. (void) &varnest;
  8940. (void) &arinest;
  8941. (void) &parenlevel;
  8942. (void) &dqvarnest;
  8943. (void) &oldstyle;
  8944. (void) &prevsyntax;
  8945. (void) &syntax;
  8946. #endif
  8947. startlinno = plinno;
  8948. dblquote = 0;
  8949. if (syntax == DQSYNTAX)
  8950. dblquote = 1;
  8951. quotef = 0;
  8952. bqlist = NULL;
  8953. varnest = 0;
  8954. arinest = 0;
  8955. parenlevel = 0;
  8956. dqvarnest = 0;
  8957. STARTSTACKSTR(out);
  8958. loop: { /* for each line, until end of word */
  8959. CHECKEND(); /* set c to PEOF if at end of here document */
  8960. for (;;) { /* until end of line or end of word */
  8961. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  8962. switch(SIT(c, syntax)) {
  8963. case CNL: /* '\n' */
  8964. if (syntax == BASESYNTAX)
  8965. goto endword; /* exit outer loop */
  8966. USTPUTC(c, out);
  8967. plinno++;
  8968. if (doprompt)
  8969. setprompt(2);
  8970. c = pgetc();
  8971. goto loop; /* continue outer loop */
  8972. case CWORD:
  8973. USTPUTC(c, out);
  8974. break;
  8975. case CCTL:
  8976. if (eofmark == NULL || dblquote)
  8977. USTPUTC(CTLESC, out);
  8978. USTPUTC(c, out);
  8979. break;
  8980. case CBACK: /* backslash */
  8981. c = pgetc2();
  8982. if (c == PEOF) {
  8983. USTPUTC(CTLESC, out);
  8984. USTPUTC('\\', out);
  8985. pungetc();
  8986. } else if (c == '\n') {
  8987. if (doprompt)
  8988. setprompt(2);
  8989. } else {
  8990. if (
  8991. dblquote &&
  8992. c != '\\' && c != '`' &&
  8993. c != '$' && (
  8994. c != '"' ||
  8995. eofmark != NULL
  8996. )
  8997. ) {
  8998. USTPUTC(CTLESC, out);
  8999. USTPUTC('\\', out);
  9000. }
  9001. if (SIT(c, SQSYNTAX) == CCTL)
  9002. USTPUTC(CTLESC, out);
  9003. USTPUTC(c, out);
  9004. quotef++;
  9005. }
  9006. break;
  9007. case CSQUOTE:
  9008. syntax = SQSYNTAX;
  9009. quotemark:
  9010. if (eofmark == NULL) {
  9011. USTPUTC(CTLQUOTEMARK, out);
  9012. }
  9013. break;
  9014. case CDQUOTE:
  9015. syntax = DQSYNTAX;
  9016. dblquote = 1;
  9017. goto quotemark;
  9018. case CENDQUOTE:
  9019. if (eofmark != NULL && arinest == 0 &&
  9020. varnest == 0) {
  9021. USTPUTC(c, out);
  9022. } else {
  9023. if (dqvarnest == 0) {
  9024. syntax = BASESYNTAX;
  9025. dblquote = 0;
  9026. }
  9027. quotef++;
  9028. goto quotemark;
  9029. }
  9030. break;
  9031. case CVAR: /* '$' */
  9032. PARSESUB(); /* parse substitution */
  9033. break;
  9034. case CENDVAR: /* '}' */
  9035. if (varnest > 0) {
  9036. varnest--;
  9037. if (dqvarnest > 0) {
  9038. dqvarnest--;
  9039. }
  9040. USTPUTC(CTLENDVAR, out);
  9041. } else {
  9042. USTPUTC(c, out);
  9043. }
  9044. break;
  9045. #ifdef BB_ASH_MATH_SUPPORT
  9046. case CLP: /* '(' in arithmetic */
  9047. parenlevel++;
  9048. USTPUTC(c, out);
  9049. break;
  9050. case CRP: /* ')' in arithmetic */
  9051. if (parenlevel > 0) {
  9052. USTPUTC(c, out);
  9053. --parenlevel;
  9054. } else {
  9055. if (pgetc() == ')') {
  9056. if (--arinest == 0) {
  9057. USTPUTC(CTLENDARI, out);
  9058. syntax = prevsyntax;
  9059. if (syntax == DQSYNTAX)
  9060. dblquote = 1;
  9061. else
  9062. dblquote = 0;
  9063. } else
  9064. USTPUTC(')', out);
  9065. } else {
  9066. /*
  9067. * unbalanced parens
  9068. * (don't 2nd guess - no error)
  9069. */
  9070. pungetc();
  9071. USTPUTC(')', out);
  9072. }
  9073. }
  9074. break;
  9075. #endif
  9076. case CBQUOTE: /* '`' */
  9077. PARSEBACKQOLD();
  9078. break;
  9079. case CENDFILE:
  9080. goto endword; /* exit outer loop */
  9081. case CIGN:
  9082. break;
  9083. default:
  9084. if (varnest == 0)
  9085. goto endword; /* exit outer loop */
  9086. #ifdef BB_ASH_ALIAS
  9087. if (c != PEOA)
  9088. #endif
  9089. USTPUTC(c, out);
  9090. }
  9091. c = pgetc_macro();
  9092. }
  9093. }
  9094. endword:
  9095. #ifdef BB_ASH_MATH_SUPPORT
  9096. if (syntax == ARISYNTAX)
  9097. synerror("Missing '))'");
  9098. #endif
  9099. if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
  9100. synerror("Unterminated quoted string");
  9101. if (varnest != 0) {
  9102. startlinno = plinno;
  9103. /* { */
  9104. synerror("Missing '}'");
  9105. }
  9106. USTPUTC('\0', out);
  9107. len = out - (char *)stackblock();
  9108. out = stackblock();
  9109. if (eofmark == NULL) {
  9110. if ((c == '>' || c == '<')
  9111. && quotef == 0
  9112. && len <= 2
  9113. && (*out == '\0' || is_digit(*out))) {
  9114. PARSEREDIR();
  9115. return lasttoken = TREDIR;
  9116. } else {
  9117. pungetc();
  9118. }
  9119. }
  9120. quoteflag = quotef;
  9121. backquotelist = bqlist;
  9122. grabstackblock(len);
  9123. wordtext = out;
  9124. return lasttoken = TWORD;
  9125. /* end of readtoken routine */
  9126. /*
  9127. * Check to see whether we are at the end of the here document. When this
  9128. * is called, c is set to the first character of the next input line. If
  9129. * we are at the end of the here document, this routine sets the c to PEOF.
  9130. */
  9131. checkend: {
  9132. if (eofmark) {
  9133. #ifdef BB_ASH_ALIAS
  9134. if (c == PEOA) {
  9135. c = pgetc2();
  9136. }
  9137. #endif
  9138. if (striptabs) {
  9139. while (c == '\t') {
  9140. c = pgetc2();
  9141. }
  9142. }
  9143. if (c == *eofmark) {
  9144. if (pfgets(line, sizeof line) != NULL) {
  9145. char *p, *q;
  9146. p = line;
  9147. for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
  9148. if (*p == '\n' && *q == '\0') {
  9149. c = PEOF;
  9150. plinno++;
  9151. needprompt = doprompt;
  9152. } else {
  9153. pushstring(line, NULL);
  9154. }
  9155. }
  9156. }
  9157. }
  9158. goto checkend_return;
  9159. }
  9160. /*
  9161. * Parse a redirection operator. The variable "out" points to a string
  9162. * specifying the fd to be redirected. The variable "c" contains the
  9163. * first character of the redirection operator.
  9164. */
  9165. parseredir: {
  9166. char fd = *out;
  9167. union node *np;
  9168. np = (union node *)stalloc(sizeof (struct nfile));
  9169. if (c == '>') {
  9170. np->nfile.fd = 1;
  9171. c = pgetc();
  9172. if (c == '>')
  9173. np->type = NAPPEND;
  9174. else if (c == '|')
  9175. np->type = NCLOBBER;
  9176. else if (c == '&')
  9177. np->type = NTOFD;
  9178. else {
  9179. np->type = NTO;
  9180. pungetc();
  9181. }
  9182. } else { /* c == '<' */
  9183. np->nfile.fd = 0;
  9184. switch (c = pgetc()) {
  9185. case '<':
  9186. if (sizeof (struct nfile) != sizeof (struct nhere)) {
  9187. np = (union node *)stalloc(sizeof (struct nhere));
  9188. np->nfile.fd = 0;
  9189. }
  9190. np->type = NHERE;
  9191. heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
  9192. heredoc->here = np;
  9193. if ((c = pgetc()) == '-') {
  9194. heredoc->striptabs = 1;
  9195. } else {
  9196. heredoc->striptabs = 0;
  9197. pungetc();
  9198. }
  9199. break;
  9200. case '&':
  9201. np->type = NFROMFD;
  9202. break;
  9203. case '>':
  9204. np->type = NFROMTO;
  9205. break;
  9206. default:
  9207. np->type = NFROM;
  9208. pungetc();
  9209. break;
  9210. }
  9211. }
  9212. if (fd != '\0')
  9213. np->nfile.fd = digit_val(fd);
  9214. redirnode = np;
  9215. goto parseredir_return;
  9216. }
  9217. /*
  9218. * Parse a substitution. At this point, we have read the dollar sign
  9219. * and nothing else.
  9220. */
  9221. parsesub: {
  9222. int subtype;
  9223. int typeloc;
  9224. int flags;
  9225. char *p;
  9226. static const char types[] = "}-+?=";
  9227. c = pgetc();
  9228. if (
  9229. c <= PEOA_OR_PEOF ||
  9230. (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  9231. ) {
  9232. USTPUTC('$', out);
  9233. pungetc();
  9234. } else if (c == '(') { /* $(command) or $((arith)) */
  9235. if (pgetc() == '(') {
  9236. #ifdef BB_ASH_MATH_SUPPORT
  9237. PARSEARITH();
  9238. #else
  9239. synerror("We unsupport $((arith))");
  9240. #endif
  9241. } else {
  9242. pungetc();
  9243. PARSEBACKQNEW();
  9244. }
  9245. } else {
  9246. USTPUTC(CTLVAR, out);
  9247. typeloc = out - (char *)stackblock();
  9248. USTPUTC(VSNORMAL, out);
  9249. subtype = VSNORMAL;
  9250. if (c == '{') {
  9251. c = pgetc();
  9252. if (c == '#') {
  9253. if ((c = pgetc()) == '}')
  9254. c = '#';
  9255. else
  9256. subtype = VSLENGTH;
  9257. }
  9258. else
  9259. subtype = 0;
  9260. }
  9261. if (c > PEOA_OR_PEOF && is_name(c)) {
  9262. do {
  9263. STPUTC(c, out);
  9264. c = pgetc();
  9265. } while (c > PEOA_OR_PEOF && is_in_name(c));
  9266. } else if (is_digit(c)) {
  9267. do {
  9268. STPUTC(c, out);
  9269. c = pgetc();
  9270. } while (is_digit(c));
  9271. }
  9272. else if (is_special(c)) {
  9273. USTPUTC(c, out);
  9274. c = pgetc();
  9275. }
  9276. else
  9277. badsub: synerror("Bad substitution");
  9278. STPUTC('=', out);
  9279. flags = 0;
  9280. if (subtype == 0) {
  9281. switch (c) {
  9282. case ':':
  9283. flags = VSNUL;
  9284. c = pgetc();
  9285. /*FALLTHROUGH*/
  9286. default:
  9287. p = strchr(types, c);
  9288. if (p == NULL)
  9289. goto badsub;
  9290. subtype = p - types + VSNORMAL;
  9291. break;
  9292. case '%':
  9293. case '#':
  9294. {
  9295. int cc = c;
  9296. subtype = c == '#' ? VSTRIMLEFT :
  9297. VSTRIMRIGHT;
  9298. c = pgetc();
  9299. if (c == cc)
  9300. subtype++;
  9301. else
  9302. pungetc();
  9303. break;
  9304. }
  9305. }
  9306. } else {
  9307. pungetc();
  9308. }
  9309. if (dblquote || arinest)
  9310. flags |= VSQUOTE;
  9311. *((char *)stackblock() + typeloc) = subtype | flags;
  9312. if (subtype != VSNORMAL) {
  9313. varnest++;
  9314. if (dblquote || arinest) {
  9315. dqvarnest++;
  9316. }
  9317. }
  9318. }
  9319. goto parsesub_return;
  9320. }
  9321. /*
  9322. * Called to parse command substitutions. Newstyle is set if the command
  9323. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  9324. * list of commands (passed by reference), and savelen is the number of
  9325. * characters on the top of the stack which must be preserved.
  9326. */
  9327. parsebackq: {
  9328. struct nodelist **nlpp;
  9329. int savepbq;
  9330. union node *n;
  9331. char *volatile str;
  9332. struct jmploc jmploc;
  9333. struct jmploc *volatile savehandler;
  9334. size_t savelen;
  9335. int saveprompt;
  9336. #ifdef __GNUC__
  9337. (void) &saveprompt;
  9338. #endif
  9339. savepbq = parsebackquote;
  9340. if (setjmp(jmploc.loc)) {
  9341. if (str)
  9342. ckfree(str);
  9343. parsebackquote = 0;
  9344. handler = savehandler;
  9345. longjmp(handler->loc, 1);
  9346. }
  9347. INTOFF;
  9348. str = NULL;
  9349. savelen = out - (char *)stackblock();
  9350. if (savelen > 0) {
  9351. str = ckmalloc(savelen);
  9352. memcpy(str, stackblock(), savelen);
  9353. }
  9354. savehandler = handler;
  9355. handler = &jmploc;
  9356. INTON;
  9357. if (oldstyle) {
  9358. /* We must read until the closing backquote, giving special
  9359. treatment to some slashes, and then push the string and
  9360. reread it as input, interpreting it normally. */
  9361. char *pout;
  9362. int pc;
  9363. size_t psavelen;
  9364. char *pstr;
  9365. STARTSTACKSTR(pout);
  9366. for (;;) {
  9367. if (needprompt) {
  9368. setprompt(2);
  9369. needprompt = 0;
  9370. }
  9371. switch (pc = pgetc()) {
  9372. case '`':
  9373. goto done;
  9374. case '\\':
  9375. if ((pc = pgetc()) == '\n') {
  9376. plinno++;
  9377. if (doprompt)
  9378. setprompt(2);
  9379. /*
  9380. * If eating a newline, avoid putting
  9381. * the newline into the new character
  9382. * stream (via the STPUTC after the
  9383. * switch).
  9384. */
  9385. continue;
  9386. }
  9387. if (pc != '\\' && pc != '`' && pc != '$'
  9388. && (!dblquote || pc != '"'))
  9389. STPUTC('\\', pout);
  9390. if (pc > PEOA_OR_PEOF) {
  9391. break;
  9392. }
  9393. /* fall through */
  9394. case PEOF:
  9395. #ifdef BB_ASH_ALIAS
  9396. case PEOA:
  9397. #endif
  9398. startlinno = plinno;
  9399. synerror("EOF in backquote substitution");
  9400. case '\n':
  9401. plinno++;
  9402. needprompt = doprompt;
  9403. break;
  9404. default:
  9405. break;
  9406. }
  9407. STPUTC(pc, pout);
  9408. }
  9409. done:
  9410. STPUTC('\0', pout);
  9411. psavelen = pout - (char *)stackblock();
  9412. if (psavelen > 0) {
  9413. pstr = grabstackstr(pout);
  9414. setinputstring(pstr);
  9415. }
  9416. }
  9417. nlpp = &bqlist;
  9418. while (*nlpp)
  9419. nlpp = &(*nlpp)->next;
  9420. *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
  9421. (*nlpp)->next = NULL;
  9422. parsebackquote = oldstyle;
  9423. if (oldstyle) {
  9424. saveprompt = doprompt;
  9425. doprompt = 0;
  9426. }
  9427. n = list(2);
  9428. if (oldstyle)
  9429. doprompt = saveprompt;
  9430. else {
  9431. if (readtoken() != TRP)
  9432. synexpect(TRP);
  9433. }
  9434. (*nlpp)->n = n;
  9435. if (oldstyle) {
  9436. /*
  9437. * Start reading from old file again, ignoring any pushed back
  9438. * tokens left from the backquote parsing
  9439. */
  9440. popfile();
  9441. tokpushback = 0;
  9442. }
  9443. while (stackblocksize() <= savelen)
  9444. growstackblock();
  9445. STARTSTACKSTR(out);
  9446. if (str) {
  9447. memcpy(out, str, savelen);
  9448. STADJUST(savelen, out);
  9449. INTOFF;
  9450. ckfree(str);
  9451. str = NULL;
  9452. INTON;
  9453. }
  9454. parsebackquote = savepbq;
  9455. handler = savehandler;
  9456. if (arinest || dblquote)
  9457. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  9458. else
  9459. USTPUTC(CTLBACKQ, out);
  9460. if (oldstyle)
  9461. goto parsebackq_oldreturn;
  9462. else
  9463. goto parsebackq_newreturn;
  9464. }
  9465. #ifdef BB_ASH_MATH_SUPPORT
  9466. /*
  9467. * Parse an arithmetic expansion (indicate start of one and set state)
  9468. */
  9469. parsearith: {
  9470. if (++arinest == 1) {
  9471. prevsyntax = syntax;
  9472. syntax = ARISYNTAX;
  9473. USTPUTC(CTLARI, out);
  9474. if (dblquote)
  9475. USTPUTC('"',out);
  9476. else
  9477. USTPUTC(' ',out);
  9478. } else {
  9479. /*
  9480. * we collapse embedded arithmetic expansion to
  9481. * parenthesis, which should be equivalent
  9482. */
  9483. USTPUTC('(', out);
  9484. }
  9485. goto parsearith_return;
  9486. }
  9487. #endif
  9488. } /* end of readtoken */
  9489. /*
  9490. * Returns true if the text contains nothing to expand (no dollar signs
  9491. * or backquotes).
  9492. */
  9493. static int
  9494. noexpand(char *text)
  9495. {
  9496. char *p;
  9497. char c;
  9498. p = text;
  9499. while ((c = *p++) != '\0') {
  9500. if (c == CTLQUOTEMARK)
  9501. continue;
  9502. if (c == CTLESC)
  9503. p++;
  9504. else if (SIT(c, BASESYNTAX) == CCTL)
  9505. return 0;
  9506. }
  9507. return 1;
  9508. }
  9509. /*
  9510. * Return of a legal variable name (a letter or underscore followed by zero or
  9511. * more letters, underscores, and digits).
  9512. */
  9513. char *
  9514. endofname(const char *name)
  9515. {
  9516. char *p;
  9517. p = (char *) name;
  9518. if (! is_name(*p))
  9519. return p;
  9520. while (*++p) {
  9521. if (! is_in_name(*p))
  9522. break;
  9523. }
  9524. return p;
  9525. }
  9526. /*
  9527. * Called when an unexpected token is read during the parse. The argument
  9528. * is the token that is expected, or -1 if more than one type of token can
  9529. * occur at this point.
  9530. */
  9531. static void synexpect(int token)
  9532. {
  9533. char msg[64];
  9534. int l;
  9535. l = sprintf(msg, "%s unexpected", tokname(lasttoken));
  9536. if (token >= 0)
  9537. sprintf(msg + l, " (expecting %s)", tokname(token));
  9538. synerror(msg);
  9539. /* NOTREACHED */
  9540. }
  9541. static void
  9542. synerror(const char *msg)
  9543. {
  9544. error("Syntax error: %s", msg);
  9545. /* NOTREACHED */
  9546. }
  9547. /*
  9548. * called by editline -- any expansions to the prompt
  9549. * should be added here.
  9550. */
  9551. static void setprompt(int whichprompt)
  9552. {
  9553. const char *prompt;
  9554. switch (whichprompt) {
  9555. case 1:
  9556. prompt = ps1val();
  9557. break;
  9558. case 2:
  9559. prompt = ps2val();
  9560. break;
  9561. default: /* 0 */
  9562. prompt = nullstr;
  9563. }
  9564. putprompt(prompt);
  9565. }
  9566. static const char *const *findkwd(const char *s)
  9567. {
  9568. return bsearch(s, tokname_array + KWDOFFSET,
  9569. (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
  9570. sizeof(const char *), pstrcmp);
  9571. }
  9572. /* $NetBSD: redir.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
  9573. /*
  9574. * Code for dealing with input/output redirection.
  9575. */
  9576. #define EMPTY -2 /* marks an unused slot in redirtab */
  9577. #ifndef PIPE_BUF
  9578. # define PIPESIZE 4096 /* amount of buffering in a pipe */
  9579. #else
  9580. # define PIPESIZE PIPE_BUF
  9581. #endif
  9582. /*
  9583. * Open a file in noclobber mode.
  9584. * The code was copied from bash.
  9585. */
  9586. static inline int
  9587. noclobberopen(const char *fname)
  9588. {
  9589. int r, fd;
  9590. struct stat finfo, finfo2;
  9591. /*
  9592. * If the file exists and is a regular file, return an error
  9593. * immediately.
  9594. */
  9595. r = stat(fname, &finfo);
  9596. if (r == 0 && S_ISREG(finfo.st_mode)) {
  9597. errno = EEXIST;
  9598. return -1;
  9599. }
  9600. /*
  9601. * If the file was not present (r != 0), make sure we open it
  9602. * exclusively so that if it is created before we open it, our open
  9603. * will fail. Make sure that we do not truncate an existing file.
  9604. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  9605. * file was not a regular file, we leave O_EXCL off.
  9606. */
  9607. if (r != 0)
  9608. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  9609. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  9610. /* If the open failed, return the file descriptor right away. */
  9611. if (fd < 0)
  9612. return fd;
  9613. /*
  9614. * OK, the open succeeded, but the file may have been changed from a
  9615. * non-regular file to a regular file between the stat and the open.
  9616. * We are assuming that the O_EXCL open handles the case where FILENAME
  9617. * did not exist and is symlinked to an existing file between the stat
  9618. * and open.
  9619. */
  9620. /*
  9621. * If we can open it and fstat the file descriptor, and neither check
  9622. * revealed that it was a regular file, and the file has not been
  9623. * replaced, return the file descriptor.
  9624. */
  9625. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
  9626. finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  9627. return fd;
  9628. /* The file has been replaced. badness. */
  9629. close(fd);
  9630. errno = EEXIST;
  9631. return -1;
  9632. }
  9633. /*
  9634. * Handle here documents. Normally we fork off a process to write the
  9635. * data to a pipe. If the document is short, we can stuff the data in
  9636. * the pipe without forking.
  9637. */
  9638. static inline int
  9639. openhere(union node *redir)
  9640. {
  9641. int pip[2];
  9642. size_t len = 0;
  9643. if (pipe(pip) < 0)
  9644. error("Pipe call failed");
  9645. if (redir->type == NHERE) {
  9646. len = strlen(redir->nhere.doc->narg.text);
  9647. if (len <= PIPESIZE) {
  9648. xwrite(pip[1], redir->nhere.doc->narg.text, len);
  9649. goto out;
  9650. }
  9651. }
  9652. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  9653. close(pip[0]);
  9654. signal(SIGINT, SIG_IGN);
  9655. signal(SIGQUIT, SIG_IGN);
  9656. signal(SIGHUP, SIG_IGN);
  9657. #ifdef SIGTSTP
  9658. signal(SIGTSTP, SIG_IGN);
  9659. #endif
  9660. signal(SIGPIPE, SIG_DFL);
  9661. if (redir->type == NHERE)
  9662. xwrite(pip[1], redir->nhere.doc->narg.text, len);
  9663. else
  9664. expandhere(redir->nhere.doc, pip[1]);
  9665. _exit(0);
  9666. }
  9667. out:
  9668. close(pip[1]);
  9669. return pip[0];
  9670. }
  9671. static int
  9672. openredirect(union node *redir)
  9673. {
  9674. char *fname;
  9675. int f;
  9676. switch (redir->nfile.type) {
  9677. case NFROM:
  9678. fname = redir->nfile.expfname;
  9679. if ((f = open(fname, O_RDONLY)) < 0)
  9680. goto eopen;
  9681. break;
  9682. case NFROMTO:
  9683. fname = redir->nfile.expfname;
  9684. if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
  9685. goto ecreate;
  9686. break;
  9687. case NTO:
  9688. /* Take care of noclobber mode. */
  9689. if (Cflag) {
  9690. fname = redir->nfile.expfname;
  9691. if ((f = noclobberopen(fname)) < 0)
  9692. goto ecreate;
  9693. break;
  9694. }
  9695. /* FALLTHROUGH */
  9696. case NCLOBBER:
  9697. fname = redir->nfile.expfname;
  9698. if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
  9699. goto ecreate;
  9700. break;
  9701. case NAPPEND:
  9702. fname = redir->nfile.expfname;
  9703. if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
  9704. goto ecreate;
  9705. break;
  9706. default:
  9707. #ifdef DEBUG
  9708. abort();
  9709. #endif
  9710. /* Fall through to eliminate warning. */
  9711. case NTOFD:
  9712. case NFROMFD:
  9713. f = -1;
  9714. break;
  9715. case NHERE:
  9716. case NXHERE:
  9717. f = openhere(redir);
  9718. break;
  9719. }
  9720. return f;
  9721. ecreate:
  9722. error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  9723. eopen:
  9724. error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
  9725. }
  9726. static inline void
  9727. dupredirect(union node *redir, int f)
  9728. {
  9729. int fd = redir->nfile.fd;
  9730. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  9731. if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
  9732. ash_copyfd(redir->ndup.dupfd, fd);
  9733. }
  9734. return;
  9735. }
  9736. if (f != fd) {
  9737. ash_copyfd(f, fd);
  9738. close(f);
  9739. }
  9740. return;
  9741. }
  9742. /*
  9743. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  9744. * old file descriptors are stashed away so that the redirection can be
  9745. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  9746. * standard output, and the standard error if it becomes a duplicate of
  9747. * stdout, is saved in memory.
  9748. */
  9749. static void
  9750. redirect(union node *redir, int flags)
  9751. {
  9752. union node *n;
  9753. struct redirtab *sv;
  9754. int i;
  9755. int fd;
  9756. int newfd;
  9757. int *p;
  9758. nullredirs++;
  9759. if (!redir) {
  9760. return;
  9761. }
  9762. sv = NULL;
  9763. INTOFF;
  9764. if (flags & REDIR_PUSH) {
  9765. struct redirtab *q;
  9766. q = ckmalloc(sizeof (struct redirtab));
  9767. q->next = redirlist;
  9768. redirlist = q;
  9769. q->nullredirs = nullredirs - 1;
  9770. for (i = 0 ; i < 10 ; i++)
  9771. q->renamed[i] = EMPTY;
  9772. nullredirs = 0;
  9773. sv = q;
  9774. }
  9775. n = redir;
  9776. do {
  9777. fd = n->nfile.fd;
  9778. if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
  9779. n->ndup.dupfd == fd)
  9780. continue; /* redirect from/to same file descriptor */
  9781. newfd = openredirect(n);
  9782. if (fd == newfd)
  9783. continue;
  9784. if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
  9785. i = fcntl(fd, F_DUPFD, 10);
  9786. if (i == -1) {
  9787. i = errno;
  9788. if (i != EBADF) {
  9789. close(newfd);
  9790. errno = i;
  9791. error("%d: %m", fd);
  9792. /* NOTREACHED */
  9793. }
  9794. } else {
  9795. *p = i;
  9796. close(fd);
  9797. }
  9798. } else {
  9799. close(fd);
  9800. }
  9801. dupredirect(n, newfd);
  9802. } while ((n = n->nfile.next));
  9803. INTON;
  9804. if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
  9805. preverrout_fd = sv->renamed[2];
  9806. }
  9807. /*
  9808. * Undo the effects of the last redirection.
  9809. */
  9810. void
  9811. popredir(int drop)
  9812. {
  9813. struct redirtab *rp;
  9814. int i;
  9815. if (--nullredirs >= 0)
  9816. return;
  9817. INTOFF;
  9818. rp = redirlist;
  9819. for (i = 0 ; i < 10 ; i++) {
  9820. if (rp->renamed[i] != EMPTY) {
  9821. if (!drop) {
  9822. close(i);
  9823. ash_copyfd(rp->renamed[i], i);
  9824. }
  9825. close(rp->renamed[i]);
  9826. }
  9827. }
  9828. redirlist = rp->next;
  9829. nullredirs = rp->nullredirs;
  9830. ckfree(rp);
  9831. INTON;
  9832. }
  9833. /*
  9834. * Undo all redirections. Called on error or interrupt.
  9835. */
  9836. /*
  9837. * Discard all saved file descriptors.
  9838. */
  9839. void
  9840. clearredir(int drop)
  9841. {
  9842. for (;;) {
  9843. nullredirs = 0;
  9844. if (!redirlist)
  9845. break;
  9846. popredir(drop);
  9847. }
  9848. }
  9849. /*
  9850. * Copy a file descriptor to be >= to. Returns -1
  9851. * if the source file descriptor is closed, EMPTY if there are no unused
  9852. * file descriptors left.
  9853. */
  9854. int
  9855. ash_copyfd(int from, int to)
  9856. {
  9857. int newfd;
  9858. newfd = fcntl(from, F_DUPFD, to);
  9859. if (newfd < 0) {
  9860. if (errno == EMFILE)
  9861. return EMPTY;
  9862. else
  9863. error("%d: %m", from);
  9864. }
  9865. return newfd;
  9866. }
  9867. int
  9868. redirectsafe(union node *redir, int flags)
  9869. {
  9870. int err;
  9871. volatile int saveint;
  9872. struct jmploc *volatile savehandler = handler;
  9873. struct jmploc jmploc;
  9874. SAVEINT(saveint);
  9875. if (!(err = setjmp(jmploc.loc) * 2)) {
  9876. handler = &jmploc;
  9877. redirect(redir, flags);
  9878. }
  9879. handler = savehandler;
  9880. if (err && exception != EXERROR)
  9881. longjmp(handler->loc, 1);
  9882. RESTOREINT(saveint);
  9883. return err;
  9884. }
  9885. /* $NetBSD: show.c,v 1.24 2003/01/22 20:36:04 dsl Exp $ */
  9886. #ifdef DEBUG
  9887. static void shtree(union node *, int, char *, FILE*);
  9888. static void shcmd(union node *, FILE *);
  9889. static void sharg(union node *, FILE *);
  9890. static void indent(int, char *, FILE *);
  9891. static void trstring(char *);
  9892. void
  9893. showtree(union node *n)
  9894. {
  9895. trputs("showtree called\n");
  9896. shtree(n, 1, NULL, stdout);
  9897. }
  9898. static void
  9899. shtree(union node *n, int ind, char *pfx, FILE *fp)
  9900. {
  9901. struct nodelist *lp;
  9902. const char *s;
  9903. if (n == NULL)
  9904. return;
  9905. indent(ind, pfx, fp);
  9906. switch(n->type) {
  9907. case NSEMI:
  9908. s = "; ";
  9909. goto binop;
  9910. case NAND:
  9911. s = " && ";
  9912. goto binop;
  9913. case NOR:
  9914. s = " || ";
  9915. binop:
  9916. shtree(n->nbinary.ch1, ind, NULL, fp);
  9917. /* if (ind < 0) */
  9918. fputs(s, fp);
  9919. shtree(n->nbinary.ch2, ind, NULL, fp);
  9920. break;
  9921. case NCMD:
  9922. shcmd(n, fp);
  9923. if (ind >= 0)
  9924. putc('\n', fp);
  9925. break;
  9926. case NPIPE:
  9927. for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
  9928. shcmd(lp->n, fp);
  9929. if (lp->next)
  9930. fputs(" | ", fp);
  9931. }
  9932. if (n->npipe.backgnd)
  9933. fputs(" &", fp);
  9934. if (ind >= 0)
  9935. putc('\n', fp);
  9936. break;
  9937. default:
  9938. fprintf(fp, "<node type %d>", n->type);
  9939. if (ind >= 0)
  9940. putc('\n', fp);
  9941. break;
  9942. }
  9943. }
  9944. static void
  9945. shcmd(union node *cmd, FILE *fp)
  9946. {
  9947. union node *np;
  9948. int first;
  9949. const char *s;
  9950. int dftfd;
  9951. first = 1;
  9952. for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
  9953. if (! first)
  9954. putchar(' ');
  9955. sharg(np, fp);
  9956. first = 0;
  9957. }
  9958. for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
  9959. if (! first)
  9960. putchar(' ');
  9961. switch (np->nfile.type) {
  9962. case NTO: s = ">"; dftfd = 1; break;
  9963. case NCLOBBER: s = ">|"; dftfd = 1; break;
  9964. case NAPPEND: s = ">>"; dftfd = 1; break;
  9965. case NTOFD: s = ">&"; dftfd = 1; break;
  9966. case NFROM: s = "<"; dftfd = 0; break;
  9967. case NFROMFD: s = "<&"; dftfd = 0; break;
  9968. case NFROMTO: s = "<>"; dftfd = 0; break;
  9969. default: s = "*error*"; dftfd = 0; break;
  9970. }
  9971. if (np->nfile.fd != dftfd)
  9972. fprintf(fp, "%d", np->nfile.fd);
  9973. fputs(s, fp);
  9974. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  9975. fprintf(fp, "%d", np->ndup.dupfd);
  9976. } else {
  9977. sharg(np->nfile.fname, fp);
  9978. }
  9979. first = 0;
  9980. }
  9981. }
  9982. static void
  9983. sharg(union node *arg, FILE *fp)
  9984. {
  9985. char *p;
  9986. struct nodelist *bqlist;
  9987. int subtype;
  9988. if (arg->type != NARG) {
  9989. out1fmt("<node type %d>\n", arg->type);
  9990. abort();
  9991. }
  9992. bqlist = arg->narg.backquote;
  9993. for (p = arg->narg.text ; *p ; p++) {
  9994. switch (*p) {
  9995. case CTLESC:
  9996. putc(*++p, fp);
  9997. break;
  9998. case CTLVAR:
  9999. putc('$', fp);
  10000. putc('{', fp);
  10001. subtype = *++p;
  10002. if (subtype == VSLENGTH)
  10003. putc('#', fp);
  10004. while (*p != '=')
  10005. putc(*p++, fp);
  10006. if (subtype & VSNUL)
  10007. putc(':', fp);
  10008. switch (subtype & VSTYPE) {
  10009. case VSNORMAL:
  10010. putc('}', fp);
  10011. break;
  10012. case VSMINUS:
  10013. putc('-', fp);
  10014. break;
  10015. case VSPLUS:
  10016. putc('+', fp);
  10017. break;
  10018. case VSQUESTION:
  10019. putc('?', fp);
  10020. break;
  10021. case VSASSIGN:
  10022. putc('=', fp);
  10023. break;
  10024. case VSTRIMLEFT:
  10025. putc('#', fp);
  10026. break;
  10027. case VSTRIMLEFTMAX:
  10028. putc('#', fp);
  10029. putc('#', fp);
  10030. break;
  10031. case VSTRIMRIGHT:
  10032. putc('%', fp);
  10033. break;
  10034. case VSTRIMRIGHTMAX:
  10035. putc('%', fp);
  10036. putc('%', fp);
  10037. break;
  10038. case VSLENGTH:
  10039. break;
  10040. default:
  10041. out1fmt("<subtype %d>", subtype);
  10042. }
  10043. break;
  10044. case CTLENDVAR:
  10045. putc('}', fp);
  10046. break;
  10047. case CTLBACKQ:
  10048. case CTLBACKQ|CTLQUOTE:
  10049. putc('$', fp);
  10050. putc('(', fp);
  10051. shtree(bqlist->n, -1, NULL, fp);
  10052. putc(')', fp);
  10053. break;
  10054. default:
  10055. putc(*p, fp);
  10056. break;
  10057. }
  10058. }
  10059. }
  10060. static void
  10061. indent(int amount, char *pfx, FILE *fp)
  10062. {
  10063. int i;
  10064. for (i = 0 ; i < amount ; i++) {
  10065. if (pfx && i == amount - 1)
  10066. fputs(pfx, fp);
  10067. putc('\t', fp);
  10068. }
  10069. }
  10070. /*
  10071. * Debugging stuff.
  10072. */
  10073. FILE *tracefile;
  10074. void
  10075. trputc(int c)
  10076. {
  10077. if (debug != 1)
  10078. return;
  10079. putc(c, tracefile);
  10080. }
  10081. void
  10082. trace(const char *fmt, ...)
  10083. {
  10084. va_list va;
  10085. if (debug != 1)
  10086. return;
  10087. va_start(va, fmt);
  10088. (void) vfprintf(tracefile, fmt, va);
  10089. va_end(va);
  10090. }
  10091. void
  10092. tracev(const char *fmt, va_list va)
  10093. {
  10094. if (debug != 1)
  10095. return;
  10096. (void) vfprintf(tracefile, fmt, va);
  10097. }
  10098. void
  10099. trputs(const char *s)
  10100. {
  10101. if (debug != 1)
  10102. return;
  10103. fputs(s, tracefile);
  10104. }
  10105. static void
  10106. trstring(char *s)
  10107. {
  10108. char *p;
  10109. char c;
  10110. if (debug != 1)
  10111. return;
  10112. putc('"', tracefile);
  10113. for (p = s ; *p ; p++) {
  10114. switch (*p) {
  10115. case '\n': c = 'n'; goto backslash;
  10116. case '\t': c = 't'; goto backslash;
  10117. case '\r': c = 'r'; goto backslash;
  10118. case '"': c = '"'; goto backslash;
  10119. case '\\': c = '\\'; goto backslash;
  10120. case CTLESC: c = 'e'; goto backslash;
  10121. case CTLVAR: c = 'v'; goto backslash;
  10122. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  10123. case CTLBACKQ: c = 'q'; goto backslash;
  10124. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  10125. backslash: putc('\\', tracefile);
  10126. putc(c, tracefile);
  10127. break;
  10128. default:
  10129. if (*p >= ' ' && *p <= '~')
  10130. putc(*p, tracefile);
  10131. else {
  10132. putc('\\', tracefile);
  10133. putc(*p >> 6 & 03, tracefile);
  10134. putc(*p >> 3 & 07, tracefile);
  10135. putc(*p & 07, tracefile);
  10136. }
  10137. break;
  10138. }
  10139. }
  10140. putc('"', tracefile);
  10141. }
  10142. void
  10143. trargs(char **ap)
  10144. {
  10145. if (debug != 1)
  10146. return;
  10147. while (*ap) {
  10148. trstring(*ap++);
  10149. if (*ap)
  10150. putc(' ', tracefile);
  10151. else
  10152. putc('\n', tracefile);
  10153. }
  10154. }
  10155. void
  10156. opentrace(void)
  10157. {
  10158. char s[100];
  10159. #ifdef O_APPEND
  10160. int flags;
  10161. #endif
  10162. if (debug != 1) {
  10163. if (tracefile)
  10164. fflush(tracefile);
  10165. /* leave open because libedit might be using it */
  10166. return;
  10167. }
  10168. scopy("./trace", s);
  10169. if (tracefile) {
  10170. if (!freopen(s, "a", tracefile)) {
  10171. fprintf(stderr, "Can't re-open %s\n", s);
  10172. debug = 0;
  10173. return;
  10174. }
  10175. } else {
  10176. if ((tracefile = fopen(s, "a")) == NULL) {
  10177. fprintf(stderr, "Can't open %s\n", s);
  10178. debug = 0;
  10179. return;
  10180. }
  10181. }
  10182. #ifdef O_APPEND
  10183. if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
  10184. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  10185. #endif
  10186. setlinebuf(tracefile);
  10187. fputs("\nTracing started.\n", tracefile);
  10188. }
  10189. #endif /* DEBUG */
  10190. /* $NetBSD: trap.c,v 1.28 2002/11/24 22:35:43 christos Exp $ */
  10191. /*
  10192. * Sigmode records the current value of the signal handlers for the various
  10193. * modes. A value of zero means that the current handler is not known.
  10194. * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  10195. */
  10196. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  10197. #define S_CATCH 2 /* signal is caught */
  10198. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  10199. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  10200. #define S_RESET 5 /* temporary - to reset a hard ignored sig */
  10201. /*
  10202. * The trap builtin.
  10203. */
  10204. int
  10205. trapcmd(int argc, char **argv)
  10206. {
  10207. char *action;
  10208. char **ap;
  10209. int signo;
  10210. nextopt(nullstr);
  10211. ap = argptr;
  10212. if (!*ap) {
  10213. for (signo = 0 ; signo < NSIG ; signo++) {
  10214. if (trap[signo] != NULL) {
  10215. const char *sn;
  10216. sn = u_signal_names(0, &signo, 0);
  10217. if (sn == NULL)
  10218. sn = "???";
  10219. out1fmt("trap -- %s %s\n",
  10220. single_quote(trap[signo]), sn);
  10221. }
  10222. }
  10223. return 0;
  10224. }
  10225. if (!ap[1])
  10226. action = NULL;
  10227. else
  10228. action = *ap++;
  10229. while (*ap) {
  10230. if ((signo = decode_signal(*ap, 0)) < 0)
  10231. error("%s: bad trap", *ap);
  10232. INTOFF;
  10233. if (action) {
  10234. if (action[0] == '-' && action[1] == '\0')
  10235. action = NULL;
  10236. else
  10237. action = savestr(action);
  10238. }
  10239. if (trap[signo])
  10240. ckfree(trap[signo]);
  10241. trap[signo] = action;
  10242. if (signo != 0)
  10243. setsignal(signo);
  10244. INTON;
  10245. ap++;
  10246. }
  10247. return 0;
  10248. }
  10249. /*
  10250. * Clear traps on a fork.
  10251. */
  10252. void
  10253. clear_traps(void)
  10254. {
  10255. char **tp;
  10256. for (tp = trap ; tp < &trap[NSIG] ; tp++) {
  10257. if (*tp && **tp) { /* trap not NULL or SIG_IGN */
  10258. INTOFF;
  10259. ckfree(*tp);
  10260. *tp = NULL;
  10261. if (tp != &trap[0])
  10262. setsignal(tp - trap);
  10263. INTON;
  10264. }
  10265. }
  10266. }
  10267. /*
  10268. * Set the signal handler for the specified signal. The routine figures
  10269. * out what it should be set to.
  10270. */
  10271. void
  10272. setsignal(int signo)
  10273. {
  10274. int action;
  10275. char *t, tsig;
  10276. struct sigaction act;
  10277. if ((t = trap[signo]) == NULL)
  10278. action = S_DFL;
  10279. else if (*t != '\0')
  10280. action = S_CATCH;
  10281. else
  10282. action = S_IGN;
  10283. if (rootshell && action == S_DFL) {
  10284. switch (signo) {
  10285. case SIGINT:
  10286. if (iflag || minusc || sflag == 0)
  10287. action = S_CATCH;
  10288. break;
  10289. case SIGQUIT:
  10290. #ifdef DEBUG
  10291. if (debug)
  10292. break;
  10293. #endif
  10294. /* FALLTHROUGH */
  10295. case SIGTERM:
  10296. if (iflag)
  10297. action = S_IGN;
  10298. break;
  10299. #if JOBS
  10300. case SIGTSTP:
  10301. case SIGTTOU:
  10302. if (mflag)
  10303. action = S_IGN;
  10304. break;
  10305. #endif
  10306. }
  10307. }
  10308. t = &sigmode[signo - 1];
  10309. tsig = *t;
  10310. if (tsig == 0) {
  10311. /*
  10312. * current setting unknown
  10313. */
  10314. if (sigaction(signo, 0, &act) == -1) {
  10315. /*
  10316. * Pretend it worked; maybe we should give a warning
  10317. * here, but other shells don't. We don't alter
  10318. * sigmode, so that we retry every time.
  10319. */
  10320. return;
  10321. }
  10322. if (act.sa_handler == SIG_IGN) {
  10323. if (mflag && (signo == SIGTSTP ||
  10324. signo == SIGTTIN || signo == SIGTTOU)) {
  10325. tsig = S_IGN; /* don't hard ignore these */
  10326. } else
  10327. tsig = S_HARD_IGN;
  10328. } else {
  10329. tsig = S_RESET; /* force to be set */
  10330. }
  10331. }
  10332. if (tsig == S_HARD_IGN || tsig == action)
  10333. return;
  10334. switch (action) {
  10335. case S_CATCH:
  10336. act.sa_handler = onsig;
  10337. break;
  10338. case S_IGN:
  10339. act.sa_handler = SIG_IGN;
  10340. break;
  10341. default:
  10342. act.sa_handler = SIG_DFL;
  10343. }
  10344. *t = action;
  10345. act.sa_flags = 0;
  10346. sigfillset(&act.sa_mask);
  10347. sigaction(signo, &act, 0);
  10348. }
  10349. /*
  10350. * Ignore a signal.
  10351. */
  10352. void
  10353. ignoresig(int signo)
  10354. {
  10355. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  10356. signal(signo, SIG_IGN);
  10357. }
  10358. sigmode[signo - 1] = S_HARD_IGN;
  10359. }
  10360. /*
  10361. * Signal handler.
  10362. */
  10363. void
  10364. onsig(int signo)
  10365. {
  10366. gotsig[signo - 1] = 1;
  10367. pendingsigs = signo;
  10368. if (exsig || (signo == SIGINT && !trap[SIGINT])) {
  10369. if (!suppressint)
  10370. onint();
  10371. intpending = 1;
  10372. }
  10373. }
  10374. /*
  10375. * Called to execute a trap. Perhaps we should avoid entering new trap
  10376. * handlers while we are executing a trap handler.
  10377. */
  10378. void
  10379. dotrap(void)
  10380. {
  10381. char *p;
  10382. char *q;
  10383. int savestatus;
  10384. savestatus = exitstatus;
  10385. q = gotsig;
  10386. while (pendingsigs = 0, barrier(), (p = memchr(q, 1, NSIG - 1))) {
  10387. *p = 0;
  10388. p = trap[p - q + 1];
  10389. if (!p)
  10390. continue;
  10391. evalstring(p, 0);
  10392. exitstatus = savestatus;
  10393. }
  10394. }
  10395. /*
  10396. * Controls whether the shell is interactive or not.
  10397. */
  10398. void
  10399. setinteractive(int on)
  10400. {
  10401. static int is_interactive;
  10402. if (++on == is_interactive)
  10403. return;
  10404. is_interactive = on;
  10405. setsignal(SIGINT);
  10406. setsignal(SIGQUIT);
  10407. setsignal(SIGTERM);
  10408. #ifndef BB_FEATURE_SH_EXTRA_QUIET
  10409. if(is_interactive > 1) {
  10410. /* Looks like they want an interactive shell */
  10411. static int do_banner;
  10412. if(!do_banner) {
  10413. out1fmt(
  10414. "\n\n" BB_BANNER " Built-in shell (ash)\n"
  10415. "Enter 'help' for a list of built-in commands.\n\n");
  10416. do_banner++;
  10417. }
  10418. }
  10419. #endif
  10420. }
  10421. #ifndef BB_FEATURE_SH_EXTRA_QUIET
  10422. /*** List the available builtins ***/
  10423. static int helpcmd(int argc, char **argv)
  10424. {
  10425. int col, i;
  10426. out1fmt("\nBuilt-in commands:\n-------------------\n");
  10427. for (col = 0, i = 0; i < NUMBUILTINS; i++) {
  10428. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  10429. builtincmd[i].name + 1);
  10430. if (col > 60) {
  10431. out1fmt("\n");
  10432. col = 0;
  10433. }
  10434. }
  10435. #ifdef BB_FEATURE_SH_STANDALONE_SHELL
  10436. {
  10437. extern const struct BB_applet applets[];
  10438. extern const size_t NUM_APPLETS;
  10439. for (i = 0; i < NUM_APPLETS; i++) {
  10440. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
  10441. if (col > 60) {
  10442. out1fmt("\n");
  10443. col = 0;
  10444. }
  10445. }
  10446. }
  10447. #endif
  10448. out1fmt("\n\n");
  10449. return EXIT_SUCCESS;
  10450. }
  10451. #endif /* BB_FEATURE_SH_EXTRA_QUIET */
  10452. /*
  10453. * Called to exit the shell.
  10454. */
  10455. void
  10456. exitshell(void)
  10457. {
  10458. struct jmploc loc;
  10459. char *p;
  10460. int status;
  10461. status = exitstatus;
  10462. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  10463. if (setjmp(loc.loc)) {
  10464. goto out;
  10465. }
  10466. handler = &loc;
  10467. if ((p = trap[0]) != NULL && *p != '\0') {
  10468. trap[0] = NULL;
  10469. evalstring(p, 0);
  10470. }
  10471. flushall();
  10472. #ifdef BB_FEATURE_COMMAND_SAVEHISTORY
  10473. if (iflag && rootshell) {
  10474. const char *hp = lookupvar("HISTFILE");
  10475. if(hp != NULL )
  10476. save_history ( hp );
  10477. }
  10478. #endif
  10479. out:
  10480. _exit(status);
  10481. /* NOTREACHED */
  10482. }
  10483. static int decode_signal(const char *string, int minsig)
  10484. {
  10485. int signo;
  10486. const char *name = u_signal_names(string, &signo, minsig);
  10487. return name ? signo : -1;
  10488. }
  10489. /* $NetBSD: var.c,v 1.32 2003/01/22 20:36:04 dsl Exp $ */
  10490. static struct var *vartab[VTABSIZE];
  10491. static int vpcmp(const void *, const void *);
  10492. static struct var **findvar(struct var **, const char *);
  10493. /*
  10494. * Initialize the varable symbol tables and import the environment
  10495. */
  10496. #ifdef BB_ASH_GETOPTS
  10497. /*
  10498. * Safe version of setvar, returns 1 on success 0 on failure.
  10499. */
  10500. int
  10501. setvarsafe(const char *name, const char *val, int flags)
  10502. {
  10503. int err;
  10504. volatile int saveint;
  10505. struct jmploc *volatile savehandler = handler;
  10506. struct jmploc jmploc;
  10507. SAVEINT(saveint);
  10508. if (setjmp(jmploc.loc))
  10509. err = 1;
  10510. else {
  10511. handler = &jmploc;
  10512. setvar(name, val, flags);
  10513. err = 0;
  10514. }
  10515. handler = savehandler;
  10516. RESTOREINT(saveint);
  10517. return err;
  10518. }
  10519. #endif
  10520. /*
  10521. * Set the value of a variable. The flags argument is ored with the
  10522. * flags of the variable. If val is NULL, the variable is unset.
  10523. */
  10524. static void
  10525. setvar(const char *name, const char *val, int flags)
  10526. {
  10527. char *p, *q;
  10528. size_t namelen;
  10529. char *nameeq;
  10530. size_t vallen;
  10531. q = endofname(name);
  10532. p = strchrnul(q, '=');
  10533. namelen = p - name;
  10534. if (!namelen || p != q)
  10535. error("%.*s: bad variable name", namelen, name);
  10536. vallen = 0;
  10537. if (val == NULL) {
  10538. flags |= VUNSET;
  10539. } else {
  10540. vallen = strlen(val);
  10541. }
  10542. INTOFF;
  10543. p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen);
  10544. *p++ = '\0';
  10545. if (vallen) {
  10546. p[-1] = '=';
  10547. p = mempcpy(p, val, vallen);
  10548. }
  10549. *p = '\0';
  10550. setvareq(nameeq, flags | VNOSAVE);
  10551. INTON;
  10552. }
  10553. /*
  10554. * Same as setvar except that the variable and value are passed in
  10555. * the first argument as name=value. Since the first argument will
  10556. * be actually stored in the table, it should not be a string that
  10557. * will go away.
  10558. * Called with interrupts off.
  10559. */
  10560. void
  10561. setvareq(char *s, int flags)
  10562. {
  10563. struct var *vp, **vpp;
  10564. vpp = hashvar(s);
  10565. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  10566. vp = *findvar(vpp, s);
  10567. if (vp) {
  10568. if (vp->flags & VREADONLY) {
  10569. if (flags & VNOSAVE)
  10570. free(s);
  10571. error("%.*s: is read only", strchrnul(s, '=') - s, s);
  10572. }
  10573. if (flags & VNOSET)
  10574. return;
  10575. if (vp->func && (flags & VNOFUNC) == 0)
  10576. (*vp->func)(strchrnul(s, '=') + 1);
  10577. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  10578. ckfree(vp->text);
  10579. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  10580. } else {
  10581. if (flags & VNOSET)
  10582. return;
  10583. /* not found */
  10584. vp = ckmalloc(sizeof (*vp));
  10585. vp->next = *vpp;
  10586. vp->func = NULL;
  10587. *vpp = vp;
  10588. }
  10589. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  10590. s = savestr(s);
  10591. vp->text = s;
  10592. vp->flags = flags;
  10593. }
  10594. /*
  10595. * Process a linked list of variable assignments.
  10596. */
  10597. static void
  10598. listsetvar(struct strlist *list_set_var, int flags)
  10599. {
  10600. struct strlist *lp = list_set_var;
  10601. if (!lp)
  10602. return;
  10603. INTOFF;
  10604. do {
  10605. setvareq(lp->text, flags);
  10606. } while ((lp = lp->next));
  10607. INTON;
  10608. }
  10609. /*
  10610. * Find the value of a variable. Returns NULL if not set.
  10611. */
  10612. static char *
  10613. lookupvar(const char *name)
  10614. {
  10615. struct var *v;
  10616. if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
  10617. return strchrnul(v->text, '=') + 1;
  10618. }
  10619. return NULL;
  10620. }
  10621. /*
  10622. * Search the environment of a builtin command.
  10623. */
  10624. static char *
  10625. bltinlookup(const char *name)
  10626. {
  10627. struct strlist *sp;
  10628. for (sp = cmdenviron ; sp ; sp = sp->next) {
  10629. if (varequal(sp->text, name))
  10630. return strchrnul(sp->text, '=') + 1;
  10631. }
  10632. return lookupvar(name);
  10633. }
  10634. /*
  10635. * Generate a list of variables satisfying the given conditions.
  10636. */
  10637. static char **
  10638. listvars(int on, int off, char ***end)
  10639. {
  10640. struct var **vpp;
  10641. struct var *vp;
  10642. char **ep;
  10643. int mask;
  10644. STARTSTACKSTR(ep);
  10645. vpp = vartab;
  10646. mask = on | off;
  10647. do {
  10648. for (vp = *vpp ; vp ; vp = vp->next)
  10649. if ((vp->flags & mask) == on) {
  10650. if (ep == stackstrend())
  10651. ep = growstackstr();
  10652. *ep++ = (char *) vp->text;
  10653. }
  10654. } while (++vpp < vartab + VTABSIZE);
  10655. if (ep == stackstrend())
  10656. ep = growstackstr();
  10657. if (end)
  10658. *end = ep;
  10659. *ep++ = NULL;
  10660. return grabstackstr(ep);
  10661. }
  10662. /*
  10663. * POSIX requires that 'set' (but not export or readonly) output the
  10664. * variables in lexicographic order - by the locale's collating order (sigh).
  10665. * Maybe we could keep them in an ordered balanced binary tree
  10666. * instead of hashed lists.
  10667. * For now just roll 'em through qsort for printing...
  10668. */
  10669. static int
  10670. showvars(const char *sep_prefix, int on, int off)
  10671. {
  10672. const char *sep;
  10673. char **ep, **epend;
  10674. ep = listvars(on, off, &epend);
  10675. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10676. sep = *sep_prefix ? spcstr : sep_prefix;
  10677. for (; ep < epend; ep++) {
  10678. const char *p;
  10679. const char *q;
  10680. p = strchrnul(*ep, '=');
  10681. q = nullstr;
  10682. if (*p)
  10683. q = single_quote(++p);
  10684. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10685. }
  10686. return 0;
  10687. }
  10688. /*
  10689. * The export and readonly commands.
  10690. */
  10691. static int
  10692. exportcmd(int argc, char **argv)
  10693. {
  10694. struct var *vp;
  10695. char *name;
  10696. const char *p;
  10697. char **aptr;
  10698. int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
  10699. int notp;
  10700. notp = nextopt("p") - 'p';
  10701. if (notp && ((name = *(aptr = argptr)))) {
  10702. do {
  10703. if ((p = strchr(name, '=')) != NULL) {
  10704. p++;
  10705. } else {
  10706. if ((vp = *findvar(hashvar(name), name))) {
  10707. vp->flags |= flag;
  10708. continue;
  10709. }
  10710. }
  10711. setvar(name, p, flag);
  10712. } while ((name = *++aptr) != NULL);
  10713. } else {
  10714. showvars(argv[0], flag, 0);
  10715. }
  10716. return 0;
  10717. }
  10718. /*
  10719. * Make a variable a local variable. When a variable is made local, it's
  10720. * value and flags are saved in a localvar structure. The saved values
  10721. * will be restored when the shell function returns. We handle the name
  10722. * "-" as a special case.
  10723. */
  10724. static inline void
  10725. mklocal(char *name)
  10726. {
  10727. struct localvar *lvp;
  10728. struct var **vpp;
  10729. struct var *vp;
  10730. INTOFF;
  10731. lvp = ckmalloc(sizeof (struct localvar));
  10732. if (name[0] == '-' && name[1] == '\0') {
  10733. char *p;
  10734. p = ckmalloc(sizeof(optlist));
  10735. lvp->text = memcpy(p, optlist, sizeof(optlist));
  10736. vp = NULL;
  10737. } else {
  10738. char *eq;
  10739. vpp = hashvar(name);
  10740. vp = *findvar(vpp, name);
  10741. eq = strchr(name, '=');
  10742. if (vp == NULL) {
  10743. if (eq)
  10744. setvareq(name, VSTRFIXED);
  10745. else
  10746. setvar(name, NULL, VSTRFIXED);
  10747. vp = *vpp; /* the new variable */
  10748. lvp->flags = VUNSET;
  10749. } else {
  10750. lvp->text = vp->text;
  10751. lvp->flags = vp->flags;
  10752. vp->flags |= VSTRFIXED|VTEXTFIXED;
  10753. if (eq)
  10754. setvareq(name, 0);
  10755. }
  10756. }
  10757. lvp->vp = vp;
  10758. lvp->next = localvars;
  10759. localvars = lvp;
  10760. INTON;
  10761. }
  10762. /*
  10763. * The "local" command.
  10764. */
  10765. static int
  10766. localcmd(int argc, char **argv)
  10767. {
  10768. char *name;
  10769. argv = argptr;
  10770. while ((name = *argv++) != NULL) {
  10771. mklocal(name);
  10772. }
  10773. return 0;
  10774. }
  10775. /*
  10776. * Called after a function returns.
  10777. * Interrupts must be off.
  10778. */
  10779. static void
  10780. poplocalvars(void)
  10781. {
  10782. struct localvar *lvp;
  10783. struct var *vp;
  10784. while ((lvp = localvars) != NULL) {
  10785. localvars = lvp->next;
  10786. vp = lvp->vp;
  10787. TRACE(("poplocalvar %s", vp ? vp->text : "-"));
  10788. if (vp == NULL) { /* $- saved */
  10789. memcpy(optlist, lvp->text, sizeof(optlist));
  10790. ckfree(lvp->text);
  10791. optschanged();
  10792. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  10793. unsetvar(vp->text);
  10794. } else {
  10795. if (vp->func)
  10796. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  10797. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  10798. ckfree(vp->text);
  10799. vp->flags = lvp->flags;
  10800. vp->text = lvp->text;
  10801. }
  10802. ckfree(lvp);
  10803. }
  10804. }
  10805. /*
  10806. * The unset builtin command. We unset the function before we unset the
  10807. * variable to allow a function to be unset when there is a readonly variable
  10808. * with the same name.
  10809. */
  10810. int
  10811. unsetcmd(int argc, char **argv)
  10812. {
  10813. char **ap;
  10814. int i;
  10815. int flag = 0;
  10816. int ret = 0;
  10817. while ((i = nextopt("vf")) != '\0') {
  10818. flag = i;
  10819. }
  10820. for (ap = argptr; *ap ; ap++) {
  10821. if (flag != 'f') {
  10822. i = unsetvar(*ap);
  10823. ret |= i;
  10824. if (!(i & 2))
  10825. continue;
  10826. }
  10827. if (flag != 'v')
  10828. unsetfunc(*ap);
  10829. }
  10830. return ret & 1;
  10831. }
  10832. /*
  10833. * Unset the specified variable.
  10834. */
  10835. int
  10836. unsetvar(const char *s)
  10837. {
  10838. struct var **vpp;
  10839. struct var *vp;
  10840. int retval;
  10841. vpp = findvar(hashvar(s), s);
  10842. vp = *vpp;
  10843. retval = 2;
  10844. if (vp) {
  10845. int flags = vp->flags;
  10846. retval = 1;
  10847. if (flags & VREADONLY)
  10848. goto out;
  10849. if (flags & VUNSET)
  10850. goto ok;
  10851. if ((flags & VSTRFIXED) == 0) {
  10852. INTOFF;
  10853. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  10854. ckfree(vp->text);
  10855. *vpp = vp->next;
  10856. ckfree(vp);
  10857. INTON;
  10858. } else {
  10859. setvar(s, 0, 0);
  10860. vp->flags &= ~VEXPORT;
  10861. }
  10862. ok:
  10863. retval = 0;
  10864. }
  10865. out:
  10866. return retval;
  10867. }
  10868. /*
  10869. * Find the appropriate entry in the hash table from the name.
  10870. */
  10871. static struct var **
  10872. hashvar(const char *p)
  10873. {
  10874. unsigned int hashval;
  10875. hashval = ((unsigned char) *p) << 4;
  10876. while (*p && *p != '=')
  10877. hashval += (unsigned char) *p++;
  10878. return &vartab[hashval % VTABSIZE];
  10879. }
  10880. /*
  10881. * Compares two strings up to the first = or '\0'. The first
  10882. * string must be terminated by '='; the second may be terminated by
  10883. * either '=' or '\0'.
  10884. */
  10885. int
  10886. varcmp(const char *p, const char *q)
  10887. {
  10888. int c, d;
  10889. while ((c = *p) == (d = *q)) {
  10890. if (!c || c == '=')
  10891. goto out;
  10892. p++;
  10893. q++;
  10894. }
  10895. if (c == '=')
  10896. c = 0;
  10897. if (d == '=')
  10898. d = 0;
  10899. out:
  10900. return c - d;
  10901. }
  10902. static int
  10903. vpcmp(const void *a, const void *b)
  10904. {
  10905. return varcmp(*(const char **)a, *(const char **)b);
  10906. }
  10907. static struct var **
  10908. findvar(struct var **vpp, const char *name)
  10909. {
  10910. for (; *vpp; vpp = &(*vpp)->next) {
  10911. if (varequal((*vpp)->text, name)) {
  10912. break;
  10913. }
  10914. }
  10915. return vpp;
  10916. }
  10917. /* $NetBSD: setmode.c,v 1.29 2003/01/15 23:58:03 kleink Exp $ */
  10918. #include <sys/times.h>
  10919. static const unsigned char timescmd_str[] = {
  10920. ' ', offsetof(struct tms, tms_utime),
  10921. '\n', offsetof(struct tms, tms_stime),
  10922. ' ', offsetof(struct tms, tms_cutime),
  10923. '\n', offsetof(struct tms, tms_cstime),
  10924. 0
  10925. };
  10926. static int timescmd(int ac, char **av)
  10927. {
  10928. long int clk_tck, s, t;
  10929. const unsigned char *p;
  10930. struct tms buf;
  10931. clk_tck = sysconf(_SC_CLK_TCK);
  10932. times(&buf);
  10933. p = timescmd_str;
  10934. do {
  10935. t = *(clock_t *)(((char *) &buf) + p[1]);
  10936. s = t / clk_tck;
  10937. out1fmt("%ldm%ld.%.3lds%c",
  10938. s/60, s%60,
  10939. ((t - s * clk_tck) * 1000) / clk_tck,
  10940. p[0]);
  10941. } while (*(p += 2));
  10942. return 0;
  10943. }
  10944. #ifdef BB_ASH_MATH_SUPPORT
  10945. static int
  10946. dash_arith(const char *s)
  10947. {
  10948. long result;
  10949. int errcode = 0;
  10950. INTOFF;
  10951. result = arith(s, &errcode);
  10952. if (errcode < 0) {
  10953. if (errcode == -3)
  10954. error("exponent less than 0");
  10955. else if (errcode == -2)
  10956. error("divide by zero");
  10957. else if (errcode == -5)
  10958. error("expression recursion loop detected");
  10959. else
  10960. synerror(s);
  10961. }
  10962. INTON;
  10963. return (result);
  10964. }
  10965. /*
  10966. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  10967. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  10968. *
  10969. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  10970. */
  10971. static int
  10972. letcmd(int argc, char **argv)
  10973. {
  10974. char **ap;
  10975. long i;
  10976. ap = argv + 1;
  10977. if(!*ap)
  10978. error("expression expected");
  10979. for (ap = argv + 1; *ap; ap++) {
  10980. i = dash_arith(*ap);
  10981. }
  10982. return (!i);
  10983. }
  10984. #endif /* BB_ASH_MATH_SUPPORT */
  10985. /* $NetBSD: miscbltin.c,v 1.31 2002/11/24 22:35:41 christos Exp $ */
  10986. /*
  10987. * Miscelaneous builtins.
  10988. */
  10989. #undef rflag
  10990. #ifdef __GLIBC__
  10991. #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  10992. typedef enum __rlimit_resource rlim_t;
  10993. #endif
  10994. #endif
  10995. /*
  10996. * The read builtin. The -e option causes backslashes to escape the
  10997. * following character.
  10998. *
  10999. * This uses unbuffered input, which may be avoidable in some cases.
  11000. */
  11001. static int
  11002. readcmd(int argc, char **argv)
  11003. {
  11004. char **ap;
  11005. int backslash;
  11006. char c;
  11007. int rflag;
  11008. char *prompt;
  11009. const char *ifs;
  11010. char *p;
  11011. int startword;
  11012. int status;
  11013. int i;
  11014. rflag = 0;
  11015. prompt = NULL;
  11016. while ((i = nextopt("p:r")) != '\0') {
  11017. if (i == 'p')
  11018. prompt = optionarg;
  11019. else
  11020. rflag = 1;
  11021. }
  11022. if (prompt && isatty(0)) {
  11023. out2str(prompt);
  11024. }
  11025. if (*(ap = argptr) == NULL)
  11026. error("arg count");
  11027. if ((ifs = bltinlookup("IFS")) == NULL)
  11028. ifs = defifs;
  11029. status = 0;
  11030. startword = 1;
  11031. backslash = 0;
  11032. STARTSTACKSTR(p);
  11033. for (;;) {
  11034. if (read(0, &c, 1) != 1) {
  11035. status = 1;
  11036. break;
  11037. }
  11038. if (c == '\0')
  11039. continue;
  11040. if (backslash) {
  11041. backslash = 0;
  11042. if (c != '\n')
  11043. goto put;
  11044. continue;
  11045. }
  11046. if (!rflag && c == '\\') {
  11047. backslash++;
  11048. continue;
  11049. }
  11050. if (c == '\n')
  11051. break;
  11052. if (startword && *ifs == ' ' && strchr(ifs, c)) {
  11053. continue;
  11054. }
  11055. startword = 0;
  11056. if (ap[1] != NULL && strchr(ifs, c) != NULL) {
  11057. STACKSTRNUL(p);
  11058. setvar(*ap, stackblock(), 0);
  11059. ap++;
  11060. startword = 1;
  11061. STARTSTACKSTR(p);
  11062. } else {
  11063. put:
  11064. STPUTC(c, p);
  11065. }
  11066. }
  11067. STACKSTRNUL(p);
  11068. /* Remove trailing blanks */
  11069. while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
  11070. *p = '\0';
  11071. setvar(*ap, stackblock(), 0);
  11072. while (*++ap != NULL)
  11073. setvar(*ap, nullstr, 0);
  11074. return status;
  11075. }
  11076. static int umaskcmd(int argc, char **argv)
  11077. {
  11078. static const char permuser[3] = "ugo";
  11079. static const char permmode[3] = "rwx";
  11080. static const short int permmask[] = {
  11081. S_IRUSR, S_IWUSR, S_IXUSR,
  11082. S_IRGRP, S_IWGRP, S_IXGRP,
  11083. S_IROTH, S_IWOTH, S_IXOTH
  11084. };
  11085. char *ap;
  11086. mode_t mask;
  11087. int i;
  11088. int symbolic_mode = 0;
  11089. while (nextopt("S") != '\0') {
  11090. symbolic_mode = 1;
  11091. }
  11092. INTOFF;
  11093. mask = umask(0);
  11094. umask(mask);
  11095. INTON;
  11096. if ((ap = *argptr) == NULL) {
  11097. if (symbolic_mode) {
  11098. char buf[18];
  11099. char *p = buf;
  11100. for (i = 0; i < 3; i++) {
  11101. int j;
  11102. *p++ = permuser[i];
  11103. *p++ = '=';
  11104. for (j = 0; j < 3; j++) {
  11105. if ((mask & permmask[3 * i + j]) == 0) {
  11106. *p++ = permmode[j];
  11107. }
  11108. }
  11109. *p++ = ',';
  11110. }
  11111. *--p = 0;
  11112. puts(buf);
  11113. } else {
  11114. out1fmt("%.4o\n", mask);
  11115. }
  11116. } else {
  11117. if (is_digit((unsigned char) *ap)) {
  11118. mask = 0;
  11119. do {
  11120. if (*ap >= '8' || *ap < '0')
  11121. error(illnum, argv[1]);
  11122. mask = (mask << 3) + (*ap - '0');
  11123. } while (*++ap != '\0');
  11124. umask(mask);
  11125. } else {
  11126. mask = ~mask & 0777;
  11127. if (!parse_mode(ap, &mask)) {
  11128. error("Illegal mode: %s", ap);
  11129. }
  11130. umask(~mask & 0777);
  11131. }
  11132. }
  11133. return 0;
  11134. }
  11135. /*
  11136. * ulimit builtin
  11137. *
  11138. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11139. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11140. * ash by J.T. Conklin.
  11141. *
  11142. * Public domain.
  11143. */
  11144. struct limits {
  11145. const char *name;
  11146. int cmd;
  11147. int factor; /* multiply by to get rlim_{cur,max} values */
  11148. char option;
  11149. };
  11150. static const struct limits limits[] = {
  11151. #ifdef RLIMIT_CPU
  11152. { "time(seconds)", RLIMIT_CPU, 1, 't' },
  11153. #endif
  11154. #ifdef RLIMIT_FSIZE
  11155. { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
  11156. #endif
  11157. #ifdef RLIMIT_DATA
  11158. { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
  11159. #endif
  11160. #ifdef RLIMIT_STACK
  11161. { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
  11162. #endif
  11163. #ifdef RLIMIT_CORE
  11164. { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
  11165. #endif
  11166. #ifdef RLIMIT_RSS
  11167. { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
  11168. #endif
  11169. #ifdef RLIMIT_MEMLOCK
  11170. { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
  11171. #endif
  11172. #ifdef RLIMIT_NPROC
  11173. { "process(processes)", RLIMIT_NPROC, 1, 'p' },
  11174. #endif
  11175. #ifdef RLIMIT_NOFILE
  11176. { "nofiles(descriptors)", RLIMIT_NOFILE, 1, 'n' },
  11177. #endif
  11178. #ifdef RLIMIT_VMEM
  11179. { "vmemory(kbytes)", RLIMIT_VMEM, 1024, 'v' },
  11180. #endif
  11181. #ifdef RLIMIT_SWAP
  11182. { "swap(kbytes)", RLIMIT_SWAP, 1024, 'w' },
  11183. #endif
  11184. { (char *) 0, 0, 0, '\0' }
  11185. };
  11186. int
  11187. ulimitcmd(int argc, char **argv)
  11188. {
  11189. int c;
  11190. rlim_t val = 0;
  11191. enum { SOFT = 0x1, HARD = 0x2 }
  11192. how = SOFT | HARD;
  11193. const struct limits *l;
  11194. int set, all = 0;
  11195. int optc, what;
  11196. struct rlimit limit;
  11197. what = 'f';
  11198. while ((optc = nextopt("HSatfdsmcnpl")) != '\0')
  11199. switch (optc) {
  11200. case 'H':
  11201. how = HARD;
  11202. break;
  11203. case 'S':
  11204. how = SOFT;
  11205. break;
  11206. case 'a':
  11207. all = 1;
  11208. break;
  11209. default:
  11210. what = optc;
  11211. }
  11212. for (l = limits; l->name && l->option != what; l++)
  11213. ;
  11214. if (!l->name)
  11215. error("internal error (%c)", what);
  11216. set = *argptr ? 1 : 0;
  11217. if (set) {
  11218. char *p = *argptr;
  11219. if (all || argptr[1])
  11220. error("too many arguments");
  11221. if (strncmp(p, "unlimited\n", 9) == 0)
  11222. val = RLIM_INFINITY;
  11223. else {
  11224. val = (rlim_t) 0;
  11225. while ((c = *p++) >= '0' && c <= '9')
  11226. {
  11227. val = (val * 10) + (long)(c - '0');
  11228. if (val < (rlim_t) 0)
  11229. break;
  11230. }
  11231. if (c)
  11232. error("bad number");
  11233. val *= l->factor;
  11234. }
  11235. }
  11236. if (all) {
  11237. for (l = limits; l->name; l++) {
  11238. getrlimit(l->cmd, &limit);
  11239. if (how & SOFT)
  11240. val = limit.rlim_cur;
  11241. else if (how & HARD)
  11242. val = limit.rlim_max;
  11243. out1fmt("%-20s ", l->name);
  11244. if (val == RLIM_INFINITY)
  11245. out1fmt("unlimited\n");
  11246. else
  11247. {
  11248. val /= l->factor;
  11249. out1fmt("%lld\n", (long long) val);
  11250. }
  11251. }
  11252. return 0;
  11253. }
  11254. getrlimit(l->cmd, &limit);
  11255. if (set) {
  11256. if (how & HARD)
  11257. limit.rlim_max = val;
  11258. if (how & SOFT)
  11259. limit.rlim_cur = val;
  11260. if (setrlimit(l->cmd, &limit) < 0)
  11261. error("error setting limit (%m)");
  11262. } else {
  11263. if (how & SOFT)
  11264. val = limit.rlim_cur;
  11265. else if (how & HARD)
  11266. val = limit.rlim_max;
  11267. if (val == RLIM_INFINITY)
  11268. out1fmt("unlimited\n");
  11269. else
  11270. {
  11271. val /= l->factor;
  11272. out1fmt("%lld\n", (long long) val);
  11273. }
  11274. }
  11275. return 0;
  11276. }
  11277. #ifdef BB_ASH_MATH_SUPPORT
  11278. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  11279. Permission is hereby granted, free of charge, to any person obtaining
  11280. a copy of this software and associated documentation files (the
  11281. "Software"), to deal in the Software without restriction, including
  11282. without limitation the rights to use, copy, modify, merge, publish,
  11283. distribute, sublicense, and/or sell copies of the Software, and to
  11284. permit persons to whom the Software is furnished to do so, subject to
  11285. the following conditions:
  11286. The above copyright notice and this permission notice shall be
  11287. included in all copies or substantial portions of the Software.
  11288. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  11289. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11290. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  11291. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  11292. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  11293. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  11294. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11295. */
  11296. /* This is my infix parser/evaluator. It is optimized for size, intended
  11297. * as a replacement for yacc-based parsers. However, it may well be faster
  11298. * than a comparable parser writen in yacc. The supported operators are
  11299. * listed in #defines below. Parens, order of operations, and error handling
  11300. * are supported. This code is threadsafe. The exact expression format should
  11301. * be that which POSIX specifies for shells. */
  11302. /* The code uses a simple two-stack algorithm. See
  11303. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  11304. * for a detailed explaination of the infix-to-postfix algorithm on which
  11305. * this is based (this code differs in that it applies operators immediately
  11306. * to the stack instead of adding them to a queue to end up with an
  11307. * expression). */
  11308. /* To use the routine, call it with an expression string and error return
  11309. * pointer */
  11310. /*
  11311. * Aug 24, 2001 Manuel Novoa III
  11312. *
  11313. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  11314. *
  11315. * 1) In arith_apply():
  11316. * a) Cached values of *numptr and &(numptr[-1]).
  11317. * b) Removed redundant test for zero denominator.
  11318. *
  11319. * 2) In arith():
  11320. * a) Eliminated redundant code for processing operator tokens by moving
  11321. * to a table-based implementation. Also folded handling of parens
  11322. * into the table.
  11323. * b) Combined all 3 loops which called arith_apply to reduce generated
  11324. * code size at the cost of speed.
  11325. *
  11326. * 3) The following expressions were treated as valid by the original code:
  11327. * 1() , 0! , 1 ( *3 ) .
  11328. * These bugs have been fixed by internally enclosing the expression in
  11329. * parens and then checking that all binary ops and right parens are
  11330. * preceded by a valid expression (NUM_TOKEN).
  11331. *
  11332. * Note: It may be desireable to replace Aaron's test for whitespace with
  11333. * ctype's isspace() if it is used by another busybox applet or if additional
  11334. * whitespace chars should be considered. Look below the "#include"s for a
  11335. * precompiler test.
  11336. */
  11337. /*
  11338. * Aug 26, 2001 Manuel Novoa III
  11339. *
  11340. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  11341. *
  11342. * Merge in Aaron's comments previously posted to the busybox list,
  11343. * modified slightly to take account of my changes to the code.
  11344. *
  11345. */
  11346. /*
  11347. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11348. *
  11349. * - allow access to variable,
  11350. * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
  11351. * - realize assign syntax (VAR=expr, +=, *= etc)
  11352. * - realize exponentiation (** operator)
  11353. * - realize comma separated - expr, expr
  11354. * - realise ++expr --expr expr++ expr--
  11355. * - realise expr ? expr : expr (but, second expr calculate always)
  11356. * - allow hexdecimal and octal numbers
  11357. * - was restored loses XOR operator
  11358. * - remove one goto label, added three ;-)
  11359. * - protect $((num num)) as true zero expr (Manuel`s error)
  11360. * - always use special isspace(), see comment from bash ;-)
  11361. */
  11362. #define arith_isspace(arithval) \
  11363. (arithval == ' ' || arithval == '\n' || arithval == '\t')
  11364. typedef unsigned char operator;
  11365. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  11366. * precedence, and 3 high bits are an ID unique accross operators of that
  11367. * precedence. The ID portion is so that multiple operators can have the
  11368. * same precedence, ensuring that the leftmost one is evaluated first.
  11369. * Consider * and /. */
  11370. #define tok_decl(prec,id) (((id)<<5)|(prec))
  11371. #define PREC(op) ((op) & 0x1F)
  11372. #define TOK_LPAREN tok_decl(0,0)
  11373. #define TOK_COMMA tok_decl(1,0)
  11374. #define TOK_ASSIGN tok_decl(2,0)
  11375. #define TOK_AND_ASSIGN tok_decl(2,1)
  11376. #define TOK_OR_ASSIGN tok_decl(2,2)
  11377. #define TOK_XOR_ASSIGN tok_decl(2,3)
  11378. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  11379. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  11380. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  11381. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  11382. #define TOK_MUL_ASSIGN tok_decl(3,0)
  11383. #define TOK_DIV_ASSIGN tok_decl(3,1)
  11384. #define TOK_REM_ASSIGN tok_decl(3,2)
  11385. /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
  11386. #define convert_prec_is_assing(prec) do { if(prec == 3) prec = 2; } while(0)
  11387. /* conditional is right associativity too */
  11388. #define TOK_CONDITIONAL tok_decl(4,0)
  11389. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  11390. #define TOK_OR tok_decl(5,0)
  11391. #define TOK_AND tok_decl(6,0)
  11392. #define TOK_BOR tok_decl(7,0)
  11393. #define TOK_BXOR tok_decl(8,0)
  11394. #define TOK_BAND tok_decl(9,0)
  11395. #define TOK_EQ tok_decl(10,0)
  11396. #define TOK_NE tok_decl(10,1)
  11397. #define TOK_LT tok_decl(11,0)
  11398. #define TOK_GT tok_decl(11,1)
  11399. #define TOK_GE tok_decl(11,2)
  11400. #define TOK_LE tok_decl(11,3)
  11401. #define TOK_LSHIFT tok_decl(12,0)
  11402. #define TOK_RSHIFT tok_decl(12,1)
  11403. #define TOK_ADD tok_decl(13,0)
  11404. #define TOK_SUB tok_decl(13,1)
  11405. #define TOK_MUL tok_decl(14,0)
  11406. #define TOK_DIV tok_decl(14,1)
  11407. #define TOK_REM tok_decl(14,2)
  11408. /* exponent is right associativity */
  11409. #define TOK_EXPONENT tok_decl(15,1)
  11410. /* For now unary operators. */
  11411. #define UNARYPREC 16
  11412. #define TOK_BNOT tok_decl(UNARYPREC,0)
  11413. #define TOK_NOT tok_decl(UNARYPREC,1)
  11414. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  11415. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  11416. #define PREC_PRE (UNARYPREC+2)
  11417. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  11418. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  11419. #define PREC_POST (UNARYPREC+3)
  11420. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  11421. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  11422. #define SPEC_PREC (UNARYPREC+4)
  11423. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  11424. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  11425. #define NUMPTR (*numstackptr)
  11426. static inline int tok_have_assign(operator op)
  11427. {
  11428. operator prec = PREC(op);
  11429. convert_prec_is_assing(prec);
  11430. return (prec == PREC(TOK_ASSIGN) ||
  11431. prec == PREC_PRE || prec == PREC_POST);
  11432. }
  11433. static inline int is_right_associativity(operator prec)
  11434. {
  11435. return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) ||
  11436. prec == PREC(TOK_CONDITIONAL));
  11437. }
  11438. typedef struct ARITCH_VAR_NUM {
  11439. long val;
  11440. long contidional_second_val;
  11441. char contidional_second_val_initialized;
  11442. char *var; /* if NULL then is regular number,
  11443. else is varable name */
  11444. } v_n_t;
  11445. typedef struct CHK_VAR_RECURSIVE_LOOPED {
  11446. const char *var;
  11447. struct CHK_VAR_RECURSIVE_LOOPED *next;
  11448. } chk_var_recursive_looped_t;
  11449. static chk_var_recursive_looped_t *prev_chk_var_recursive;
  11450. static int arith_lookup_val(v_n_t *t)
  11451. {
  11452. if(t->var) {
  11453. const char * p = lookupvar(t->var);
  11454. if(p) {
  11455. int errcode;
  11456. /* recursive try as expression */
  11457. chk_var_recursive_looped_t *cur;
  11458. chk_var_recursive_looped_t cur_save;
  11459. for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
  11460. if(strcmp(cur->var, t->var) == 0) {
  11461. /* expression recursion loop detected */
  11462. return -5;
  11463. }
  11464. }
  11465. /* save current lookuped var name */
  11466. cur = prev_chk_var_recursive;
  11467. cur_save.var = t->var;
  11468. cur_save.next = cur;
  11469. prev_chk_var_recursive = &cur_save;
  11470. t->val = arith (p, &errcode);
  11471. /* restore previous ptr after recursiving */
  11472. prev_chk_var_recursive = cur;
  11473. return errcode;
  11474. } else {
  11475. /* allow undefined var as 0 */
  11476. t->val = 0;
  11477. }
  11478. }
  11479. return 0;
  11480. }
  11481. /* "applying" a token means performing it on the top elements on the integer
  11482. * stack. For a unary operator it will only change the top element, but a
  11483. * binary operator will pop two arguments and push a result */
  11484. static inline int
  11485. arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
  11486. {
  11487. long numptr_val;
  11488. v_n_t *numptr_m1;
  11489. long rez;
  11490. int ret_arith_lookup_val;
  11491. if (NUMPTR == numstack) goto err; /* There is no operator that can work
  11492. without arguments */
  11493. numptr_m1 = NUMPTR - 1;
  11494. /* check operand is var with noninteger value */
  11495. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11496. if(ret_arith_lookup_val)
  11497. return ret_arith_lookup_val;
  11498. rez = numptr_m1->val;
  11499. if (op == TOK_UMINUS)
  11500. rez *= -1;
  11501. else if (op == TOK_NOT)
  11502. rez = !rez;
  11503. else if (op == TOK_BNOT)
  11504. rez = ~rez;
  11505. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  11506. rez++;
  11507. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  11508. rez--;
  11509. else if (op != TOK_UPLUS) {
  11510. /* Binary operators */
  11511. /* check and binary operators need two arguments */
  11512. if (numptr_m1 == numstack) goto err;
  11513. /* ... and they pop one */
  11514. --NUMPTR;
  11515. numptr_val = rez;
  11516. if (op == TOK_CONDITIONAL) {
  11517. if(! numptr_m1->contidional_second_val_initialized) {
  11518. /* protect $((expr1 ? expr2)) without ": expr" */
  11519. goto err;
  11520. }
  11521. rez = numptr_m1->contidional_second_val;
  11522. } else if(numptr_m1->contidional_second_val_initialized) {
  11523. /* protect $((expr1 : expr2)) without "expr ? " */
  11524. goto err;
  11525. }
  11526. numptr_m1 = NUMPTR - 1;
  11527. if(op != TOK_ASSIGN) {
  11528. /* check operand is var with noninteger value for not '=' */
  11529. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11530. if(ret_arith_lookup_val)
  11531. return ret_arith_lookup_val;
  11532. }
  11533. if (op == TOK_CONDITIONAL) {
  11534. numptr_m1->contidional_second_val = rez;
  11535. }
  11536. rez = numptr_m1->val;
  11537. if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  11538. rez |= numptr_val;
  11539. else if (op == TOK_OR)
  11540. rez = numptr_val || rez;
  11541. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  11542. rez &= numptr_val;
  11543. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  11544. rez ^= numptr_val;
  11545. else if (op == TOK_AND)
  11546. rez = rez && numptr_val;
  11547. else if (op == TOK_EQ)
  11548. rez = (rez == numptr_val);
  11549. else if (op == TOK_NE)
  11550. rez = (rez != numptr_val);
  11551. else if (op == TOK_GE)
  11552. rez = (rez >= numptr_val);
  11553. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  11554. rez >>= numptr_val;
  11555. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  11556. rez <<= numptr_val;
  11557. else if (op == TOK_GT)
  11558. rez = (rez > numptr_val);
  11559. else if (op == TOK_LT)
  11560. rez = (rez < numptr_val);
  11561. else if (op == TOK_LE)
  11562. rez = (rez <= numptr_val);
  11563. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  11564. rez *= numptr_val;
  11565. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  11566. rez += numptr_val;
  11567. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  11568. rez -= numptr_val;
  11569. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  11570. rez = numptr_val;
  11571. else if (op == TOK_CONDITIONAL_SEP) {
  11572. if (numptr_m1 == numstack) {
  11573. /* protect $((expr : expr)) without "expr ? " */
  11574. goto err;
  11575. }
  11576. numptr_m1->contidional_second_val_initialized = op;
  11577. numptr_m1->contidional_second_val = numptr_val;
  11578. }
  11579. else if (op == TOK_CONDITIONAL) {
  11580. rez = rez ?
  11581. numptr_val : numptr_m1->contidional_second_val;
  11582. }
  11583. else if(op == TOK_EXPONENT) {
  11584. if(numptr_val < 0)
  11585. return -3; /* exponent less than 0 */
  11586. else {
  11587. long c = 1;
  11588. if(numptr_val)
  11589. while(numptr_val--)
  11590. c *= rez;
  11591. rez = c;
  11592. }
  11593. }
  11594. else if(numptr_val==0) /* zero divisor check */
  11595. return -2;
  11596. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  11597. rez /= numptr_val;
  11598. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  11599. rez %= numptr_val;
  11600. }
  11601. if(tok_have_assign(op)) {
  11602. char buf[32];
  11603. if(numptr_m1->var == NULL) {
  11604. /* Hmm, 1=2 ? */
  11605. goto err;
  11606. }
  11607. /* save to shell variable */
  11608. sprintf(buf, "%ld", rez);
  11609. setvar(numptr_m1->var, buf, 0);
  11610. /* after saving, make previous value for v++ or v-- */
  11611. if(op == TOK_POST_INC)
  11612. rez--;
  11613. else if(op == TOK_POST_DEC)
  11614. rez++;
  11615. }
  11616. numptr_m1->val = rez;
  11617. /* protect geting var value, is number now */
  11618. numptr_m1->var = NULL;
  11619. return 0;
  11620. err: return(-1);
  11621. }
  11622. /* longest must first */
  11623. static const char op_tokens[] = {
  11624. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  11625. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  11626. '<','<', 0, TOK_LSHIFT,
  11627. '>','>', 0, TOK_RSHIFT,
  11628. '|','|', 0, TOK_OR,
  11629. '&','&', 0, TOK_AND,
  11630. '!','=', 0, TOK_NE,
  11631. '<','=', 0, TOK_LE,
  11632. '>','=', 0, TOK_GE,
  11633. '=','=', 0, TOK_EQ,
  11634. '|','=', 0, TOK_OR_ASSIGN,
  11635. '&','=', 0, TOK_AND_ASSIGN,
  11636. '*','=', 0, TOK_MUL_ASSIGN,
  11637. '/','=', 0, TOK_DIV_ASSIGN,
  11638. '%','=', 0, TOK_REM_ASSIGN,
  11639. '+','=', 0, TOK_PLUS_ASSIGN,
  11640. '-','=', 0, TOK_MINUS_ASSIGN,
  11641. '-','-', 0, TOK_POST_DEC,
  11642. '^','=', 0, TOK_XOR_ASSIGN,
  11643. '+','+', 0, TOK_POST_INC,
  11644. '*','*', 0, TOK_EXPONENT,
  11645. '!', 0, TOK_NOT,
  11646. '<', 0, TOK_LT,
  11647. '>', 0, TOK_GT,
  11648. '=', 0, TOK_ASSIGN,
  11649. '|', 0, TOK_BOR,
  11650. '&', 0, TOK_BAND,
  11651. '*', 0, TOK_MUL,
  11652. '/', 0, TOK_DIV,
  11653. '%', 0, TOK_REM,
  11654. '+', 0, TOK_ADD,
  11655. '-', 0, TOK_SUB,
  11656. '^', 0, TOK_BXOR,
  11657. /* uniq */
  11658. '~', 0, TOK_BNOT,
  11659. ',', 0, TOK_COMMA,
  11660. '?', 0, TOK_CONDITIONAL,
  11661. ':', 0, TOK_CONDITIONAL_SEP,
  11662. ')', 0, TOK_RPAREN,
  11663. '(', 0, TOK_LPAREN,
  11664. 0
  11665. };
  11666. /* ptr to ")" */
  11667. #define endexpression &op_tokens[sizeof(op_tokens)-7]
  11668. extern long arith (const char *expr, int *perrcode)
  11669. {
  11670. register char arithval; /* Current character under analysis */
  11671. operator lasttok, op;
  11672. operator prec;
  11673. const char *p = endexpression;
  11674. int errcode;
  11675. size_t datasizes = strlen(expr) + 2;
  11676. /* Stack of integers */
  11677. /* The proof that there can be no more than strlen(startbuf)/2+1 integers
  11678. * in any given correct or incorrect expression is left as an excersize to
  11679. * the reader. */
  11680. v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
  11681. *numstackptr = numstack;
  11682. /* Stack of operator tokens */
  11683. operator *stack = alloca((datasizes) * sizeof(operator)),
  11684. *stackptr = stack;
  11685. *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
  11686. *perrcode = errcode = 0;
  11687. while(1) {
  11688. if ((arithval = *expr) == 0) {
  11689. if (p == endexpression) {
  11690. /* Null expression. */
  11691. return 0;
  11692. }
  11693. /* This is only reached after all tokens have been extracted from the
  11694. * input stream. If there are still tokens on the operator stack, they
  11695. * are to be applied in order. At the end, there should be a final
  11696. * result on the integer stack */
  11697. if (expr != endexpression + 1) {
  11698. /* If we haven't done so already, */
  11699. /* append a closing right paren */
  11700. expr = endexpression;
  11701. /* and let the loop process it. */
  11702. continue;
  11703. }
  11704. /* At this point, we're done with the expression. */
  11705. if (numstackptr != numstack+1) {
  11706. /* ... but if there isn't, it's bad */
  11707. err:
  11708. return (*perrcode = -1);
  11709. }
  11710. if(numstack->var) {
  11711. /* expression is $((var)) only, lookup now */
  11712. errcode = arith_lookup_val(numstack);
  11713. }
  11714. ret:
  11715. *perrcode = errcode;
  11716. return numstack->val;
  11717. } else {
  11718. /* Continue processing the expression. */
  11719. if (arith_isspace(arithval)) {
  11720. /* Skip whitespace */
  11721. goto prologue;
  11722. }
  11723. if((p = endofname(expr)) != expr) {
  11724. int var_name_size = (p-expr) + 1; /* trailing zero */
  11725. numstackptr->var = alloca(var_name_size);
  11726. safe_strncpy(numstackptr->var, expr, var_name_size);
  11727. expr = p;
  11728. num:
  11729. numstackptr->contidional_second_val_initialized = 0;
  11730. numstackptr++;
  11731. lasttok = TOK_NUM;
  11732. continue;
  11733. } else if (is_digit(arithval)) {
  11734. numstackptr->var = NULL;
  11735. numstackptr->val = strtol(expr, (char **) &expr, 0);
  11736. goto num;
  11737. }
  11738. for(p = op_tokens; ; p++) {
  11739. const char *o;
  11740. if(*p == 0) {
  11741. /* strange operator not found */
  11742. goto err;
  11743. }
  11744. for(o = expr; *p && *o == *p; p++)
  11745. o++;
  11746. if(! *p) {
  11747. /* found */
  11748. expr = o - 1;
  11749. break;
  11750. }
  11751. /* skip tail uncompared token */
  11752. while(*p)
  11753. p++;
  11754. /* skip zero delim */
  11755. p++;
  11756. }
  11757. op = p[1];
  11758. /* post grammar: a++ reduce to num */
  11759. if(lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  11760. lasttok = TOK_NUM;
  11761. /* Plus and minus are binary (not unary) _only_ if the last
  11762. * token was as number, or a right paren (which pretends to be
  11763. * a number, since it evaluates to one). Think about it.
  11764. * It makes sense. */
  11765. if (lasttok != TOK_NUM) {
  11766. switch(op) {
  11767. case TOK_ADD:
  11768. op = TOK_UPLUS;
  11769. break;
  11770. case TOK_SUB:
  11771. op = TOK_UMINUS;
  11772. break;
  11773. case TOK_POST_INC:
  11774. op = TOK_PRE_INC;
  11775. break;
  11776. case TOK_POST_DEC:
  11777. op = TOK_PRE_DEC;
  11778. break;
  11779. }
  11780. }
  11781. /* We don't want a unary operator to cause recursive descent on the
  11782. * stack, because there can be many in a row and it could cause an
  11783. * operator to be evaluated before its argument is pushed onto the
  11784. * integer stack. */
  11785. /* But for binary operators, "apply" everything on the operator
  11786. * stack until we find an operator with a lesser priority than the
  11787. * one we have just extracted. */
  11788. /* Left paren is given the lowest priority so it will never be
  11789. * "applied" in this way.
  11790. * if associativity is right and priority eq, applied also skip
  11791. */
  11792. prec = PREC(op);
  11793. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  11794. /* not left paren or unary */
  11795. if (lasttok != TOK_NUM) {
  11796. /* binary op must be preceded by a num */
  11797. goto err;
  11798. }
  11799. while (stackptr != stack) {
  11800. if (op == TOK_RPAREN) {
  11801. /* The algorithm employed here is simple: while we don't
  11802. * hit an open paren nor the bottom of the stack, pop
  11803. * tokens and apply them */
  11804. if (stackptr[-1] == TOK_LPAREN) {
  11805. --stackptr;
  11806. /* Any operator directly after a */
  11807. lasttok = TOK_NUM;
  11808. /* close paren should consider itself binary */
  11809. goto prologue;
  11810. }
  11811. } else {
  11812. operator prev_prec = PREC(stackptr[-1]);
  11813. convert_prec_is_assing(prec);
  11814. convert_prec_is_assing(prev_prec);
  11815. if (prev_prec < prec)
  11816. break;
  11817. /* check right assoc */
  11818. if(prev_prec == prec && is_right_associativity(prec))
  11819. break;
  11820. }
  11821. errcode = arith_apply(*--stackptr, numstack, &numstackptr);
  11822. if(errcode) goto ret;
  11823. }
  11824. if (op == TOK_RPAREN) {
  11825. goto err;
  11826. }
  11827. }
  11828. /* Push this operator to the stack and remember it. */
  11829. *stackptr++ = lasttok = op;
  11830. prologue:
  11831. ++expr;
  11832. }
  11833. }
  11834. }
  11835. #endif /* BB_ASH_MATH_SUPPORT */
  11836. #ifdef DEBUG
  11837. const char *bb_applet_name = "debug stuff usage";
  11838. int main(int argc, char **argv)
  11839. {
  11840. return ash_main(argc, argv);
  11841. }
  11842. #endif
  11843. /*-
  11844. * Copyright (c) 1989, 1991, 1993, 1994
  11845. * The Regents of the University of California. All rights reserved.
  11846. *
  11847. * This code is derived from software contributed to Berkeley by
  11848. * Kenneth Almquist.
  11849. *
  11850. * Redistribution and use in source and binary forms, with or without
  11851. * modification, are permitted provided that the following conditions
  11852. * are met:
  11853. * 1. Redistributions of source code must retain the above copyright
  11854. * notice, this list of conditions and the following disclaimer.
  11855. * 2. Redistributions in binary form must reproduce the above copyright
  11856. * notice, this list of conditions and the following disclaimer in the
  11857. * documentation and/or other materials provided with the distribution.
  11858. *
  11859. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  11860. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  11861. *
  11862. * 4. Neither the name of the University nor the names of its contributors
  11863. * may be used to endorse or promote products derived from this software
  11864. * without specific prior written permission.
  11865. *
  11866. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  11867. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11868. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  11869. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  11870. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  11871. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  11872. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  11873. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  11874. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  11875. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11876. * SUCH DAMAGE.
  11877. */