ash.c 272 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * Copyright (c) 1989, 1991, 1993, 1994
  6. * The Regents of the University of California. All rights reserved.
  7. *
  8. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  9. * was re-ported from NetBSD and debianized.
  10. *
  11. *
  12. * This code is derived from software contributed to Berkeley by
  13. * Kenneth Almquist.
  14. *
  15. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  16. *
  17. * Original BSD copyright notice is retained at the end of this file.
  18. */
  19. /*
  20. * rewrite arith.y to micro stack based cryptic algorithm by
  21. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  22. *
  23. * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
  24. * dynamic variables.
  25. *
  26. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
  27. * used in busybox and size optimizations,
  28. * rewrote arith (see notes to this), added locale support,
  29. * rewrote dynamic variables.
  30. *
  31. */
  32. /*
  33. * The follow should be set to reflect the type of system you have:
  34. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  35. * define SYSV if you are running under System V.
  36. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  37. * define DEBUG=2 to compile in and turn on debugging.
  38. *
  39. * When debugging is on, debugging info will be written to ./trace and
  40. * a quit signal will generate a core dump.
  41. */
  42. #define DEBUG 0
  43. #define IFS_BROKEN
  44. #define PROFILE 0
  45. #if ENABLE_ASH_JOB_CONTROL
  46. #define JOBS 1
  47. #else
  48. #define JOBS 0
  49. #endif
  50. #if DEBUG
  51. #define _GNU_SOURCE
  52. #endif
  53. #include "busybox.h" /* for struct bb_applet */
  54. #include <paths.h>
  55. #include <setjmp.h>
  56. #include <fnmatch.h>
  57. #if JOBS || ENABLE_ASH_READ_NCHARS
  58. #include <termios.h>
  59. #endif
  60. extern char **environ;
  61. #if defined(__uClinux__)
  62. #error "Do not even bother, ash will not run on uClinux"
  63. #endif
  64. /* ============ Misc helpers */
  65. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  66. /* C99 say: "char" declaration may be signed or unsigned default */
  67. #define signed_char2int(sc) ((int)((signed char)sc))
  68. /* ============ Shell options */
  69. static const char *const optletters_optnames[] = {
  70. "e" "errexit",
  71. "f" "noglob",
  72. "I" "ignoreeof",
  73. "i" "interactive",
  74. "m" "monitor",
  75. "n" "noexec",
  76. "s" "stdin",
  77. "x" "xtrace",
  78. "v" "verbose",
  79. "C" "noclobber",
  80. "a" "allexport",
  81. "b" "notify",
  82. "u" "nounset",
  83. "\0" "vi"
  84. #if DEBUG
  85. ,"\0" "nolog"
  86. ,"\0" "debug"
  87. #endif
  88. };
  89. #define optletters(n) optletters_optnames[(n)][0]
  90. #define optnames(n) (&optletters_optnames[(n)][1])
  91. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  92. static char optlist[NOPTS] ALIGN1;
  93. #define eflag optlist[0]
  94. #define fflag optlist[1]
  95. #define Iflag optlist[2]
  96. #define iflag optlist[3]
  97. #define mflag optlist[4]
  98. #define nflag optlist[5]
  99. #define sflag optlist[6]
  100. #define xflag optlist[7]
  101. #define vflag optlist[8]
  102. #define Cflag optlist[9]
  103. #define aflag optlist[10]
  104. #define bflag optlist[11]
  105. #define uflag optlist[12]
  106. #define viflag optlist[13]
  107. #if DEBUG
  108. #define nolog optlist[14]
  109. #define debug optlist[15]
  110. #endif
  111. /* ============ Misc data */
  112. static char nullstr[1] ALIGN1; /* zero length string */
  113. static const char homestr[] ALIGN1 = "HOME";
  114. static const char snlfmt[] ALIGN1 = "%s\n";
  115. static const char illnum[] ALIGN1 = "Illegal number: %s";
  116. static char *minusc; /* argument to -c option */
  117. /* pid of main shell */
  118. static int rootpid;
  119. /* shell level: 0 for the main shell, 1 for its children, and so on */
  120. static int shlvl;
  121. #define rootshell (!shlvl)
  122. /* trap handler commands */
  123. static char *trap[NSIG];
  124. static smallint isloginsh;
  125. /* current value of signal */
  126. static char sigmode[NSIG - 1];
  127. /* indicates specified signal received */
  128. static char gotsig[NSIG - 1];
  129. static char *arg0; /* value of $0 */
  130. /* ============ Interrupts / exceptions */
  131. /*
  132. * We enclose jmp_buf in a structure so that we can declare pointers to
  133. * jump locations. The global variable handler contains the location to
  134. * jump to when an exception occurs, and the global variable exception
  135. * contains a code identifying the exception. To implement nested
  136. * exception handlers, the user should save the value of handler on entry
  137. * to an inner scope, set handler to point to a jmploc structure for the
  138. * inner scope, and restore handler on exit from the scope.
  139. */
  140. struct jmploc {
  141. jmp_buf loc;
  142. };
  143. static struct jmploc *exception_handler;
  144. static int exception;
  145. /* exceptions */
  146. #define EXINT 0 /* SIGINT received */
  147. #define EXERROR 1 /* a generic error */
  148. #define EXSHELLPROC 2 /* execute a shell procedure */
  149. #define EXEXEC 3 /* command execution failed */
  150. #define EXEXIT 4 /* exit the shell */
  151. #define EXSIG 5 /* trapped signal in wait(1) */
  152. static volatile int suppressint;
  153. static volatile sig_atomic_t intpending;
  154. /* do we generate EXSIG events */
  155. static int exsig;
  156. /* last pending signal */
  157. static volatile sig_atomic_t pendingsig;
  158. /*
  159. * Sigmode records the current value of the signal handlers for the various
  160. * modes. A value of zero means that the current handler is not known.
  161. * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  162. */
  163. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  164. #define S_CATCH 2 /* signal is caught */
  165. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  166. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  167. #define S_RESET 5 /* temporary - to reset a hard ignored sig */
  168. /*
  169. * These macros allow the user to suspend the handling of interrupt signals
  170. * over a period of time. This is similar to SIGHOLD to or sigblock, but
  171. * much more efficient and portable. (But hacking the kernel is so much
  172. * more fun than worrying about efficiency and portability. :-))
  173. */
  174. #define INT_OFF \
  175. do { \
  176. suppressint++; \
  177. xbarrier(); \
  178. } while (0)
  179. /*
  180. * Called to raise an exception. Since C doesn't include exceptions, we
  181. * just do a longjmp to the exception handler. The type of exception is
  182. * stored in the global variable "exception".
  183. */
  184. static void raise_exception(int) ATTRIBUTE_NORETURN;
  185. static void
  186. raise_exception(int e)
  187. {
  188. #if DEBUG
  189. if (exception_handler == NULL)
  190. abort();
  191. #endif
  192. INT_OFF;
  193. exception = e;
  194. longjmp(exception_handler->loc, 1);
  195. }
  196. /*
  197. * Called from trap.c when a SIGINT is received. (If the user specifies
  198. * that SIGINT is to be trapped or ignored using the trap builtin, then
  199. * this routine is not called.) Suppressint is nonzero when interrupts
  200. * are held using the INT_OFF macro. (The test for iflag is just
  201. * defensive programming.)
  202. */
  203. static void raise_interrupt(void) ATTRIBUTE_NORETURN;
  204. static void
  205. raise_interrupt(void)
  206. {
  207. int i;
  208. sigset_t mask;
  209. intpending = 0;
  210. /* Signal is not automatically re-enabled after it is raised,
  211. * do it ourself */
  212. sigemptyset(&mask);
  213. sigprocmask(SIG_SETMASK, &mask, 0);
  214. /* pendingsig = 0; - now done in onsig() */
  215. i = EXSIG;
  216. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  217. if (!(rootshell && iflag)) {
  218. signal(SIGINT, SIG_DFL);
  219. raise(SIGINT);
  220. }
  221. i = EXINT;
  222. }
  223. raise_exception(i);
  224. /* NOTREACHED */
  225. }
  226. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  227. static void
  228. int_on(void)
  229. {
  230. if (--suppressint == 0 && intpending) {
  231. raise_interrupt();
  232. }
  233. }
  234. #define INT_ON int_on()
  235. static void
  236. force_int_on(void)
  237. {
  238. suppressint = 0;
  239. if (intpending)
  240. raise_interrupt();
  241. }
  242. #define FORCE_INT_ON force_int_on()
  243. #else
  244. #define INT_ON \
  245. do { \
  246. xbarrier(); \
  247. if (--suppressint == 0 && intpending) \
  248. raise_interrupt(); \
  249. } while (0)
  250. #define FORCE_INT_ON \
  251. do { \
  252. xbarrier(); \
  253. suppressint = 0; \
  254. if (intpending) \
  255. raise_interrupt(); \
  256. } while (0)
  257. #endif /* ASH_OPTIMIZE_FOR_SIZE */
  258. #define SAVE_INT(v) ((v) = suppressint)
  259. #define RESTORE_INT(v) \
  260. do { \
  261. xbarrier(); \
  262. suppressint = (v); \
  263. if (suppressint == 0 && intpending) \
  264. raise_interrupt(); \
  265. } while (0)
  266. #define EXSIGON \
  267. do { \
  268. exsig++; \
  269. xbarrier(); \
  270. if (pendingsig) \
  271. raise_exception(EXSIG); \
  272. } while (0)
  273. /* EXSIG is turned off by evalbltin(). */
  274. /*
  275. * Ignore a signal. Only one usage site - in forkchild()
  276. */
  277. static void
  278. ignoresig(int signo)
  279. {
  280. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  281. signal(signo, SIG_IGN);
  282. }
  283. sigmode[signo - 1] = S_HARD_IGN;
  284. }
  285. /*
  286. * Signal handler. Only one usage site - in setsignal()
  287. */
  288. static void
  289. onsig(int signo)
  290. {
  291. gotsig[signo - 1] = 1;
  292. pendingsig = signo;
  293. if (exsig || (signo == SIGINT && !trap[SIGINT])) {
  294. if (!suppressint) {
  295. pendingsig = 0;
  296. raise_interrupt();
  297. }
  298. intpending = 1;
  299. }
  300. }
  301. /* ============ Stdout/stderr output */
  302. static void
  303. outstr(const char *p, FILE *file)
  304. {
  305. INT_OFF;
  306. fputs(p, file);
  307. INT_ON;
  308. }
  309. static void
  310. flush_stdout_stderr(void)
  311. {
  312. INT_OFF;
  313. fflush(stdout);
  314. fflush(stderr);
  315. INT_ON;
  316. }
  317. static void
  318. flush_stderr(void)
  319. {
  320. INT_OFF;
  321. fflush(stderr);
  322. INT_ON;
  323. }
  324. static void
  325. outcslow(int c, FILE *dest)
  326. {
  327. INT_OFF;
  328. putc(c, dest);
  329. fflush(dest);
  330. INT_ON;
  331. }
  332. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  333. static int
  334. out1fmt(const char *fmt, ...)
  335. {
  336. va_list ap;
  337. int r;
  338. INT_OFF;
  339. va_start(ap, fmt);
  340. r = vprintf(fmt, ap);
  341. va_end(ap);
  342. INT_ON;
  343. return r;
  344. }
  345. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  346. static int
  347. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  348. {
  349. va_list ap;
  350. int ret;
  351. va_start(ap, fmt);
  352. INT_OFF;
  353. ret = vsnprintf(outbuf, length, fmt, ap);
  354. va_end(ap);
  355. INT_ON;
  356. return ret;
  357. }
  358. static void
  359. out1str(const char *p)
  360. {
  361. outstr(p, stdout);
  362. }
  363. static void
  364. out2str(const char *p)
  365. {
  366. outstr(p, stderr);
  367. flush_stderr();
  368. }
  369. /* ============ Parser structures */
  370. /* control characters in argument strings */
  371. #define CTLESC '\201' /* escape next character */
  372. #define CTLVAR '\202' /* variable defn */
  373. #define CTLENDVAR '\203'
  374. #define CTLBACKQ '\204'
  375. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  376. /* CTLBACKQ | CTLQUOTE == '\205' */
  377. #define CTLARI '\206' /* arithmetic expression */
  378. #define CTLENDARI '\207'
  379. #define CTLQUOTEMARK '\210'
  380. /* variable substitution byte (follows CTLVAR) */
  381. #define VSTYPE 0x0f /* type of variable substitution */
  382. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  383. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  384. /* values of VSTYPE field */
  385. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  386. #define VSMINUS 0x2 /* ${var-text} */
  387. #define VSPLUS 0x3 /* ${var+text} */
  388. #define VSQUESTION 0x4 /* ${var?message} */
  389. #define VSASSIGN 0x5 /* ${var=text} */
  390. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  391. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  392. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  393. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  394. #define VSLENGTH 0xa /* ${#var} */
  395. static const char dolatstr[] ALIGN1 = {
  396. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  397. };
  398. #define NCMD 0
  399. #define NPIPE 1
  400. #define NREDIR 2
  401. #define NBACKGND 3
  402. #define NSUBSHELL 4
  403. #define NAND 5
  404. #define NOR 6
  405. #define NSEMI 7
  406. #define NIF 8
  407. #define NWHILE 9
  408. #define NUNTIL 10
  409. #define NFOR 11
  410. #define NCASE 12
  411. #define NCLIST 13
  412. #define NDEFUN 14
  413. #define NARG 15
  414. #define NTO 16
  415. #define NCLOBBER 17
  416. #define NFROM 18
  417. #define NFROMTO 19
  418. #define NAPPEND 20
  419. #define NTOFD 21
  420. #define NFROMFD 22
  421. #define NHERE 23
  422. #define NXHERE 24
  423. #define NNOT 25
  424. union node;
  425. struct ncmd {
  426. int type;
  427. union node *assign;
  428. union node *args;
  429. union node *redirect;
  430. };
  431. struct npipe {
  432. int type;
  433. int backgnd;
  434. struct nodelist *cmdlist;
  435. };
  436. struct nredir {
  437. int type;
  438. union node *n;
  439. union node *redirect;
  440. };
  441. struct nbinary {
  442. int type;
  443. union node *ch1;
  444. union node *ch2;
  445. };
  446. struct nif {
  447. int type;
  448. union node *test;
  449. union node *ifpart;
  450. union node *elsepart;
  451. };
  452. struct nfor {
  453. int type;
  454. union node *args;
  455. union node *body;
  456. char *var;
  457. };
  458. struct ncase {
  459. int type;
  460. union node *expr;
  461. union node *cases;
  462. };
  463. struct nclist {
  464. int type;
  465. union node *next;
  466. union node *pattern;
  467. union node *body;
  468. };
  469. struct narg {
  470. int type;
  471. union node *next;
  472. char *text;
  473. struct nodelist *backquote;
  474. };
  475. struct nfile {
  476. int type;
  477. union node *next;
  478. int fd;
  479. union node *fname;
  480. char *expfname;
  481. };
  482. struct ndup {
  483. int type;
  484. union node *next;
  485. int fd;
  486. int dupfd;
  487. union node *vname;
  488. };
  489. struct nhere {
  490. int type;
  491. union node *next;
  492. int fd;
  493. union node *doc;
  494. };
  495. struct nnot {
  496. int type;
  497. union node *com;
  498. };
  499. union node {
  500. int type;
  501. struct ncmd ncmd;
  502. struct npipe npipe;
  503. struct nredir nredir;
  504. struct nbinary nbinary;
  505. struct nif nif;
  506. struct nfor nfor;
  507. struct ncase ncase;
  508. struct nclist nclist;
  509. struct narg narg;
  510. struct nfile nfile;
  511. struct ndup ndup;
  512. struct nhere nhere;
  513. struct nnot nnot;
  514. };
  515. struct nodelist {
  516. struct nodelist *next;
  517. union node *n;
  518. };
  519. struct funcnode {
  520. int count;
  521. union node n;
  522. };
  523. /*
  524. * Free a parse tree.
  525. */
  526. static void
  527. freefunc(struct funcnode *f)
  528. {
  529. if (f && --f->count < 0)
  530. free(f);
  531. }
  532. /* ============ Debugging output */
  533. #if DEBUG
  534. static FILE *tracefile;
  535. static void
  536. trace_printf(const char *fmt, ...)
  537. {
  538. va_list va;
  539. if (debug != 1)
  540. return;
  541. va_start(va, fmt);
  542. vfprintf(tracefile, fmt, va);
  543. va_end(va);
  544. }
  545. static void
  546. trace_vprintf(const char *fmt, va_list va)
  547. {
  548. if (debug != 1)
  549. return;
  550. vfprintf(tracefile, fmt, va);
  551. }
  552. static void
  553. trace_puts(const char *s)
  554. {
  555. if (debug != 1)
  556. return;
  557. fputs(s, tracefile);
  558. }
  559. static void
  560. trace_puts_quoted(char *s)
  561. {
  562. char *p;
  563. char c;
  564. if (debug != 1)
  565. return;
  566. putc('"', tracefile);
  567. for (p = s; *p; p++) {
  568. switch (*p) {
  569. case '\n': c = 'n'; goto backslash;
  570. case '\t': c = 't'; goto backslash;
  571. case '\r': c = 'r'; goto backslash;
  572. case '"': c = '"'; goto backslash;
  573. case '\\': c = '\\'; goto backslash;
  574. case CTLESC: c = 'e'; goto backslash;
  575. case CTLVAR: c = 'v'; goto backslash;
  576. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  577. case CTLBACKQ: c = 'q'; goto backslash;
  578. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  579. backslash:
  580. putc('\\', tracefile);
  581. putc(c, tracefile);
  582. break;
  583. default:
  584. if (*p >= ' ' && *p <= '~')
  585. putc(*p, tracefile);
  586. else {
  587. putc('\\', tracefile);
  588. putc(*p >> 6 & 03, tracefile);
  589. putc(*p >> 3 & 07, tracefile);
  590. putc(*p & 07, tracefile);
  591. }
  592. break;
  593. }
  594. }
  595. putc('"', tracefile);
  596. }
  597. static void
  598. trace_puts_args(char **ap)
  599. {
  600. if (debug != 1)
  601. return;
  602. if (!*ap)
  603. return;
  604. while (1) {
  605. trace_puts_quoted(*ap);
  606. if (!*++ap) {
  607. putc('\n', tracefile);
  608. break;
  609. }
  610. putc(' ', tracefile);
  611. }
  612. }
  613. static void
  614. opentrace(void)
  615. {
  616. char s[100];
  617. #ifdef O_APPEND
  618. int flags;
  619. #endif
  620. if (debug != 1) {
  621. if (tracefile)
  622. fflush(tracefile);
  623. /* leave open because libedit might be using it */
  624. return;
  625. }
  626. strcpy(s, "./trace");
  627. if (tracefile) {
  628. if (!freopen(s, "a", tracefile)) {
  629. fprintf(stderr, "Can't re-open %s\n", s);
  630. debug = 0;
  631. return;
  632. }
  633. } else {
  634. tracefile = fopen(s, "a");
  635. if (tracefile == NULL) {
  636. fprintf(stderr, "Can't open %s\n", s);
  637. debug = 0;
  638. return;
  639. }
  640. }
  641. #ifdef O_APPEND
  642. flags = fcntl(fileno(tracefile), F_GETFL);
  643. if (flags >= 0)
  644. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  645. #endif
  646. setlinebuf(tracefile);
  647. fputs("\nTracing started.\n", tracefile);
  648. }
  649. static void
  650. indent(int amount, char *pfx, FILE *fp)
  651. {
  652. int i;
  653. for (i = 0; i < amount; i++) {
  654. if (pfx && i == amount - 1)
  655. fputs(pfx, fp);
  656. putc('\t', fp);
  657. }
  658. }
  659. /* little circular references here... */
  660. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  661. static void
  662. sharg(union node *arg, FILE *fp)
  663. {
  664. char *p;
  665. struct nodelist *bqlist;
  666. int subtype;
  667. if (arg->type != NARG) {
  668. out1fmt("<node type %d>\n", arg->type);
  669. abort();
  670. }
  671. bqlist = arg->narg.backquote;
  672. for (p = arg->narg.text; *p; p++) {
  673. switch (*p) {
  674. case CTLESC:
  675. putc(*++p, fp);
  676. break;
  677. case CTLVAR:
  678. putc('$', fp);
  679. putc('{', fp);
  680. subtype = *++p;
  681. if (subtype == VSLENGTH)
  682. putc('#', fp);
  683. while (*p != '=')
  684. putc(*p++, fp);
  685. if (subtype & VSNUL)
  686. putc(':', fp);
  687. switch (subtype & VSTYPE) {
  688. case VSNORMAL:
  689. putc('}', fp);
  690. break;
  691. case VSMINUS:
  692. putc('-', fp);
  693. break;
  694. case VSPLUS:
  695. putc('+', fp);
  696. break;
  697. case VSQUESTION:
  698. putc('?', fp);
  699. break;
  700. case VSASSIGN:
  701. putc('=', fp);
  702. break;
  703. case VSTRIMLEFT:
  704. putc('#', fp);
  705. break;
  706. case VSTRIMLEFTMAX:
  707. putc('#', fp);
  708. putc('#', fp);
  709. break;
  710. case VSTRIMRIGHT:
  711. putc('%', fp);
  712. break;
  713. case VSTRIMRIGHTMAX:
  714. putc('%', fp);
  715. putc('%', fp);
  716. break;
  717. case VSLENGTH:
  718. break;
  719. default:
  720. out1fmt("<subtype %d>", subtype);
  721. }
  722. break;
  723. case CTLENDVAR:
  724. putc('}', fp);
  725. break;
  726. case CTLBACKQ:
  727. case CTLBACKQ|CTLQUOTE:
  728. putc('$', fp);
  729. putc('(', fp);
  730. shtree(bqlist->n, -1, NULL, fp);
  731. putc(')', fp);
  732. break;
  733. default:
  734. putc(*p, fp);
  735. break;
  736. }
  737. }
  738. }
  739. static void
  740. shcmd(union node *cmd, FILE *fp)
  741. {
  742. union node *np;
  743. int first;
  744. const char *s;
  745. int dftfd;
  746. first = 1;
  747. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  748. if (!first)
  749. putc(' ', fp);
  750. sharg(np, fp);
  751. first = 0;
  752. }
  753. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  754. if (!first)
  755. putc(' ', fp);
  756. dftfd = 0;
  757. switch (np->nfile.type) {
  758. case NTO: s = ">>"+1; dftfd = 1; break;
  759. case NCLOBBER: s = ">|"; dftfd = 1; break;
  760. case NAPPEND: s = ">>"; dftfd = 1; break;
  761. case NTOFD: s = ">&"; dftfd = 1; break;
  762. case NFROM: s = "<"; break;
  763. case NFROMFD: s = "<&"; break;
  764. case NFROMTO: s = "<>"; break;
  765. default: s = "*error*"; break;
  766. }
  767. if (np->nfile.fd != dftfd)
  768. fprintf(fp, "%d", np->nfile.fd);
  769. fputs(s, fp);
  770. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  771. fprintf(fp, "%d", np->ndup.dupfd);
  772. } else {
  773. sharg(np->nfile.fname, fp);
  774. }
  775. first = 0;
  776. }
  777. }
  778. static void
  779. shtree(union node *n, int ind, char *pfx, FILE *fp)
  780. {
  781. struct nodelist *lp;
  782. const char *s;
  783. if (n == NULL)
  784. return;
  785. indent(ind, pfx, fp);
  786. switch (n->type) {
  787. case NSEMI:
  788. s = "; ";
  789. goto binop;
  790. case NAND:
  791. s = " && ";
  792. goto binop;
  793. case NOR:
  794. s = " || ";
  795. binop:
  796. shtree(n->nbinary.ch1, ind, NULL, fp);
  797. /* if (ind < 0) */
  798. fputs(s, fp);
  799. shtree(n->nbinary.ch2, ind, NULL, fp);
  800. break;
  801. case NCMD:
  802. shcmd(n, fp);
  803. if (ind >= 0)
  804. putc('\n', fp);
  805. break;
  806. case NPIPE:
  807. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  808. shcmd(lp->n, fp);
  809. if (lp->next)
  810. fputs(" | ", fp);
  811. }
  812. if (n->npipe.backgnd)
  813. fputs(" &", fp);
  814. if (ind >= 0)
  815. putc('\n', fp);
  816. break;
  817. default:
  818. fprintf(fp, "<node type %d>", n->type);
  819. if (ind >= 0)
  820. putc('\n', fp);
  821. break;
  822. }
  823. }
  824. static void
  825. showtree(union node *n)
  826. {
  827. trace_puts("showtree called\n");
  828. shtree(n, 1, NULL, stdout);
  829. }
  830. #define TRACE(param) trace_printf param
  831. #define TRACEV(param) trace_vprintf param
  832. #else
  833. #define TRACE(param)
  834. #define TRACEV(param)
  835. #endif /* DEBUG */
  836. /* ============ Parser data */
  837. /*
  838. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  839. */
  840. struct strlist {
  841. struct strlist *next;
  842. char *text;
  843. };
  844. #if ENABLE_ASH_ALIAS
  845. struct alias;
  846. #endif
  847. struct strpush {
  848. struct strpush *prev; /* preceding string on stack */
  849. char *prevstring;
  850. int prevnleft;
  851. #if ENABLE_ASH_ALIAS
  852. struct alias *ap; /* if push was associated with an alias */
  853. #endif
  854. char *string; /* remember the string since it may change */
  855. };
  856. struct parsefile {
  857. struct parsefile *prev; /* preceding file on stack */
  858. int linno; /* current line */
  859. int fd; /* file descriptor (or -1 if string) */
  860. int nleft; /* number of chars left in this line */
  861. int lleft; /* number of chars left in this buffer */
  862. char *nextc; /* next char in buffer */
  863. char *buf; /* input buffer */
  864. struct strpush *strpush; /* for pushing strings at this level */
  865. struct strpush basestrpush; /* so pushing one is fast */
  866. };
  867. static struct parsefile basepf; /* top level input file */
  868. static struct parsefile *parsefile = &basepf; /* current input file */
  869. static int startlinno; /* line # where last token started */
  870. static char *commandname; /* currently executing command */
  871. static struct strlist *cmdenviron; /* environment for builtin command */
  872. static int exitstatus; /* exit status of last command */
  873. /* ============ Message printing */
  874. static void
  875. ash_vmsg(const char *msg, va_list ap)
  876. {
  877. fprintf(stderr, "%s: ", arg0);
  878. if (commandname) {
  879. if (strcmp(arg0, commandname))
  880. fprintf(stderr, "%s: ", commandname);
  881. if (!iflag || parsefile->fd)
  882. fprintf(stderr, "line %d: ", startlinno);
  883. }
  884. vfprintf(stderr, msg, ap);
  885. outcslow('\n', stderr);
  886. }
  887. /*
  888. * Exverror is called to raise the error exception. If the second argument
  889. * is not NULL then error prints an error message using printf style
  890. * formatting. It then raises the error exception.
  891. */
  892. static void ash_vmsg_and_raise(int, const char *, va_list) ATTRIBUTE_NORETURN;
  893. static void
  894. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  895. {
  896. #if DEBUG
  897. if (msg) {
  898. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  899. TRACEV((msg, ap));
  900. TRACE(("\") pid=%d\n", getpid()));
  901. } else
  902. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  903. if (msg)
  904. #endif
  905. ash_vmsg(msg, ap);
  906. flush_stdout_stderr();
  907. raise_exception(cond);
  908. /* NOTREACHED */
  909. }
  910. static void ash_msg_and_raise_error(const char *, ...) ATTRIBUTE_NORETURN;
  911. static void
  912. ash_msg_and_raise_error(const char *msg, ...)
  913. {
  914. va_list ap;
  915. va_start(ap, msg);
  916. ash_vmsg_and_raise(EXERROR, msg, ap);
  917. /* NOTREACHED */
  918. va_end(ap);
  919. }
  920. static void ash_msg_and_raise(int, const char *, ...) ATTRIBUTE_NORETURN;
  921. static void
  922. ash_msg_and_raise(int cond, const char *msg, ...)
  923. {
  924. va_list ap;
  925. va_start(ap, msg);
  926. ash_vmsg_and_raise(cond, msg, ap);
  927. /* NOTREACHED */
  928. va_end(ap);
  929. }
  930. /*
  931. * error/warning routines for external builtins
  932. */
  933. static void
  934. ash_msg(const char *fmt, ...)
  935. {
  936. va_list ap;
  937. va_start(ap, fmt);
  938. ash_vmsg(fmt, ap);
  939. va_end(ap);
  940. }
  941. /*
  942. * Return a string describing an error. The returned string may be a
  943. * pointer to a static buffer that will be overwritten on the next call.
  944. * Action describes the operation that got the error.
  945. */
  946. static const char *
  947. errmsg(int e, const char *em)
  948. {
  949. if (e == ENOENT || e == ENOTDIR) {
  950. return em;
  951. }
  952. return strerror(e);
  953. }
  954. /* ============ Memory allocation */
  955. /*
  956. * It appears that grabstackstr() will barf with such alignments
  957. * because stalloc() will return a string allocated in a new stackblock.
  958. */
  959. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  960. enum {
  961. /* Most machines require the value returned from malloc to be aligned
  962. * in some way. The following macro will get this right
  963. * on many machines. */
  964. SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
  965. /* Minimum size of a block */
  966. MINSIZE = SHELL_ALIGN(504),
  967. };
  968. struct stack_block {
  969. struct stack_block *prev;
  970. char space[MINSIZE];
  971. };
  972. struct stackmark {
  973. struct stack_block *stackp;
  974. char *stacknxt;
  975. size_t stacknleft;
  976. struct stackmark *marknext;
  977. };
  978. static struct stack_block stackbase;
  979. static struct stack_block *stackp = &stackbase;
  980. static struct stackmark *markp;
  981. static char *stacknxt = stackbase.space;
  982. static size_t stacknleft = MINSIZE;
  983. static char *sstrend = stackbase.space + MINSIZE;
  984. static int herefd = -1;
  985. #define stackblock() ((void *)stacknxt)
  986. #define stackblocksize() stacknleft
  987. static void *
  988. ckrealloc(void * p, size_t nbytes)
  989. {
  990. p = realloc(p, nbytes);
  991. if (!p)
  992. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  993. return p;
  994. }
  995. static void *
  996. ckmalloc(size_t nbytes)
  997. {
  998. return ckrealloc(NULL, nbytes);
  999. }
  1000. /*
  1001. * Make a copy of a string in safe storage.
  1002. */
  1003. static char *
  1004. ckstrdup(const char *s)
  1005. {
  1006. char *p = strdup(s);
  1007. if (!p)
  1008. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1009. return p;
  1010. }
  1011. /*
  1012. * Parse trees for commands are allocated in lifo order, so we use a stack
  1013. * to make this more efficient, and also to avoid all sorts of exception
  1014. * handling code to handle interrupts in the middle of a parse.
  1015. *
  1016. * The size 504 was chosen because the Ultrix malloc handles that size
  1017. * well.
  1018. */
  1019. static void *
  1020. stalloc(size_t nbytes)
  1021. {
  1022. char *p;
  1023. size_t aligned;
  1024. aligned = SHELL_ALIGN(nbytes);
  1025. if (aligned > stacknleft) {
  1026. size_t len;
  1027. size_t blocksize;
  1028. struct stack_block *sp;
  1029. blocksize = aligned;
  1030. if (blocksize < MINSIZE)
  1031. blocksize = MINSIZE;
  1032. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1033. if (len < blocksize)
  1034. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1035. INT_OFF;
  1036. sp = ckmalloc(len);
  1037. sp->prev = stackp;
  1038. stacknxt = sp->space;
  1039. stacknleft = blocksize;
  1040. sstrend = stacknxt + blocksize;
  1041. stackp = sp;
  1042. INT_ON;
  1043. }
  1044. p = stacknxt;
  1045. stacknxt += aligned;
  1046. stacknleft -= aligned;
  1047. return p;
  1048. }
  1049. static void
  1050. stunalloc(void *p)
  1051. {
  1052. #if DEBUG
  1053. if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
  1054. write(2, "stunalloc\n", 10);
  1055. abort();
  1056. }
  1057. #endif
  1058. stacknleft += stacknxt - (char *)p;
  1059. stacknxt = p;
  1060. }
  1061. /*
  1062. * Like strdup but works with the ash stack.
  1063. */
  1064. static char *
  1065. ststrdup(const char *p)
  1066. {
  1067. size_t len = strlen(p) + 1;
  1068. return memcpy(stalloc(len), p, len);
  1069. }
  1070. static void
  1071. setstackmark(struct stackmark *mark)
  1072. {
  1073. mark->stackp = stackp;
  1074. mark->stacknxt = stacknxt;
  1075. mark->stacknleft = stacknleft;
  1076. mark->marknext = markp;
  1077. markp = mark;
  1078. }
  1079. static void
  1080. popstackmark(struct stackmark *mark)
  1081. {
  1082. struct stack_block *sp;
  1083. if (!mark->stackp)
  1084. return;
  1085. INT_OFF;
  1086. markp = mark->marknext;
  1087. while (stackp != mark->stackp) {
  1088. sp = stackp;
  1089. stackp = sp->prev;
  1090. free(sp);
  1091. }
  1092. stacknxt = mark->stacknxt;
  1093. stacknleft = mark->stacknleft;
  1094. sstrend = mark->stacknxt + mark->stacknleft;
  1095. INT_ON;
  1096. }
  1097. /*
  1098. * When the parser reads in a string, it wants to stick the string on the
  1099. * stack and only adjust the stack pointer when it knows how big the
  1100. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1101. * of space on top of the stack and stackblocklen returns the length of
  1102. * this block. Growstackblock will grow this space by at least one byte,
  1103. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1104. * part of the block that has been used.
  1105. */
  1106. static void
  1107. growstackblock(void)
  1108. {
  1109. size_t newlen;
  1110. newlen = stacknleft * 2;
  1111. if (newlen < stacknleft)
  1112. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1113. if (newlen < 128)
  1114. newlen += 128;
  1115. if (stacknxt == stackp->space && stackp != &stackbase) {
  1116. struct stack_block *oldstackp;
  1117. struct stackmark *xmark;
  1118. struct stack_block *sp;
  1119. struct stack_block *prevstackp;
  1120. size_t grosslen;
  1121. INT_OFF;
  1122. oldstackp = stackp;
  1123. sp = stackp;
  1124. prevstackp = sp->prev;
  1125. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1126. sp = ckrealloc(sp, grosslen);
  1127. sp->prev = prevstackp;
  1128. stackp = sp;
  1129. stacknxt = sp->space;
  1130. stacknleft = newlen;
  1131. sstrend = sp->space + newlen;
  1132. /*
  1133. * Stack marks pointing to the start of the old block
  1134. * must be relocated to point to the new block
  1135. */
  1136. xmark = markp;
  1137. while (xmark != NULL && xmark->stackp == oldstackp) {
  1138. xmark->stackp = stackp;
  1139. xmark->stacknxt = stacknxt;
  1140. xmark->stacknleft = stacknleft;
  1141. xmark = xmark->marknext;
  1142. }
  1143. INT_ON;
  1144. } else {
  1145. char *oldspace = stacknxt;
  1146. int oldlen = stacknleft;
  1147. char *p = stalloc(newlen);
  1148. /* free the space we just allocated */
  1149. stacknxt = memcpy(p, oldspace, oldlen);
  1150. stacknleft += newlen;
  1151. }
  1152. }
  1153. static void
  1154. grabstackblock(size_t len)
  1155. {
  1156. len = SHELL_ALIGN(len);
  1157. stacknxt += len;
  1158. stacknleft -= len;
  1159. }
  1160. /*
  1161. * The following routines are somewhat easier to use than the above.
  1162. * The user declares a variable of type STACKSTR, which may be declared
  1163. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1164. * the user uses the macro STPUTC to add characters to the string. In
  1165. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1166. * grown as necessary. When the user is done, she can just leave the
  1167. * string there and refer to it using stackblock(). Or she can allocate
  1168. * the space for it using grabstackstr(). If it is necessary to allow
  1169. * someone else to use the stack temporarily and then continue to grow
  1170. * the string, the user should use grabstack to allocate the space, and
  1171. * then call ungrabstr(p) to return to the previous mode of operation.
  1172. *
  1173. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1174. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1175. * is space for at least one character.
  1176. */
  1177. static void *
  1178. growstackstr(void)
  1179. {
  1180. size_t len = stackblocksize();
  1181. if (herefd >= 0 && len >= 1024) {
  1182. full_write(herefd, stackblock(), len);
  1183. return stackblock();
  1184. }
  1185. growstackblock();
  1186. return stackblock() + len;
  1187. }
  1188. /*
  1189. * Called from CHECKSTRSPACE.
  1190. */
  1191. static char *
  1192. makestrspace(size_t newlen, char *p)
  1193. {
  1194. size_t len = p - stacknxt;
  1195. size_t size = stackblocksize();
  1196. for (;;) {
  1197. size_t nleft;
  1198. size = stackblocksize();
  1199. nleft = size - len;
  1200. if (nleft >= newlen)
  1201. break;
  1202. growstackblock();
  1203. }
  1204. return stackblock() + len;
  1205. }
  1206. static char *
  1207. stack_nputstr(const char *s, size_t n, char *p)
  1208. {
  1209. p = makestrspace(n, p);
  1210. p = memcpy(p, s, n) + n;
  1211. return p;
  1212. }
  1213. static char *
  1214. stack_putstr(const char *s, char *p)
  1215. {
  1216. return stack_nputstr(s, strlen(s), p);
  1217. }
  1218. static char *
  1219. _STPUTC(int c, char *p)
  1220. {
  1221. if (p == sstrend)
  1222. p = growstackstr();
  1223. *p++ = c;
  1224. return p;
  1225. }
  1226. #define STARTSTACKSTR(p) ((p) = stackblock())
  1227. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1228. #define CHECKSTRSPACE(n, p) \
  1229. do { \
  1230. char *q = (p); \
  1231. size_t l = (n); \
  1232. size_t m = sstrend - q; \
  1233. if (l > m) \
  1234. (p) = makestrspace(l, q); \
  1235. } while (0)
  1236. #define USTPUTC(c, p) (*p++ = (c))
  1237. #define STACKSTRNUL(p) \
  1238. do { \
  1239. if ((p) == sstrend) \
  1240. p = growstackstr(); \
  1241. *p = '\0'; \
  1242. } while (0)
  1243. #define STUNPUTC(p) (--p)
  1244. #define STTOPC(p) (p[-1])
  1245. #define STADJUST(amount, p) (p += (amount))
  1246. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1247. #define ungrabstackstr(s, p) stunalloc((s))
  1248. #define stackstrend() ((void *)sstrend)
  1249. /* ============ String helpers */
  1250. /*
  1251. * prefix -- see if pfx is a prefix of string.
  1252. */
  1253. static char *
  1254. prefix(const char *string, const char *pfx)
  1255. {
  1256. while (*pfx) {
  1257. if (*pfx++ != *string++)
  1258. return 0;
  1259. }
  1260. return (char *) string;
  1261. }
  1262. /*
  1263. * Check for a valid number. This should be elsewhere.
  1264. */
  1265. static int
  1266. is_number(const char *p)
  1267. {
  1268. do {
  1269. if (!isdigit(*p))
  1270. return 0;
  1271. } while (*++p != '\0');
  1272. return 1;
  1273. }
  1274. /*
  1275. * Convert a string of digits to an integer, printing an error message on
  1276. * failure.
  1277. */
  1278. static int
  1279. number(const char *s)
  1280. {
  1281. if (!is_number(s))
  1282. ash_msg_and_raise_error(illnum, s);
  1283. return atoi(s);
  1284. }
  1285. /*
  1286. * Produce a possibly single quoted string suitable as input to the shell.
  1287. * The return string is allocated on the stack.
  1288. */
  1289. static char *
  1290. single_quote(const char *s)
  1291. {
  1292. char *p;
  1293. STARTSTACKSTR(p);
  1294. do {
  1295. char *q;
  1296. size_t len;
  1297. len = strchrnul(s, '\'') - s;
  1298. q = p = makestrspace(len + 3, p);
  1299. *q++ = '\'';
  1300. q = memcpy(q, s, len) + len;
  1301. *q++ = '\'';
  1302. s += len;
  1303. STADJUST(q - p, p);
  1304. len = strspn(s, "'");
  1305. if (!len)
  1306. break;
  1307. q = p = makestrspace(len + 3, p);
  1308. *q++ = '"';
  1309. q = memcpy(q, s, len) + len;
  1310. *q++ = '"';
  1311. s += len;
  1312. STADJUST(q - p, p);
  1313. } while (*s);
  1314. USTPUTC(0, p);
  1315. return stackblock();
  1316. }
  1317. /* ============ nextopt */
  1318. static char **argptr; /* argument list for builtin commands */
  1319. static char *optionarg; /* set by nextopt (like getopt) */
  1320. static char *optptr; /* used by nextopt */
  1321. /*
  1322. * XXX - should get rid of. have all builtins use getopt(3). the
  1323. * library getopt must have the BSD extension static variable "optreset"
  1324. * otherwise it can't be used within the shell safely.
  1325. *
  1326. * Standard option processing (a la getopt) for builtin routines. The
  1327. * only argument that is passed to nextopt is the option string; the
  1328. * other arguments are unnecessary. It return the character, or '\0' on
  1329. * end of input.
  1330. */
  1331. static int
  1332. nextopt(const char *optstring)
  1333. {
  1334. char *p;
  1335. const char *q;
  1336. char c;
  1337. p = optptr;
  1338. if (p == NULL || *p == '\0') {
  1339. p = *argptr;
  1340. if (p == NULL || *p != '-' || *++p == '\0')
  1341. return '\0';
  1342. argptr++;
  1343. if (LONE_DASH(p)) /* check for "--" */
  1344. return '\0';
  1345. }
  1346. c = *p++;
  1347. for (q = optstring; *q != c; ) {
  1348. if (*q == '\0')
  1349. ash_msg_and_raise_error("illegal option -%c", c);
  1350. if (*++q == ':')
  1351. q++;
  1352. }
  1353. if (*++q == ':') {
  1354. if (*p == '\0' && (p = *argptr++) == NULL)
  1355. ash_msg_and_raise_error("no arg for -%c option", c);
  1356. optionarg = p;
  1357. p = NULL;
  1358. }
  1359. optptr = p;
  1360. return c;
  1361. }
  1362. /* ============ Math support definitions */
  1363. #if ENABLE_ASH_MATH_SUPPORT_64
  1364. typedef int64_t arith_t;
  1365. #define arith_t_type long long
  1366. #else
  1367. typedef long arith_t;
  1368. #define arith_t_type long
  1369. #endif
  1370. #if ENABLE_ASH_MATH_SUPPORT
  1371. static arith_t dash_arith(const char *);
  1372. static arith_t arith(const char *expr, int *perrcode);
  1373. #endif
  1374. #if ENABLE_ASH_RANDOM_SUPPORT
  1375. static unsigned long rseed;
  1376. #ifndef DYNAMIC_VAR
  1377. #define DYNAMIC_VAR
  1378. #endif
  1379. #endif
  1380. /* ============ Shell variables */
  1381. /* flags */
  1382. #define VEXPORT 0x01 /* variable is exported */
  1383. #define VREADONLY 0x02 /* variable cannot be modified */
  1384. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1385. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1386. #define VSTACK 0x10 /* text is allocated on the stack */
  1387. #define VUNSET 0x20 /* the variable is not set */
  1388. #define VNOFUNC 0x40 /* don't call the callback function */
  1389. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1390. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1391. #ifdef DYNAMIC_VAR
  1392. # define VDYNAMIC 0x200 /* dynamic variable */
  1393. #else
  1394. # define VDYNAMIC 0
  1395. #endif
  1396. #ifdef IFS_BROKEN
  1397. static const char defifsvar[] ALIGN1 = "IFS= \t\n";
  1398. #define defifs (defifsvar + 4)
  1399. #else
  1400. static const char defifs[] ALIGN1 = " \t\n";
  1401. #endif
  1402. struct shparam {
  1403. int nparam; /* # of positional parameters (without $0) */
  1404. unsigned char malloc; /* if parameter list dynamically allocated */
  1405. char **p; /* parameter list */
  1406. #if ENABLE_ASH_GETOPTS
  1407. int optind; /* next parameter to be processed by getopts */
  1408. int optoff; /* used by getopts */
  1409. #endif
  1410. };
  1411. static struct shparam shellparam; /* $@ current positional parameters */
  1412. /*
  1413. * Free the list of positional parameters.
  1414. */
  1415. static void
  1416. freeparam(volatile struct shparam *param)
  1417. {
  1418. char **ap;
  1419. if (param->malloc) {
  1420. for (ap = param->p; *ap; ap++)
  1421. free(*ap);
  1422. free(param->p);
  1423. }
  1424. }
  1425. #if ENABLE_ASH_GETOPTS
  1426. static void
  1427. getoptsreset(const char *value)
  1428. {
  1429. shellparam.optind = number(value);
  1430. shellparam.optoff = -1;
  1431. }
  1432. #endif
  1433. struct var {
  1434. struct var *next; /* next entry in hash list */
  1435. int flags; /* flags are defined above */
  1436. const char *text; /* name=value */
  1437. void (*func)(const char *); /* function to be called when */
  1438. /* the variable gets set/unset */
  1439. };
  1440. struct localvar {
  1441. struct localvar *next; /* next local variable in list */
  1442. struct var *vp; /* the variable that was made local */
  1443. int flags; /* saved flags */
  1444. const char *text; /* saved text */
  1445. };
  1446. /* Forward decls for varinit[] */
  1447. #if ENABLE_LOCALE_SUPPORT
  1448. static void
  1449. change_lc_all(const char *value)
  1450. {
  1451. if (value && *value != '\0')
  1452. setlocale(LC_ALL, value);
  1453. }
  1454. static void
  1455. change_lc_ctype(const char *value)
  1456. {
  1457. if (value && *value != '\0')
  1458. setlocale(LC_CTYPE, value);
  1459. }
  1460. #endif
  1461. #if ENABLE_ASH_MAIL
  1462. static void chkmail(void);
  1463. static void changemail(const char *);
  1464. #endif
  1465. static void changepath(const char *);
  1466. #if ENABLE_ASH_RANDOM_SUPPORT
  1467. static void change_random(const char *);
  1468. #endif
  1469. static struct var varinit[] = {
  1470. #ifdef IFS_BROKEN
  1471. { NULL, VSTRFIXED|VTEXTFIXED, defifsvar, NULL },
  1472. #else
  1473. { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", NULL },
  1474. #endif
  1475. #if ENABLE_ASH_MAIL
  1476. { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
  1477. { NULL, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1478. #endif
  1479. { NULL, VSTRFIXED|VTEXTFIXED, bb_PATH_root_path, changepath },
  1480. { NULL, VSTRFIXED|VTEXTFIXED, "PS1=$ ", NULL },
  1481. { NULL, VSTRFIXED|VTEXTFIXED, "PS2=> ", NULL },
  1482. { NULL, VSTRFIXED|VTEXTFIXED, "PS4=+ ", NULL },
  1483. #if ENABLE_ASH_GETOPTS
  1484. { NULL, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
  1485. #endif
  1486. #if ENABLE_ASH_RANDOM_SUPPORT
  1487. { NULL, VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1488. #endif
  1489. #if ENABLE_LOCALE_SUPPORT
  1490. { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL\0", change_lc_all },
  1491. { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1492. #endif
  1493. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1494. { NULL, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE\0", NULL },
  1495. #endif
  1496. };
  1497. #define vifs varinit[0]
  1498. #if ENABLE_ASH_MAIL
  1499. #define vmail (&vifs)[1]
  1500. #define vmpath (&vmail)[1]
  1501. #else
  1502. #define vmpath vifs
  1503. #endif
  1504. #define vpath (&vmpath)[1]
  1505. #define vps1 (&vpath)[1]
  1506. #define vps2 (&vps1)[1]
  1507. #define vps4 (&vps2)[1]
  1508. #define voptind (&vps4)[1]
  1509. #if ENABLE_ASH_GETOPTS
  1510. #define vrandom (&voptind)[1]
  1511. #else
  1512. #define vrandom (&vps4)[1]
  1513. #endif
  1514. /*
  1515. * The following macros access the values of the above variables.
  1516. * They have to skip over the name. They return the null string
  1517. * for unset variables.
  1518. */
  1519. #define ifsval() (vifs.text + 4)
  1520. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1521. #define mailval() (vmail.text + 5)
  1522. #define mpathval() (vmpath.text + 9)
  1523. #define pathval() (vpath.text + 5)
  1524. #define ps1val() (vps1.text + 4)
  1525. #define ps2val() (vps2.text + 4)
  1526. #define ps4val() (vps4.text + 4)
  1527. #define optindval() (voptind.text + 7)
  1528. #define mpathset() ((vmpath.flags & VUNSET) == 0)
  1529. /*
  1530. * The parsefile structure pointed to by the global variable parsefile
  1531. * contains information about the current file being read.
  1532. */
  1533. struct redirtab {
  1534. struct redirtab *next;
  1535. int renamed[10];
  1536. int nullredirs;
  1537. };
  1538. static struct redirtab *redirlist;
  1539. static int nullredirs;
  1540. static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1541. #define VTABSIZE 39
  1542. static struct var *vartab[VTABSIZE];
  1543. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1544. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1545. /*
  1546. * Return of a legal variable name (a letter or underscore followed by zero or
  1547. * more letters, underscores, and digits).
  1548. */
  1549. static char *
  1550. endofname(const char *name)
  1551. {
  1552. char *p;
  1553. p = (char *) name;
  1554. if (!is_name(*p))
  1555. return p;
  1556. while (*++p) {
  1557. if (!is_in_name(*p))
  1558. break;
  1559. }
  1560. return p;
  1561. }
  1562. /*
  1563. * Compares two strings up to the first = or '\0'. The first
  1564. * string must be terminated by '='; the second may be terminated by
  1565. * either '=' or '\0'.
  1566. */
  1567. static int
  1568. varcmp(const char *p, const char *q)
  1569. {
  1570. int c, d;
  1571. while ((c = *p) == (d = *q)) {
  1572. if (!c || c == '=')
  1573. goto out;
  1574. p++;
  1575. q++;
  1576. }
  1577. if (c == '=')
  1578. c = '\0';
  1579. if (d == '=')
  1580. d = '\0';
  1581. out:
  1582. return c - d;
  1583. }
  1584. static int
  1585. varequal(const char *a, const char *b)
  1586. {
  1587. return !varcmp(a, b);
  1588. }
  1589. /*
  1590. * Find the appropriate entry in the hash table from the name.
  1591. */
  1592. static struct var **
  1593. hashvar(const char *p)
  1594. {
  1595. unsigned hashval;
  1596. hashval = ((unsigned char) *p) << 4;
  1597. while (*p && *p != '=')
  1598. hashval += (unsigned char) *p++;
  1599. return &vartab[hashval % VTABSIZE];
  1600. }
  1601. static int
  1602. vpcmp(const void *a, const void *b)
  1603. {
  1604. return varcmp(*(const char **)a, *(const char **)b);
  1605. }
  1606. /*
  1607. * This routine initializes the builtin variables.
  1608. */
  1609. static void
  1610. initvar(void)
  1611. {
  1612. struct var *vp;
  1613. struct var *end;
  1614. struct var **vpp;
  1615. /*
  1616. * PS1 depends on uid
  1617. */
  1618. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1619. vps1.text = "PS1=\\w \\$ ";
  1620. #else
  1621. if (!geteuid())
  1622. vps1.text = "PS1=# ";
  1623. #endif
  1624. vp = varinit;
  1625. end = vp + ARRAY_SIZE(varinit);
  1626. do {
  1627. vpp = hashvar(vp->text);
  1628. vp->next = *vpp;
  1629. *vpp = vp;
  1630. } while (++vp < end);
  1631. }
  1632. static struct var **
  1633. findvar(struct var **vpp, const char *name)
  1634. {
  1635. for (; *vpp; vpp = &(*vpp)->next) {
  1636. if (varequal((*vpp)->text, name)) {
  1637. break;
  1638. }
  1639. }
  1640. return vpp;
  1641. }
  1642. /*
  1643. * Find the value of a variable. Returns NULL if not set.
  1644. */
  1645. static char *
  1646. lookupvar(const char *name)
  1647. {
  1648. struct var *v;
  1649. v = *findvar(hashvar(name), name);
  1650. if (v) {
  1651. #ifdef DYNAMIC_VAR
  1652. /*
  1653. * Dynamic variables are implemented roughly the same way they are
  1654. * in bash. Namely, they're "special" so long as they aren't unset.
  1655. * As soon as they're unset, they're no longer dynamic, and dynamic
  1656. * lookup will no longer happen at that point. -- PFM.
  1657. */
  1658. if ((v->flags & VDYNAMIC))
  1659. (*v->func)(NULL);
  1660. #endif
  1661. if (!(v->flags & VUNSET))
  1662. return strchrnul(v->text, '=') + 1;
  1663. }
  1664. return NULL;
  1665. }
  1666. /*
  1667. * Search the environment of a builtin command.
  1668. */
  1669. static char *
  1670. bltinlookup(const char *name)
  1671. {
  1672. struct strlist *sp;
  1673. for (sp = cmdenviron; sp; sp = sp->next) {
  1674. if (varequal(sp->text, name))
  1675. return strchrnul(sp->text, '=') + 1;
  1676. }
  1677. return lookupvar(name);
  1678. }
  1679. /*
  1680. * Same as setvar except that the variable and value are passed in
  1681. * the first argument as name=value. Since the first argument will
  1682. * be actually stored in the table, it should not be a string that
  1683. * will go away.
  1684. * Called with interrupts off.
  1685. */
  1686. static void
  1687. setvareq(char *s, int flags)
  1688. {
  1689. struct var *vp, **vpp;
  1690. vpp = hashvar(s);
  1691. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1692. vp = *findvar(vpp, s);
  1693. if (vp) {
  1694. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1695. const char *n;
  1696. if (flags & VNOSAVE)
  1697. free(s);
  1698. n = vp->text;
  1699. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1700. }
  1701. if (flags & VNOSET)
  1702. return;
  1703. if (vp->func && (flags & VNOFUNC) == 0)
  1704. (*vp->func)(strchrnul(s, '=') + 1);
  1705. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1706. free((char*)vp->text);
  1707. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1708. } else {
  1709. if (flags & VNOSET)
  1710. return;
  1711. /* not found */
  1712. vp = ckmalloc(sizeof(*vp));
  1713. vp->next = *vpp;
  1714. vp->func = NULL;
  1715. *vpp = vp;
  1716. }
  1717. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1718. s = ckstrdup(s);
  1719. vp->text = s;
  1720. vp->flags = flags;
  1721. }
  1722. /*
  1723. * Set the value of a variable. The flags argument is ored with the
  1724. * flags of the variable. If val is NULL, the variable is unset.
  1725. */
  1726. static void
  1727. setvar(const char *name, const char *val, int flags)
  1728. {
  1729. char *p, *q;
  1730. size_t namelen;
  1731. char *nameeq;
  1732. size_t vallen;
  1733. q = endofname(name);
  1734. p = strchrnul(q, '=');
  1735. namelen = p - name;
  1736. if (!namelen || p != q)
  1737. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1738. vallen = 0;
  1739. if (val == NULL) {
  1740. flags |= VUNSET;
  1741. } else {
  1742. vallen = strlen(val);
  1743. }
  1744. INT_OFF;
  1745. nameeq = ckmalloc(namelen + vallen + 2);
  1746. p = memcpy(nameeq, name, namelen) + namelen;
  1747. if (val) {
  1748. *p++ = '=';
  1749. p = memcpy(p, val, vallen) + vallen;
  1750. }
  1751. *p = '\0';
  1752. setvareq(nameeq, flags | VNOSAVE);
  1753. INT_ON;
  1754. }
  1755. #if ENABLE_ASH_GETOPTS
  1756. /*
  1757. * Safe version of setvar, returns 1 on success 0 on failure.
  1758. */
  1759. static int
  1760. setvarsafe(const char *name, const char *val, int flags)
  1761. {
  1762. int err;
  1763. volatile int saveint;
  1764. struct jmploc *volatile savehandler = exception_handler;
  1765. struct jmploc jmploc;
  1766. SAVE_INT(saveint);
  1767. if (setjmp(jmploc.loc))
  1768. err = 1;
  1769. else {
  1770. exception_handler = &jmploc;
  1771. setvar(name, val, flags);
  1772. err = 0;
  1773. }
  1774. exception_handler = savehandler;
  1775. RESTORE_INT(saveint);
  1776. return err;
  1777. }
  1778. #endif
  1779. /*
  1780. * Unset the specified variable.
  1781. */
  1782. static int
  1783. unsetvar(const char *s)
  1784. {
  1785. struct var **vpp;
  1786. struct var *vp;
  1787. int retval;
  1788. vpp = findvar(hashvar(s), s);
  1789. vp = *vpp;
  1790. retval = 2;
  1791. if (vp) {
  1792. int flags = vp->flags;
  1793. retval = 1;
  1794. if (flags & VREADONLY)
  1795. goto out;
  1796. #ifdef DYNAMIC_VAR
  1797. vp->flags &= ~VDYNAMIC;
  1798. #endif
  1799. if (flags & VUNSET)
  1800. goto ok;
  1801. if ((flags & VSTRFIXED) == 0) {
  1802. INT_OFF;
  1803. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1804. free((char*)vp->text);
  1805. *vpp = vp->next;
  1806. free(vp);
  1807. INT_ON;
  1808. } else {
  1809. setvar(s, 0, 0);
  1810. vp->flags &= ~VEXPORT;
  1811. }
  1812. ok:
  1813. retval = 0;
  1814. }
  1815. out:
  1816. return retval;
  1817. }
  1818. /*
  1819. * Process a linked list of variable assignments.
  1820. */
  1821. static void
  1822. listsetvar(struct strlist *list_set_var, int flags)
  1823. {
  1824. struct strlist *lp = list_set_var;
  1825. if (!lp)
  1826. return;
  1827. INT_OFF;
  1828. do {
  1829. setvareq(lp->text, flags);
  1830. lp = lp->next;
  1831. } while (lp);
  1832. INT_ON;
  1833. }
  1834. /*
  1835. * Generate a list of variables satisfying the given conditions.
  1836. */
  1837. static char **
  1838. listvars(int on, int off, char ***end)
  1839. {
  1840. struct var **vpp;
  1841. struct var *vp;
  1842. char **ep;
  1843. int mask;
  1844. STARTSTACKSTR(ep);
  1845. vpp = vartab;
  1846. mask = on | off;
  1847. do {
  1848. for (vp = *vpp; vp; vp = vp->next) {
  1849. if ((vp->flags & mask) == on) {
  1850. if (ep == stackstrend())
  1851. ep = growstackstr();
  1852. *ep++ = (char *) vp->text;
  1853. }
  1854. }
  1855. } while (++vpp < vartab + VTABSIZE);
  1856. if (ep == stackstrend())
  1857. ep = growstackstr();
  1858. if (end)
  1859. *end = ep;
  1860. *ep++ = NULL;
  1861. return grabstackstr(ep);
  1862. }
  1863. /* ============ Path search helper
  1864. *
  1865. * The variable path (passed by reference) should be set to the start
  1866. * of the path before the first call; padvance will update
  1867. * this value as it proceeds. Successive calls to padvance will return
  1868. * the possible path expansions in sequence. If an option (indicated by
  1869. * a percent sign) appears in the path entry then the global variable
  1870. * pathopt will be set to point to it; otherwise pathopt will be set to
  1871. * NULL.
  1872. */
  1873. static const char *pathopt; /* set by padvance */
  1874. static char *
  1875. padvance(const char **path, const char *name)
  1876. {
  1877. const char *p;
  1878. char *q;
  1879. const char *start;
  1880. size_t len;
  1881. if (*path == NULL)
  1882. return NULL;
  1883. start = *path;
  1884. for (p = start; *p && *p != ':' && *p != '%'; p++);
  1885. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  1886. while (stackblocksize() < len)
  1887. growstackblock();
  1888. q = stackblock();
  1889. if (p != start) {
  1890. memcpy(q, start, p - start);
  1891. q += p - start;
  1892. *q++ = '/';
  1893. }
  1894. strcpy(q, name);
  1895. pathopt = NULL;
  1896. if (*p == '%') {
  1897. pathopt = ++p;
  1898. while (*p && *p != ':') p++;
  1899. }
  1900. if (*p == ':')
  1901. *path = p + 1;
  1902. else
  1903. *path = NULL;
  1904. return stalloc(len);
  1905. }
  1906. /* ============ Prompt */
  1907. static smallint doprompt; /* if set, prompt the user */
  1908. static smallint needprompt; /* true if interactive and at start of line */
  1909. #if ENABLE_FEATURE_EDITING
  1910. static line_input_t *line_input_state;
  1911. static const char *cmdedit_prompt;
  1912. static void
  1913. putprompt(const char *s)
  1914. {
  1915. if (ENABLE_ASH_EXPAND_PRMT) {
  1916. free((char*)cmdedit_prompt);
  1917. cmdedit_prompt = ckstrdup(s);
  1918. return;
  1919. }
  1920. cmdedit_prompt = s;
  1921. }
  1922. #else
  1923. static void
  1924. putprompt(const char *s)
  1925. {
  1926. out2str(s);
  1927. }
  1928. #endif
  1929. #if ENABLE_ASH_EXPAND_PRMT
  1930. /* expandstr() needs parsing machinery, so it is far away ahead... */
  1931. static const char *expandstr(const char *ps);
  1932. #else
  1933. #define expandstr(s) s
  1934. #endif
  1935. static void
  1936. setprompt(int whichprompt)
  1937. {
  1938. const char *prompt;
  1939. #if ENABLE_ASH_EXPAND_PRMT
  1940. struct stackmark smark;
  1941. #endif
  1942. needprompt = 0;
  1943. switch (whichprompt) {
  1944. case 1:
  1945. prompt = ps1val();
  1946. break;
  1947. case 2:
  1948. prompt = ps2val();
  1949. break;
  1950. default: /* 0 */
  1951. prompt = nullstr;
  1952. }
  1953. #if ENABLE_ASH_EXPAND_PRMT
  1954. setstackmark(&smark);
  1955. stalloc(stackblocksize());
  1956. #endif
  1957. putprompt(expandstr(prompt));
  1958. #if ENABLE_ASH_EXPAND_PRMT
  1959. popstackmark(&smark);
  1960. #endif
  1961. }
  1962. /* ============ The cd and pwd commands */
  1963. #define CD_PHYSICAL 1
  1964. #define CD_PRINT 2
  1965. static int docd(const char *, int);
  1966. static char *curdir = nullstr; /* current working directory */
  1967. static char *physdir = nullstr; /* physical working directory */
  1968. static int
  1969. cdopt(void)
  1970. {
  1971. int flags = 0;
  1972. int i, j;
  1973. j = 'L';
  1974. while ((i = nextopt("LP"))) {
  1975. if (i != j) {
  1976. flags ^= CD_PHYSICAL;
  1977. j = i;
  1978. }
  1979. }
  1980. return flags;
  1981. }
  1982. /*
  1983. * Update curdir (the name of the current directory) in response to a
  1984. * cd command.
  1985. */
  1986. static const char *
  1987. updatepwd(const char *dir)
  1988. {
  1989. char *new;
  1990. char *p;
  1991. char *cdcomppath;
  1992. const char *lim;
  1993. cdcomppath = ststrdup(dir);
  1994. STARTSTACKSTR(new);
  1995. if (*dir != '/') {
  1996. if (curdir == nullstr)
  1997. return 0;
  1998. new = stack_putstr(curdir, new);
  1999. }
  2000. new = makestrspace(strlen(dir) + 2, new);
  2001. lim = stackblock() + 1;
  2002. if (*dir != '/') {
  2003. if (new[-1] != '/')
  2004. USTPUTC('/', new);
  2005. if (new > lim && *lim == '/')
  2006. lim++;
  2007. } else {
  2008. USTPUTC('/', new);
  2009. cdcomppath++;
  2010. if (dir[1] == '/' && dir[2] != '/') {
  2011. USTPUTC('/', new);
  2012. cdcomppath++;
  2013. lim++;
  2014. }
  2015. }
  2016. p = strtok(cdcomppath, "/");
  2017. while (p) {
  2018. switch (*p) {
  2019. case '.':
  2020. if (p[1] == '.' && p[2] == '\0') {
  2021. while (new > lim) {
  2022. STUNPUTC(new);
  2023. if (new[-1] == '/')
  2024. break;
  2025. }
  2026. break;
  2027. }
  2028. if (p[1] == '\0')
  2029. break;
  2030. /* fall through */
  2031. default:
  2032. new = stack_putstr(p, new);
  2033. USTPUTC('/', new);
  2034. }
  2035. p = strtok(0, "/");
  2036. }
  2037. if (new > lim)
  2038. STUNPUTC(new);
  2039. *new = 0;
  2040. return stackblock();
  2041. }
  2042. /*
  2043. * Find out what the current directory is. If we already know the current
  2044. * directory, this routine returns immediately.
  2045. */
  2046. static char *
  2047. getpwd(void)
  2048. {
  2049. char *dir = getcwd(0, 0);
  2050. return dir ? dir : nullstr;
  2051. }
  2052. static void
  2053. setpwd(const char *val, int setold)
  2054. {
  2055. char *oldcur, *dir;
  2056. oldcur = dir = curdir;
  2057. if (setold) {
  2058. setvar("OLDPWD", oldcur, VEXPORT);
  2059. }
  2060. INT_OFF;
  2061. if (physdir != nullstr) {
  2062. if (physdir != oldcur)
  2063. free(physdir);
  2064. physdir = nullstr;
  2065. }
  2066. if (oldcur == val || !val) {
  2067. char *s = getpwd();
  2068. physdir = s;
  2069. if (!val)
  2070. dir = s;
  2071. } else
  2072. dir = ckstrdup(val);
  2073. if (oldcur != dir && oldcur != nullstr) {
  2074. free(oldcur);
  2075. }
  2076. curdir = dir;
  2077. INT_ON;
  2078. setvar("PWD", dir, VEXPORT);
  2079. }
  2080. static void hashcd(void);
  2081. /*
  2082. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2083. * know that the current directory has changed.
  2084. */
  2085. static int
  2086. docd(const char *dest, int flags)
  2087. {
  2088. const char *dir = 0;
  2089. int err;
  2090. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2091. INT_OFF;
  2092. if (!(flags & CD_PHYSICAL)) {
  2093. dir = updatepwd(dest);
  2094. if (dir)
  2095. dest = dir;
  2096. }
  2097. err = chdir(dest);
  2098. if (err)
  2099. goto out;
  2100. setpwd(dir, 1);
  2101. hashcd();
  2102. out:
  2103. INT_ON;
  2104. return err;
  2105. }
  2106. static int
  2107. cdcmd(int argc, char **argv)
  2108. {
  2109. const char *dest;
  2110. const char *path;
  2111. const char *p;
  2112. char c;
  2113. struct stat statb;
  2114. int flags;
  2115. flags = cdopt();
  2116. dest = *argptr;
  2117. if (!dest)
  2118. dest = bltinlookup(homestr);
  2119. else if (LONE_DASH(dest)) {
  2120. dest = bltinlookup("OLDPWD");
  2121. flags |= CD_PRINT;
  2122. }
  2123. if (!dest)
  2124. dest = nullstr;
  2125. if (*dest == '/')
  2126. goto step7;
  2127. if (*dest == '.') {
  2128. c = dest[1];
  2129. dotdot:
  2130. switch (c) {
  2131. case '\0':
  2132. case '/':
  2133. goto step6;
  2134. case '.':
  2135. c = dest[2];
  2136. if (c != '.')
  2137. goto dotdot;
  2138. }
  2139. }
  2140. if (!*dest)
  2141. dest = ".";
  2142. path = bltinlookup("CDPATH");
  2143. if (!path) {
  2144. step6:
  2145. step7:
  2146. p = dest;
  2147. goto docd;
  2148. }
  2149. do {
  2150. c = *path;
  2151. p = padvance(&path, dest);
  2152. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2153. if (c && c != ':')
  2154. flags |= CD_PRINT;
  2155. docd:
  2156. if (!docd(p, flags))
  2157. goto out;
  2158. break;
  2159. }
  2160. } while (path);
  2161. ash_msg_and_raise_error("can't cd to %s", dest);
  2162. /* NOTREACHED */
  2163. out:
  2164. if (flags & CD_PRINT)
  2165. out1fmt(snlfmt, curdir);
  2166. return 0;
  2167. }
  2168. static int
  2169. pwdcmd(int argc, char **argv)
  2170. {
  2171. int flags;
  2172. const char *dir = curdir;
  2173. flags = cdopt();
  2174. if (flags) {
  2175. if (physdir == nullstr)
  2176. setpwd(dir, 0);
  2177. dir = physdir;
  2178. }
  2179. out1fmt(snlfmt, dir);
  2180. return 0;
  2181. }
  2182. /* ============ ... */
  2183. #define IBUFSIZ COMMON_BUFSIZE
  2184. #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
  2185. /* Syntax classes */
  2186. #define CWORD 0 /* character is nothing special */
  2187. #define CNL 1 /* newline character */
  2188. #define CBACK 2 /* a backslash character */
  2189. #define CSQUOTE 3 /* single quote */
  2190. #define CDQUOTE 4 /* double quote */
  2191. #define CENDQUOTE 5 /* a terminating quote */
  2192. #define CBQUOTE 6 /* backwards single quote */
  2193. #define CVAR 7 /* a dollar sign */
  2194. #define CENDVAR 8 /* a '}' character */
  2195. #define CLP 9 /* a left paren in arithmetic */
  2196. #define CRP 10 /* a right paren in arithmetic */
  2197. #define CENDFILE 11 /* end of file */
  2198. #define CCTL 12 /* like CWORD, except it must be escaped */
  2199. #define CSPCL 13 /* these terminate a word */
  2200. #define CIGN 14 /* character should be ignored */
  2201. #if ENABLE_ASH_ALIAS
  2202. #define SYNBASE 130
  2203. #define PEOF -130
  2204. #define PEOA -129
  2205. #define PEOA_OR_PEOF PEOA
  2206. #else
  2207. #define SYNBASE 129
  2208. #define PEOF -129
  2209. #define PEOA_OR_PEOF PEOF
  2210. #endif
  2211. /* number syntax index */
  2212. #define BASESYNTAX 0 /* not in quotes */
  2213. #define DQSYNTAX 1 /* in double quotes */
  2214. #define SQSYNTAX 2 /* in single quotes */
  2215. #define ARISYNTAX 3 /* in arithmetic */
  2216. #define PSSYNTAX 4 /* prompt */
  2217. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2218. #define USE_SIT_FUNCTION
  2219. #endif
  2220. #if ENABLE_ASH_MATH_SUPPORT
  2221. static const char S_I_T[][4] = {
  2222. #if ENABLE_ASH_ALIAS
  2223. { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
  2224. #endif
  2225. { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
  2226. { CNL, CNL, CNL, CNL }, /* 2, \n */
  2227. { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
  2228. { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
  2229. { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
  2230. { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
  2231. { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
  2232. { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
  2233. { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
  2234. { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
  2235. { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
  2236. #ifndef USE_SIT_FUNCTION
  2237. { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2238. { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2239. { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2240. #endif
  2241. };
  2242. #else
  2243. static const char S_I_T[][3] = {
  2244. #if ENABLE_ASH_ALIAS
  2245. { CSPCL, CIGN, CIGN }, /* 0, PEOA */
  2246. #endif
  2247. { CSPCL, CWORD, CWORD }, /* 1, ' ' */
  2248. { CNL, CNL, CNL }, /* 2, \n */
  2249. { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
  2250. { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
  2251. { CVAR, CVAR, CWORD }, /* 5, $ */
  2252. { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
  2253. { CSPCL, CWORD, CWORD }, /* 7, ( */
  2254. { CSPCL, CWORD, CWORD }, /* 8, ) */
  2255. { CBACK, CBACK, CCTL }, /* 9, \ */
  2256. { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
  2257. { CENDVAR, CENDVAR, CWORD }, /* 11, } */
  2258. #ifndef USE_SIT_FUNCTION
  2259. { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2260. { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2261. { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2262. #endif
  2263. };
  2264. #endif /* ASH_MATH_SUPPORT */
  2265. #ifdef USE_SIT_FUNCTION
  2266. static int
  2267. SIT(int c, int syntax)
  2268. {
  2269. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2270. #if ENABLE_ASH_ALIAS
  2271. static const char syntax_index_table[] ALIGN1 = {
  2272. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2273. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2274. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2275. 11, 3 /* "}~" */
  2276. };
  2277. #else
  2278. static const char syntax_index_table[] ALIGN1 = {
  2279. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2280. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2281. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2282. 10, 2 /* "}~" */
  2283. };
  2284. #endif
  2285. const char *s;
  2286. int indx;
  2287. if (c == PEOF) /* 2^8+2 */
  2288. return CENDFILE;
  2289. #if ENABLE_ASH_ALIAS
  2290. if (c == PEOA) /* 2^8+1 */
  2291. indx = 0;
  2292. else
  2293. #endif
  2294. #define U_C(c) ((unsigned char)(c))
  2295. if ((unsigned char)c >= (unsigned char)(CTLESC)
  2296. && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
  2297. ) {
  2298. return CCTL;
  2299. } else {
  2300. s = strchr(spec_symbls, c);
  2301. if (s == NULL || *s == '\0')
  2302. return CWORD;
  2303. indx = syntax_index_table[(s - spec_symbls)];
  2304. }
  2305. return S_I_T[indx][syntax];
  2306. }
  2307. #else /* !USE_SIT_FUNCTION */
  2308. #if ENABLE_ASH_ALIAS
  2309. #define CSPCL_CIGN_CIGN_CIGN 0
  2310. #define CSPCL_CWORD_CWORD_CWORD 1
  2311. #define CNL_CNL_CNL_CNL 2
  2312. #define CWORD_CCTL_CCTL_CWORD 3
  2313. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  2314. #define CVAR_CVAR_CWORD_CVAR 5
  2315. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  2316. #define CSPCL_CWORD_CWORD_CLP 7
  2317. #define CSPCL_CWORD_CWORD_CRP 8
  2318. #define CBACK_CBACK_CCTL_CBACK 9
  2319. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  2320. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  2321. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  2322. #define CWORD_CWORD_CWORD_CWORD 13
  2323. #define CCTL_CCTL_CCTL_CCTL 14
  2324. #else
  2325. #define CSPCL_CWORD_CWORD_CWORD 0
  2326. #define CNL_CNL_CNL_CNL 1
  2327. #define CWORD_CCTL_CCTL_CWORD 2
  2328. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  2329. #define CVAR_CVAR_CWORD_CVAR 4
  2330. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  2331. #define CSPCL_CWORD_CWORD_CLP 6
  2332. #define CSPCL_CWORD_CWORD_CRP 7
  2333. #define CBACK_CBACK_CCTL_CBACK 8
  2334. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  2335. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  2336. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  2337. #define CWORD_CWORD_CWORD_CWORD 12
  2338. #define CCTL_CCTL_CCTL_CCTL 13
  2339. #endif
  2340. static const char syntax_index_table[258] = {
  2341. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2342. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2343. #if ENABLE_ASH_ALIAS
  2344. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2345. #endif
  2346. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2347. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2348. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2349. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2350. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2351. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2352. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2353. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2354. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2355. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  2356. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  2357. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  2358. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  2359. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  2360. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  2361. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  2362. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  2363. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  2364. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  2365. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  2366. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  2367. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  2368. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  2369. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  2370. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  2371. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  2372. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  2373. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  2374. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  2375. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  2376. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  2377. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  2378. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  2379. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  2380. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  2381. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  2382. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  2383. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  2384. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  2385. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  2386. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  2387. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  2388. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  2389. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  2390. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  2391. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  2392. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  2393. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  2394. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  2395. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  2396. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  2397. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  2398. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  2399. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  2400. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  2401. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  2402. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  2403. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  2404. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  2405. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  2406. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  2407. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  2408. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  2409. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  2410. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  2411. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  2412. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  2413. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  2414. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  2415. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  2416. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  2417. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  2418. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  2419. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  2420. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  2421. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  2422. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  2423. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  2424. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  2425. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  2426. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  2427. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  2428. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  2429. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  2430. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  2431. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  2432. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  2433. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  2434. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  2435. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  2436. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  2437. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  2438. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  2439. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  2440. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  2441. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  2442. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  2443. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  2444. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  2445. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  2446. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  2447. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  2448. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  2449. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  2450. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  2451. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  2452. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  2453. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  2454. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  2455. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  2456. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  2457. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  2458. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  2459. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  2460. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  2461. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  2462. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  2463. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  2464. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  2465. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  2466. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  2467. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  2468. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  2469. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  2470. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  2471. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  2472. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  2473. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  2474. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  2475. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  2476. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  2477. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  2478. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  2479. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  2480. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  2481. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  2482. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  2483. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2484. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  2485. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  2486. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  2487. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  2488. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  2489. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  2490. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  2491. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  2492. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  2493. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  2495. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  2496. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  2497. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  2498. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  2499. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  2500. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  2501. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  2502. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2507. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2508. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2509. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2511. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2513. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2514. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2515. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2516. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2517. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2520. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2522. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2528. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2529. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2530. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2531. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2533. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2534. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2535. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2536. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2537. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2538. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2566. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2567. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2568. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2571. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2573. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2574. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2596. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2597. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2598. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2599. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2600. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2601. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  2602. };
  2603. #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
  2604. #endif /* USE_SIT_FUNCTION */
  2605. /* ============ Alias handling */
  2606. #if ENABLE_ASH_ALIAS
  2607. #define ALIASINUSE 1
  2608. #define ALIASDEAD 2
  2609. #define ATABSIZE 39
  2610. struct alias {
  2611. struct alias *next;
  2612. char *name;
  2613. char *val;
  2614. int flag;
  2615. };
  2616. static struct alias *atab[ATABSIZE];
  2617. static struct alias **
  2618. __lookupalias(const char *name) {
  2619. unsigned int hashval;
  2620. struct alias **app;
  2621. const char *p;
  2622. unsigned int ch;
  2623. p = name;
  2624. ch = (unsigned char)*p;
  2625. hashval = ch << 4;
  2626. while (ch) {
  2627. hashval += ch;
  2628. ch = (unsigned char)*++p;
  2629. }
  2630. app = &atab[hashval % ATABSIZE];
  2631. for (; *app; app = &(*app)->next) {
  2632. if (strcmp(name, (*app)->name) == 0) {
  2633. break;
  2634. }
  2635. }
  2636. return app;
  2637. }
  2638. static struct alias *
  2639. lookupalias(const char *name, int check)
  2640. {
  2641. struct alias *ap = *__lookupalias(name);
  2642. if (check && ap && (ap->flag & ALIASINUSE))
  2643. return NULL;
  2644. return ap;
  2645. }
  2646. static struct alias *
  2647. freealias(struct alias *ap)
  2648. {
  2649. struct alias *next;
  2650. if (ap->flag & ALIASINUSE) {
  2651. ap->flag |= ALIASDEAD;
  2652. return ap;
  2653. }
  2654. next = ap->next;
  2655. free(ap->name);
  2656. free(ap->val);
  2657. free(ap);
  2658. return next;
  2659. }
  2660. static void
  2661. setalias(const char *name, const char *val)
  2662. {
  2663. struct alias *ap, **app;
  2664. app = __lookupalias(name);
  2665. ap = *app;
  2666. INT_OFF;
  2667. if (ap) {
  2668. if (!(ap->flag & ALIASINUSE)) {
  2669. free(ap->val);
  2670. }
  2671. ap->val = ckstrdup(val);
  2672. ap->flag &= ~ALIASDEAD;
  2673. } else {
  2674. /* not found */
  2675. ap = ckmalloc(sizeof(struct alias));
  2676. ap->name = ckstrdup(name);
  2677. ap->val = ckstrdup(val);
  2678. ap->flag = 0;
  2679. ap->next = 0;
  2680. *app = ap;
  2681. }
  2682. INT_ON;
  2683. }
  2684. static int
  2685. unalias(const char *name)
  2686. {
  2687. struct alias **app;
  2688. app = __lookupalias(name);
  2689. if (*app) {
  2690. INT_OFF;
  2691. *app = freealias(*app);
  2692. INT_ON;
  2693. return 0;
  2694. }
  2695. return 1;
  2696. }
  2697. static void
  2698. rmaliases(void)
  2699. {
  2700. struct alias *ap, **app;
  2701. int i;
  2702. INT_OFF;
  2703. for (i = 0; i < ATABSIZE; i++) {
  2704. app = &atab[i];
  2705. for (ap = *app; ap; ap = *app) {
  2706. *app = freealias(*app);
  2707. if (ap == *app) {
  2708. app = &ap->next;
  2709. }
  2710. }
  2711. }
  2712. INT_ON;
  2713. }
  2714. static void
  2715. printalias(const struct alias *ap)
  2716. {
  2717. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2718. }
  2719. /*
  2720. * TODO - sort output
  2721. */
  2722. static int
  2723. aliascmd(int argc, char **argv)
  2724. {
  2725. char *n, *v;
  2726. int ret = 0;
  2727. struct alias *ap;
  2728. if (argc == 1) {
  2729. int i;
  2730. for (i = 0; i < ATABSIZE; i++)
  2731. for (ap = atab[i]; ap; ap = ap->next) {
  2732. printalias(ap);
  2733. }
  2734. return 0;
  2735. }
  2736. while ((n = *++argv) != NULL) {
  2737. v = strchr(n+1, '=');
  2738. if (v == NULL) { /* n+1: funny ksh stuff */
  2739. ap = *__lookupalias(n);
  2740. if (ap == NULL) {
  2741. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2742. ret = 1;
  2743. } else
  2744. printalias(ap);
  2745. } else {
  2746. *v++ = '\0';
  2747. setalias(n, v);
  2748. }
  2749. }
  2750. return ret;
  2751. }
  2752. static int
  2753. unaliascmd(int argc, char **argv)
  2754. {
  2755. int i;
  2756. while ((i = nextopt("a")) != '\0') {
  2757. if (i == 'a') {
  2758. rmaliases();
  2759. return 0;
  2760. }
  2761. }
  2762. for (i = 0; *argptr; argptr++) {
  2763. if (unalias(*argptr)) {
  2764. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2765. i = 1;
  2766. }
  2767. }
  2768. return i;
  2769. }
  2770. #endif /* ASH_ALIAS */
  2771. /* ============ jobs.c */
  2772. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2773. #define FORK_FG 0
  2774. #define FORK_BG 1
  2775. #define FORK_NOJOB 2
  2776. /* mode flags for showjob(s) */
  2777. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  2778. #define SHOW_PID 0x04 /* include process pid */
  2779. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  2780. /*
  2781. * A job structure contains information about a job. A job is either a
  2782. * single process or a set of processes contained in a pipeline. In the
  2783. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2784. * array of pids.
  2785. */
  2786. struct procstat {
  2787. pid_t pid; /* process id */
  2788. int status; /* last process status from wait() */
  2789. char *cmd; /* text of command being run */
  2790. };
  2791. struct job {
  2792. struct procstat ps0; /* status of process */
  2793. struct procstat *ps; /* status or processes when more than one */
  2794. #if JOBS
  2795. int stopstatus; /* status of a stopped job */
  2796. #endif
  2797. uint32_t
  2798. nprocs: 16, /* number of processes */
  2799. state: 8,
  2800. #define JOBRUNNING 0 /* at least one proc running */
  2801. #define JOBSTOPPED 1 /* all procs are stopped */
  2802. #define JOBDONE 2 /* all procs are completed */
  2803. #if JOBS
  2804. sigint: 1, /* job was killed by SIGINT */
  2805. jobctl: 1, /* job running under job control */
  2806. #endif
  2807. waited: 1, /* true if this entry has been waited for */
  2808. used: 1, /* true if this entry is in used */
  2809. changed: 1; /* true if status has changed */
  2810. struct job *prev_job; /* previous job */
  2811. };
  2812. static pid_t backgndpid; /* pid of last background process */
  2813. static smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  2814. static struct job *makejob(union node *, int);
  2815. static int forkshell(struct job *, union node *, int);
  2816. static int waitforjob(struct job *);
  2817. #if !JOBS
  2818. enum { jobctl = 0 };
  2819. #define setjobctl(on) do {} while (0)
  2820. #else
  2821. static smallint jobctl; /* true if doing job control */
  2822. static void setjobctl(int);
  2823. #endif
  2824. /*
  2825. * Set the signal handler for the specified signal. The routine figures
  2826. * out what it should be set to.
  2827. */
  2828. static void
  2829. setsignal(int signo)
  2830. {
  2831. int action;
  2832. char *t, tsig;
  2833. struct sigaction act;
  2834. t = trap[signo];
  2835. if (t == NULL)
  2836. action = S_DFL;
  2837. else if (*t != '\0')
  2838. action = S_CATCH;
  2839. else
  2840. action = S_IGN;
  2841. if (rootshell && action == S_DFL) {
  2842. switch (signo) {
  2843. case SIGINT:
  2844. if (iflag || minusc || sflag == 0)
  2845. action = S_CATCH;
  2846. break;
  2847. case SIGQUIT:
  2848. #if DEBUG
  2849. if (debug)
  2850. break;
  2851. #endif
  2852. /* FALLTHROUGH */
  2853. case SIGTERM:
  2854. if (iflag)
  2855. action = S_IGN;
  2856. break;
  2857. #if JOBS
  2858. case SIGTSTP:
  2859. case SIGTTOU:
  2860. if (mflag)
  2861. action = S_IGN;
  2862. break;
  2863. #endif
  2864. }
  2865. }
  2866. t = &sigmode[signo - 1];
  2867. tsig = *t;
  2868. if (tsig == 0) {
  2869. /*
  2870. * current setting unknown
  2871. */
  2872. if (sigaction(signo, 0, &act) == -1) {
  2873. /*
  2874. * Pretend it worked; maybe we should give a warning
  2875. * here, but other shells don't. We don't alter
  2876. * sigmode, so that we retry every time.
  2877. */
  2878. return;
  2879. }
  2880. if (act.sa_handler == SIG_IGN) {
  2881. if (mflag
  2882. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  2883. ) {
  2884. tsig = S_IGN; /* don't hard ignore these */
  2885. } else
  2886. tsig = S_HARD_IGN;
  2887. } else {
  2888. tsig = S_RESET; /* force to be set */
  2889. }
  2890. }
  2891. if (tsig == S_HARD_IGN || tsig == action)
  2892. return;
  2893. switch (action) {
  2894. case S_CATCH:
  2895. act.sa_handler = onsig;
  2896. break;
  2897. case S_IGN:
  2898. act.sa_handler = SIG_IGN;
  2899. break;
  2900. default:
  2901. act.sa_handler = SIG_DFL;
  2902. }
  2903. *t = action;
  2904. act.sa_flags = 0;
  2905. sigfillset(&act.sa_mask);
  2906. sigaction(signo, &act, 0);
  2907. }
  2908. /* mode flags for set_curjob */
  2909. #define CUR_DELETE 2
  2910. #define CUR_RUNNING 1
  2911. #define CUR_STOPPED 0
  2912. /* mode flags for dowait */
  2913. #define DOWAIT_NORMAL 0
  2914. #define DOWAIT_BLOCK 1
  2915. #if JOBS
  2916. /* pgrp of shell on invocation */
  2917. static int initialpgrp;
  2918. static int ttyfd = -1;
  2919. #endif
  2920. /* array of jobs */
  2921. static struct job *jobtab;
  2922. /* size of array */
  2923. static unsigned njobs;
  2924. /* current job */
  2925. static struct job *curjob;
  2926. /* number of presumed living untracked jobs */
  2927. static int jobless;
  2928. static void
  2929. set_curjob(struct job *jp, unsigned mode)
  2930. {
  2931. struct job *jp1;
  2932. struct job **jpp, **curp;
  2933. /* first remove from list */
  2934. jpp = curp = &curjob;
  2935. do {
  2936. jp1 = *jpp;
  2937. if (jp1 == jp)
  2938. break;
  2939. jpp = &jp1->prev_job;
  2940. } while (1);
  2941. *jpp = jp1->prev_job;
  2942. /* Then re-insert in correct position */
  2943. jpp = curp;
  2944. switch (mode) {
  2945. default:
  2946. #if DEBUG
  2947. abort();
  2948. #endif
  2949. case CUR_DELETE:
  2950. /* job being deleted */
  2951. break;
  2952. case CUR_RUNNING:
  2953. /* newly created job or backgrounded job,
  2954. put after all stopped jobs. */
  2955. do {
  2956. jp1 = *jpp;
  2957. #if JOBS
  2958. if (!jp1 || jp1->state != JOBSTOPPED)
  2959. #endif
  2960. break;
  2961. jpp = &jp1->prev_job;
  2962. } while (1);
  2963. /* FALLTHROUGH */
  2964. #if JOBS
  2965. case CUR_STOPPED:
  2966. #endif
  2967. /* newly stopped job - becomes curjob */
  2968. jp->prev_job = *jpp;
  2969. *jpp = jp;
  2970. break;
  2971. }
  2972. }
  2973. #if JOBS || DEBUG
  2974. static int
  2975. jobno(const struct job *jp)
  2976. {
  2977. return jp - jobtab + 1;
  2978. }
  2979. #endif
  2980. /*
  2981. * Convert a job name to a job structure.
  2982. */
  2983. static struct job *
  2984. getjob(const char *name, int getctl)
  2985. {
  2986. struct job *jp;
  2987. struct job *found;
  2988. const char *err_msg = "No such job: %s";
  2989. unsigned num;
  2990. int c;
  2991. const char *p;
  2992. char *(*match)(const char *, const char *);
  2993. jp = curjob;
  2994. p = name;
  2995. if (!p)
  2996. goto currentjob;
  2997. if (*p != '%')
  2998. goto err;
  2999. c = *++p;
  3000. if (!c)
  3001. goto currentjob;
  3002. if (!p[1]) {
  3003. if (c == '+' || c == '%') {
  3004. currentjob:
  3005. err_msg = "No current job";
  3006. goto check;
  3007. }
  3008. if (c == '-') {
  3009. if (jp)
  3010. jp = jp->prev_job;
  3011. err_msg = "No previous job";
  3012. check:
  3013. if (!jp)
  3014. goto err;
  3015. goto gotit;
  3016. }
  3017. }
  3018. if (is_number(p)) {
  3019. num = atoi(p);
  3020. if (num < njobs) {
  3021. jp = jobtab + num - 1;
  3022. if (jp->used)
  3023. goto gotit;
  3024. goto err;
  3025. }
  3026. }
  3027. match = prefix;
  3028. if (*p == '?') {
  3029. match = strstr;
  3030. p++;
  3031. }
  3032. found = 0;
  3033. while (1) {
  3034. if (!jp)
  3035. goto err;
  3036. if (match(jp->ps[0].cmd, p)) {
  3037. if (found)
  3038. goto err;
  3039. found = jp;
  3040. err_msg = "%s: ambiguous";
  3041. }
  3042. jp = jp->prev_job;
  3043. }
  3044. gotit:
  3045. #if JOBS
  3046. err_msg = "job %s not created under job control";
  3047. if (getctl && jp->jobctl == 0)
  3048. goto err;
  3049. #endif
  3050. return jp;
  3051. err:
  3052. ash_msg_and_raise_error(err_msg, name);
  3053. }
  3054. /*
  3055. * Mark a job structure as unused.
  3056. */
  3057. static void
  3058. freejob(struct job *jp)
  3059. {
  3060. struct procstat *ps;
  3061. int i;
  3062. INT_OFF;
  3063. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3064. if (ps->cmd != nullstr)
  3065. free(ps->cmd);
  3066. }
  3067. if (jp->ps != &jp->ps0)
  3068. free(jp->ps);
  3069. jp->used = 0;
  3070. set_curjob(jp, CUR_DELETE);
  3071. INT_ON;
  3072. }
  3073. #if JOBS
  3074. static void
  3075. xtcsetpgrp(int fd, pid_t pgrp)
  3076. {
  3077. if (tcsetpgrp(fd, pgrp))
  3078. ash_msg_and_raise_error("cannot set tty process group (%m)");
  3079. }
  3080. /*
  3081. * Turn job control on and off.
  3082. *
  3083. * Note: This code assumes that the third arg to ioctl is a character
  3084. * pointer, which is true on Berkeley systems but not System V. Since
  3085. * System V doesn't have job control yet, this isn't a problem now.
  3086. *
  3087. * Called with interrupts off.
  3088. */
  3089. static void
  3090. setjobctl(int on)
  3091. {
  3092. int fd;
  3093. int pgrp;
  3094. if (on == jobctl || rootshell == 0)
  3095. return;
  3096. if (on) {
  3097. int ofd;
  3098. ofd = fd = open(_PATH_TTY, O_RDWR);
  3099. if (fd < 0) {
  3100. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3101. * That sometimes helps to acquire controlling tty.
  3102. * Obviously, a workaround for bugs when someone
  3103. * failed to provide a controlling tty to bash! :) */
  3104. fd += 3;
  3105. while (!isatty(fd) && --fd >= 0)
  3106. ;
  3107. }
  3108. fd = fcntl(fd, F_DUPFD, 10);
  3109. close(ofd);
  3110. if (fd < 0)
  3111. goto out;
  3112. close_on_exec_on(fd);
  3113. do { /* while we are in the background */
  3114. pgrp = tcgetpgrp(fd);
  3115. if (pgrp < 0) {
  3116. out:
  3117. ash_msg("can't access tty; job control turned off");
  3118. mflag = on = 0;
  3119. goto close;
  3120. }
  3121. if (pgrp == getpgrp())
  3122. break;
  3123. killpg(0, SIGTTIN);
  3124. } while (1);
  3125. initialpgrp = pgrp;
  3126. setsignal(SIGTSTP);
  3127. setsignal(SIGTTOU);
  3128. setsignal(SIGTTIN);
  3129. pgrp = rootpid;
  3130. setpgid(0, pgrp);
  3131. xtcsetpgrp(fd, pgrp);
  3132. } else {
  3133. /* turning job control off */
  3134. fd = ttyfd;
  3135. pgrp = initialpgrp;
  3136. /* was xtcsetpgrp, but this can make exiting ash
  3137. * with pty already deleted loop forever */
  3138. tcsetpgrp(fd, pgrp);
  3139. setpgid(0, pgrp);
  3140. setsignal(SIGTSTP);
  3141. setsignal(SIGTTOU);
  3142. setsignal(SIGTTIN);
  3143. close:
  3144. close(fd);
  3145. fd = -1;
  3146. }
  3147. ttyfd = fd;
  3148. jobctl = on;
  3149. }
  3150. static int
  3151. killcmd(int argc, char **argv)
  3152. {
  3153. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3154. int i = 1;
  3155. do {
  3156. if (argv[i][0] == '%') {
  3157. struct job *jp = getjob(argv[i], 0);
  3158. unsigned pid = jp->ps[0].pid;
  3159. /* Enough space for ' -NNN<nul>' */
  3160. argv[i] = alloca(sizeof(int)*3 + 3);
  3161. /* kill_main has matching code to expect
  3162. * leading space. Needed to not confuse
  3163. * negative pids with "kill -SIGNAL_NO" syntax */
  3164. sprintf(argv[i], " -%u", pid);
  3165. }
  3166. } while (argv[++i]);
  3167. }
  3168. return kill_main(argc, argv);
  3169. }
  3170. static void
  3171. showpipe(struct job *jp, FILE *out)
  3172. {
  3173. struct procstat *sp;
  3174. struct procstat *spend;
  3175. spend = jp->ps + jp->nprocs;
  3176. for (sp = jp->ps + 1; sp < spend; sp++)
  3177. fprintf(out, " | %s", sp->cmd);
  3178. outcslow('\n', out);
  3179. flush_stdout_stderr();
  3180. }
  3181. static int
  3182. restartjob(struct job *jp, int mode)
  3183. {
  3184. struct procstat *ps;
  3185. int i;
  3186. int status;
  3187. pid_t pgid;
  3188. INT_OFF;
  3189. if (jp->state == JOBDONE)
  3190. goto out;
  3191. jp->state = JOBRUNNING;
  3192. pgid = jp->ps->pid;
  3193. if (mode == FORK_FG)
  3194. xtcsetpgrp(ttyfd, pgid);
  3195. killpg(pgid, SIGCONT);
  3196. ps = jp->ps;
  3197. i = jp->nprocs;
  3198. do {
  3199. if (WIFSTOPPED(ps->status)) {
  3200. ps->status = -1;
  3201. }
  3202. ps++;
  3203. } while (--i);
  3204. out:
  3205. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3206. INT_ON;
  3207. return status;
  3208. }
  3209. static int
  3210. fg_bgcmd(int argc, char **argv)
  3211. {
  3212. struct job *jp;
  3213. FILE *out;
  3214. int mode;
  3215. int retval;
  3216. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3217. nextopt(nullstr);
  3218. argv = argptr;
  3219. out = stdout;
  3220. do {
  3221. jp = getjob(*argv, 1);
  3222. if (mode == FORK_BG) {
  3223. set_curjob(jp, CUR_RUNNING);
  3224. fprintf(out, "[%d] ", jobno(jp));
  3225. }
  3226. outstr(jp->ps->cmd, out);
  3227. showpipe(jp, out);
  3228. retval = restartjob(jp, mode);
  3229. } while (*argv && *++argv);
  3230. return retval;
  3231. }
  3232. #endif
  3233. static int
  3234. sprint_status(char *s, int status, int sigonly)
  3235. {
  3236. int col;
  3237. int st;
  3238. col = 0;
  3239. if (!WIFEXITED(status)) {
  3240. #if JOBS
  3241. if (WIFSTOPPED(status))
  3242. st = WSTOPSIG(status);
  3243. else
  3244. #endif
  3245. st = WTERMSIG(status);
  3246. if (sigonly) {
  3247. if (st == SIGINT || st == SIGPIPE)
  3248. goto out;
  3249. #if JOBS
  3250. if (WIFSTOPPED(status))
  3251. goto out;
  3252. #endif
  3253. }
  3254. st &= 0x7f;
  3255. col = fmtstr(s, 32, strsignal(st));
  3256. if (WCOREDUMP(status)) {
  3257. col += fmtstr(s + col, 16, " (core dumped)");
  3258. }
  3259. } else if (!sigonly) {
  3260. st = WEXITSTATUS(status);
  3261. if (st)
  3262. col = fmtstr(s, 16, "Done(%d)", st);
  3263. else
  3264. col = fmtstr(s, 16, "Done");
  3265. }
  3266. out:
  3267. return col;
  3268. }
  3269. /*
  3270. * Do a wait system call. If job control is compiled in, we accept
  3271. * stopped processes. If block is zero, we return a value of zero
  3272. * rather than blocking.
  3273. *
  3274. * System V doesn't have a non-blocking wait system call. It does
  3275. * have a SIGCLD signal that is sent to a process when one of it's
  3276. * children dies. The obvious way to use SIGCLD would be to install
  3277. * a handler for SIGCLD which simply bumped a counter when a SIGCLD
  3278. * was received, and have waitproc bump another counter when it got
  3279. * the status of a process. Waitproc would then know that a wait
  3280. * system call would not block if the two counters were different.
  3281. * This approach doesn't work because if a process has children that
  3282. * have not been waited for, System V will send it a SIGCLD when it
  3283. * installs a signal handler for SIGCLD. What this means is that when
  3284. * a child exits, the shell will be sent SIGCLD signals continuously
  3285. * until is runs out of stack space, unless it does a wait call before
  3286. * restoring the signal handler. The code below takes advantage of
  3287. * this (mis)feature by installing a signal handler for SIGCLD and
  3288. * then checking to see whether it was called. If there are any
  3289. * children to be waited for, it will be.
  3290. *
  3291. * If neither SYSV nor BSD is defined, we don't implement nonblocking
  3292. * waits at all. In this case, the user will not be informed when
  3293. * a background process until the next time she runs a real program
  3294. * (as opposed to running a builtin command or just typing return),
  3295. * and the jobs command may give out of date information.
  3296. */
  3297. static int
  3298. waitproc(int block, int *status)
  3299. {
  3300. int flags = 0;
  3301. #if JOBS
  3302. if (jobctl)
  3303. flags |= WUNTRACED;
  3304. #endif
  3305. if (block == 0)
  3306. flags |= WNOHANG;
  3307. return wait3(status, flags, (struct rusage *)NULL);
  3308. }
  3309. /*
  3310. * Wait for a process to terminate.
  3311. */
  3312. static int
  3313. dowait(int block, struct job *job)
  3314. {
  3315. int pid;
  3316. int status;
  3317. struct job *jp;
  3318. struct job *thisjob;
  3319. int state;
  3320. TRACE(("dowait(%d) called\n", block));
  3321. pid = waitproc(block, &status);
  3322. TRACE(("wait returns pid %d, status=%d\n", pid, status));
  3323. if (pid <= 0)
  3324. return pid;
  3325. INT_OFF;
  3326. thisjob = NULL;
  3327. for (jp = curjob; jp; jp = jp->prev_job) {
  3328. struct procstat *sp;
  3329. struct procstat *spend;
  3330. if (jp->state == JOBDONE)
  3331. continue;
  3332. state = JOBDONE;
  3333. spend = jp->ps + jp->nprocs;
  3334. sp = jp->ps;
  3335. do {
  3336. if (sp->pid == pid) {
  3337. TRACE(("Job %d: changing status of proc %d "
  3338. "from 0x%x to 0x%x\n",
  3339. jobno(jp), pid, sp->status, status));
  3340. sp->status = status;
  3341. thisjob = jp;
  3342. }
  3343. if (sp->status == -1)
  3344. state = JOBRUNNING;
  3345. #if JOBS
  3346. if (state == JOBRUNNING)
  3347. continue;
  3348. if (WIFSTOPPED(sp->status)) {
  3349. jp->stopstatus = sp->status;
  3350. state = JOBSTOPPED;
  3351. }
  3352. #endif
  3353. } while (++sp < spend);
  3354. if (thisjob)
  3355. goto gotjob;
  3356. }
  3357. #if JOBS
  3358. if (!WIFSTOPPED(status))
  3359. #endif
  3360. jobless--;
  3361. goto out;
  3362. gotjob:
  3363. if (state != JOBRUNNING) {
  3364. thisjob->changed = 1;
  3365. if (thisjob->state != state) {
  3366. TRACE(("Job %d: changing state from %d to %d\n",
  3367. jobno(thisjob), thisjob->state, state));
  3368. thisjob->state = state;
  3369. #if JOBS
  3370. if (state == JOBSTOPPED) {
  3371. set_curjob(thisjob, CUR_STOPPED);
  3372. }
  3373. #endif
  3374. }
  3375. }
  3376. out:
  3377. INT_ON;
  3378. if (thisjob && thisjob == job) {
  3379. char s[48 + 1];
  3380. int len;
  3381. len = sprint_status(s, status, 1);
  3382. if (len) {
  3383. s[len] = '\n';
  3384. s[len + 1] = 0;
  3385. out2str(s);
  3386. }
  3387. }
  3388. return pid;
  3389. }
  3390. #if JOBS
  3391. static void
  3392. showjob(FILE *out, struct job *jp, int mode)
  3393. {
  3394. struct procstat *ps;
  3395. struct procstat *psend;
  3396. int col;
  3397. int indent_col;
  3398. char s[80];
  3399. ps = jp->ps;
  3400. if (mode & SHOW_PGID) {
  3401. /* just output process (group) id of pipeline */
  3402. fprintf(out, "%d\n", ps->pid);
  3403. return;
  3404. }
  3405. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3406. indent_col = col;
  3407. if (jp == curjob)
  3408. s[col - 2] = '+';
  3409. else if (curjob && jp == curjob->prev_job)
  3410. s[col - 2] = '-';
  3411. if (mode & SHOW_PID)
  3412. col += fmtstr(s + col, 16, "%d ", ps->pid);
  3413. psend = ps + jp->nprocs;
  3414. if (jp->state == JOBRUNNING) {
  3415. strcpy(s + col, "Running");
  3416. col += sizeof("Running") - 1;
  3417. } else {
  3418. int status = psend[-1].status;
  3419. if (jp->state == JOBSTOPPED)
  3420. status = jp->stopstatus;
  3421. col += sprint_status(s + col, status, 0);
  3422. }
  3423. goto start;
  3424. do {
  3425. /* for each process */
  3426. col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
  3427. start:
  3428. fprintf(out, "%s%*c%s",
  3429. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  3430. );
  3431. if (!(mode & SHOW_PID)) {
  3432. showpipe(jp, out);
  3433. break;
  3434. }
  3435. if (++ps == psend) {
  3436. outcslow('\n', out);
  3437. break;
  3438. }
  3439. } while (1);
  3440. jp->changed = 0;
  3441. if (jp->state == JOBDONE) {
  3442. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3443. freejob(jp);
  3444. }
  3445. }
  3446. /*
  3447. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3448. * statuses have changed since the last call to showjobs.
  3449. */
  3450. static void
  3451. showjobs(FILE *out, int mode)
  3452. {
  3453. struct job *jp;
  3454. TRACE(("showjobs(%x) called\n", mode));
  3455. /* If not even one one job changed, there is nothing to do */
  3456. while (dowait(DOWAIT_NORMAL, NULL) > 0)
  3457. continue;
  3458. for (jp = curjob; jp; jp = jp->prev_job) {
  3459. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3460. showjob(out, jp, mode);
  3461. }
  3462. }
  3463. }
  3464. static int
  3465. jobscmd(int argc, char **argv)
  3466. {
  3467. int mode, m;
  3468. mode = 0;
  3469. while ((m = nextopt("lp"))) {
  3470. if (m == 'l')
  3471. mode = SHOW_PID;
  3472. else
  3473. mode = SHOW_PGID;
  3474. }
  3475. argv = argptr;
  3476. if (*argv) {
  3477. do
  3478. showjob(stdout, getjob(*argv,0), mode);
  3479. while (*++argv);
  3480. } else
  3481. showjobs(stdout, mode);
  3482. return 0;
  3483. }
  3484. #endif /* JOBS */
  3485. static int
  3486. getstatus(struct job *job)
  3487. {
  3488. int status;
  3489. int retval;
  3490. status = job->ps[job->nprocs - 1].status;
  3491. retval = WEXITSTATUS(status);
  3492. if (!WIFEXITED(status)) {
  3493. #if JOBS
  3494. retval = WSTOPSIG(status);
  3495. if (!WIFSTOPPED(status))
  3496. #endif
  3497. {
  3498. /* XXX: limits number of signals */
  3499. retval = WTERMSIG(status);
  3500. #if JOBS
  3501. if (retval == SIGINT)
  3502. job->sigint = 1;
  3503. #endif
  3504. }
  3505. retval += 128;
  3506. }
  3507. TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
  3508. jobno(job), job->nprocs, status, retval));
  3509. return retval;
  3510. }
  3511. static int
  3512. waitcmd(int argc, char **argv)
  3513. {
  3514. struct job *job;
  3515. int retval;
  3516. struct job *jp;
  3517. EXSIGON;
  3518. nextopt(nullstr);
  3519. retval = 0;
  3520. argv = argptr;
  3521. if (!*argv) {
  3522. /* wait for all jobs */
  3523. for (;;) {
  3524. jp = curjob;
  3525. while (1) {
  3526. if (!jp) {
  3527. /* no running procs */
  3528. goto out;
  3529. }
  3530. if (jp->state == JOBRUNNING)
  3531. break;
  3532. jp->waited = 1;
  3533. jp = jp->prev_job;
  3534. }
  3535. dowait(DOWAIT_BLOCK, 0);
  3536. }
  3537. }
  3538. retval = 127;
  3539. do {
  3540. if (**argv != '%') {
  3541. pid_t pid = number(*argv);
  3542. job = curjob;
  3543. goto start;
  3544. do {
  3545. if (job->ps[job->nprocs - 1].pid == pid)
  3546. break;
  3547. job = job->prev_job;
  3548. start:
  3549. if (!job)
  3550. goto repeat;
  3551. } while (1);
  3552. } else
  3553. job = getjob(*argv, 0);
  3554. /* loop until process terminated or stopped */
  3555. while (job->state == JOBRUNNING)
  3556. dowait(DOWAIT_BLOCK, 0);
  3557. job->waited = 1;
  3558. retval = getstatus(job);
  3559. repeat:
  3560. ;
  3561. } while (*++argv);
  3562. out:
  3563. return retval;
  3564. }
  3565. static struct job *
  3566. growjobtab(void)
  3567. {
  3568. size_t len;
  3569. ptrdiff_t offset;
  3570. struct job *jp, *jq;
  3571. len = njobs * sizeof(*jp);
  3572. jq = jobtab;
  3573. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3574. offset = (char *)jp - (char *)jq;
  3575. if (offset) {
  3576. /* Relocate pointers */
  3577. size_t l = len;
  3578. jq = (struct job *)((char *)jq + l);
  3579. while (l) {
  3580. l -= sizeof(*jp);
  3581. jq--;
  3582. #define joff(p) ((struct job *)((char *)(p) + l))
  3583. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3584. if (joff(jp)->ps == &jq->ps0)
  3585. jmove(joff(jp)->ps);
  3586. if (joff(jp)->prev_job)
  3587. jmove(joff(jp)->prev_job);
  3588. }
  3589. if (curjob)
  3590. jmove(curjob);
  3591. #undef joff
  3592. #undef jmove
  3593. }
  3594. njobs += 4;
  3595. jobtab = jp;
  3596. jp = (struct job *)((char *)jp + len);
  3597. jq = jp + 3;
  3598. do {
  3599. jq->used = 0;
  3600. } while (--jq >= jp);
  3601. return jp;
  3602. }
  3603. /*
  3604. * Return a new job structure.
  3605. * Called with interrupts off.
  3606. */
  3607. static struct job *
  3608. makejob(union node *node, int nprocs)
  3609. {
  3610. int i;
  3611. struct job *jp;
  3612. for (i = njobs, jp = jobtab; ; jp++) {
  3613. if (--i < 0) {
  3614. jp = growjobtab();
  3615. break;
  3616. }
  3617. if (jp->used == 0)
  3618. break;
  3619. if (jp->state != JOBDONE || !jp->waited)
  3620. continue;
  3621. #if JOBS
  3622. if (jobctl)
  3623. continue;
  3624. #endif
  3625. freejob(jp);
  3626. break;
  3627. }
  3628. memset(jp, 0, sizeof(*jp));
  3629. #if JOBS
  3630. /* jp->jobctl is a bitfield.
  3631. * "jp->jobctl |= jobctl" likely to give awful code */
  3632. if (jobctl)
  3633. jp->jobctl = 1;
  3634. #endif
  3635. jp->prev_job = curjob;
  3636. curjob = jp;
  3637. jp->used = 1;
  3638. jp->ps = &jp->ps0;
  3639. if (nprocs > 1) {
  3640. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3641. }
  3642. TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
  3643. jobno(jp)));
  3644. return jp;
  3645. }
  3646. #if JOBS
  3647. /*
  3648. * Return a string identifying a command (to be printed by the
  3649. * jobs command).
  3650. */
  3651. static char *cmdnextc;
  3652. static void
  3653. cmdputs(const char *s)
  3654. {
  3655. const char *p, *str;
  3656. char c, cc[2] = " ";
  3657. char *nextc;
  3658. int subtype = 0;
  3659. int quoted = 0;
  3660. static const char vstype[VSTYPE + 1][4] = {
  3661. "", "}", "-", "+", "?", "=",
  3662. "%", "%%", "#", "##"
  3663. };
  3664. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3665. p = s;
  3666. while ((c = *p++) != 0) {
  3667. str = 0;
  3668. switch (c) {
  3669. case CTLESC:
  3670. c = *p++;
  3671. break;
  3672. case CTLVAR:
  3673. subtype = *p++;
  3674. if ((subtype & VSTYPE) == VSLENGTH)
  3675. str = "${#";
  3676. else
  3677. str = "${";
  3678. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3679. goto dostr;
  3680. quoted ^= 1;
  3681. c = '"';
  3682. break;
  3683. case CTLENDVAR:
  3684. str = "\"}" + !(quoted & 1);
  3685. quoted >>= 1;
  3686. subtype = 0;
  3687. goto dostr;
  3688. case CTLBACKQ:
  3689. str = "$(...)";
  3690. goto dostr;
  3691. case CTLBACKQ+CTLQUOTE:
  3692. str = "\"$(...)\"";
  3693. goto dostr;
  3694. #if ENABLE_ASH_MATH_SUPPORT
  3695. case CTLARI:
  3696. str = "$((";
  3697. goto dostr;
  3698. case CTLENDARI:
  3699. str = "))";
  3700. goto dostr;
  3701. #endif
  3702. case CTLQUOTEMARK:
  3703. quoted ^= 1;
  3704. c = '"';
  3705. break;
  3706. case '=':
  3707. if (subtype == 0)
  3708. break;
  3709. if ((subtype & VSTYPE) != VSNORMAL)
  3710. quoted <<= 1;
  3711. str = vstype[subtype & VSTYPE];
  3712. if (subtype & VSNUL)
  3713. c = ':';
  3714. else
  3715. goto checkstr;
  3716. break;
  3717. case '\'':
  3718. case '\\':
  3719. case '"':
  3720. case '$':
  3721. /* These can only happen inside quotes */
  3722. cc[0] = c;
  3723. str = cc;
  3724. c = '\\';
  3725. break;
  3726. default:
  3727. break;
  3728. }
  3729. USTPUTC(c, nextc);
  3730. checkstr:
  3731. if (!str)
  3732. continue;
  3733. dostr:
  3734. while ((c = *str++)) {
  3735. USTPUTC(c, nextc);
  3736. }
  3737. }
  3738. if (quoted & 1) {
  3739. USTPUTC('"', nextc);
  3740. }
  3741. *nextc = 0;
  3742. cmdnextc = nextc;
  3743. }
  3744. /* cmdtxt() and cmdlist() call each other */
  3745. static void cmdtxt(union node *n);
  3746. static void
  3747. cmdlist(union node *np, int sep)
  3748. {
  3749. for (; np; np = np->narg.next) {
  3750. if (!sep)
  3751. cmdputs(" ");
  3752. cmdtxt(np);
  3753. if (sep && np->narg.next)
  3754. cmdputs(" ");
  3755. }
  3756. }
  3757. static void
  3758. cmdtxt(union node *n)
  3759. {
  3760. union node *np;
  3761. struct nodelist *lp;
  3762. const char *p;
  3763. char s[2];
  3764. if (!n)
  3765. return;
  3766. switch (n->type) {
  3767. default:
  3768. #if DEBUG
  3769. abort();
  3770. #endif
  3771. case NPIPE:
  3772. lp = n->npipe.cmdlist;
  3773. for (;;) {
  3774. cmdtxt(lp->n);
  3775. lp = lp->next;
  3776. if (!lp)
  3777. break;
  3778. cmdputs(" | ");
  3779. }
  3780. break;
  3781. case NSEMI:
  3782. p = "; ";
  3783. goto binop;
  3784. case NAND:
  3785. p = " && ";
  3786. goto binop;
  3787. case NOR:
  3788. p = " || ";
  3789. binop:
  3790. cmdtxt(n->nbinary.ch1);
  3791. cmdputs(p);
  3792. n = n->nbinary.ch2;
  3793. goto donode;
  3794. case NREDIR:
  3795. case NBACKGND:
  3796. n = n->nredir.n;
  3797. goto donode;
  3798. case NNOT:
  3799. cmdputs("!");
  3800. n = n->nnot.com;
  3801. donode:
  3802. cmdtxt(n);
  3803. break;
  3804. case NIF:
  3805. cmdputs("if ");
  3806. cmdtxt(n->nif.test);
  3807. cmdputs("; then ");
  3808. n = n->nif.ifpart;
  3809. if (n->nif.elsepart) {
  3810. cmdtxt(n);
  3811. cmdputs("; else ");
  3812. n = n->nif.elsepart;
  3813. }
  3814. p = "; fi";
  3815. goto dotail;
  3816. case NSUBSHELL:
  3817. cmdputs("(");
  3818. n = n->nredir.n;
  3819. p = ")";
  3820. goto dotail;
  3821. case NWHILE:
  3822. p = "while ";
  3823. goto until;
  3824. case NUNTIL:
  3825. p = "until ";
  3826. until:
  3827. cmdputs(p);
  3828. cmdtxt(n->nbinary.ch1);
  3829. n = n->nbinary.ch2;
  3830. p = "; done";
  3831. dodo:
  3832. cmdputs("; do ");
  3833. dotail:
  3834. cmdtxt(n);
  3835. goto dotail2;
  3836. case NFOR:
  3837. cmdputs("for ");
  3838. cmdputs(n->nfor.var);
  3839. cmdputs(" in ");
  3840. cmdlist(n->nfor.args, 1);
  3841. n = n->nfor.body;
  3842. p = "; done";
  3843. goto dodo;
  3844. case NDEFUN:
  3845. cmdputs(n->narg.text);
  3846. p = "() { ... }";
  3847. goto dotail2;
  3848. case NCMD:
  3849. cmdlist(n->ncmd.args, 1);
  3850. cmdlist(n->ncmd.redirect, 0);
  3851. break;
  3852. case NARG:
  3853. p = n->narg.text;
  3854. dotail2:
  3855. cmdputs(p);
  3856. break;
  3857. case NHERE:
  3858. case NXHERE:
  3859. p = "<<...";
  3860. goto dotail2;
  3861. case NCASE:
  3862. cmdputs("case ");
  3863. cmdputs(n->ncase.expr->narg.text);
  3864. cmdputs(" in ");
  3865. for (np = n->ncase.cases; np; np = np->nclist.next) {
  3866. cmdtxt(np->nclist.pattern);
  3867. cmdputs(") ");
  3868. cmdtxt(np->nclist.body);
  3869. cmdputs(";; ");
  3870. }
  3871. p = "esac";
  3872. goto dotail2;
  3873. case NTO:
  3874. p = ">";
  3875. goto redir;
  3876. case NCLOBBER:
  3877. p = ">|";
  3878. goto redir;
  3879. case NAPPEND:
  3880. p = ">>";
  3881. goto redir;
  3882. case NTOFD:
  3883. p = ">&";
  3884. goto redir;
  3885. case NFROM:
  3886. p = "<";
  3887. goto redir;
  3888. case NFROMFD:
  3889. p = "<&";
  3890. goto redir;
  3891. case NFROMTO:
  3892. p = "<>";
  3893. redir:
  3894. s[0] = n->nfile.fd + '0';
  3895. s[1] = '\0';
  3896. cmdputs(s);
  3897. cmdputs(p);
  3898. if (n->type == NTOFD || n->type == NFROMFD) {
  3899. s[0] = n->ndup.dupfd + '0';
  3900. p = s;
  3901. goto dotail2;
  3902. }
  3903. n = n->nfile.fname;
  3904. goto donode;
  3905. }
  3906. }
  3907. static char *
  3908. commandtext(union node *n)
  3909. {
  3910. char *name;
  3911. STARTSTACKSTR(cmdnextc);
  3912. cmdtxt(n);
  3913. name = stackblock();
  3914. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  3915. name, cmdnextc, cmdnextc));
  3916. return ckstrdup(name);
  3917. }
  3918. #endif /* JOBS */
  3919. /*
  3920. * Fork off a subshell. If we are doing job control, give the subshell its
  3921. * own process group. Jp is a job structure that the job is to be added to.
  3922. * N is the command that will be evaluated by the child. Both jp and n may
  3923. * be NULL. The mode parameter can be one of the following:
  3924. * FORK_FG - Fork off a foreground process.
  3925. * FORK_BG - Fork off a background process.
  3926. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  3927. * process group even if job control is on.
  3928. *
  3929. * When job control is turned off, background processes have their standard
  3930. * input redirected to /dev/null (except for the second and later processes
  3931. * in a pipeline).
  3932. *
  3933. * Called with interrupts off.
  3934. */
  3935. /*
  3936. * Clear traps on a fork.
  3937. */
  3938. static void
  3939. clear_traps(void)
  3940. {
  3941. char **tp;
  3942. for (tp = trap; tp < &trap[NSIG]; tp++) {
  3943. if (*tp && **tp) { /* trap not NULL or SIG_IGN */
  3944. INT_OFF;
  3945. free(*tp);
  3946. *tp = NULL;
  3947. if (tp != &trap[0])
  3948. setsignal(tp - trap);
  3949. INT_ON;
  3950. }
  3951. }
  3952. }
  3953. /* Lives far away from here, needed for forkchild */
  3954. static void closescript(void);
  3955. /* Called after fork(), in child */
  3956. static void
  3957. forkchild(struct job *jp, union node *n, int mode)
  3958. {
  3959. int oldlvl;
  3960. TRACE(("Child shell %d\n", getpid()));
  3961. oldlvl = shlvl;
  3962. shlvl++;
  3963. closescript();
  3964. clear_traps();
  3965. #if JOBS
  3966. /* do job control only in root shell */
  3967. jobctl = 0;
  3968. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  3969. pid_t pgrp;
  3970. if (jp->nprocs == 0)
  3971. pgrp = getpid();
  3972. else
  3973. pgrp = jp->ps[0].pid;
  3974. /* This can fail because we are doing it in the parent also */
  3975. (void)setpgid(0, pgrp);
  3976. if (mode == FORK_FG)
  3977. xtcsetpgrp(ttyfd, pgrp);
  3978. setsignal(SIGTSTP);
  3979. setsignal(SIGTTOU);
  3980. } else
  3981. #endif
  3982. if (mode == FORK_BG) {
  3983. ignoresig(SIGINT);
  3984. ignoresig(SIGQUIT);
  3985. if (jp->nprocs == 0) {
  3986. close(0);
  3987. if (open(bb_dev_null, O_RDONLY) != 0)
  3988. ash_msg_and_raise_error("can't open %s", bb_dev_null);
  3989. }
  3990. }
  3991. if (!oldlvl && iflag) {
  3992. setsignal(SIGINT);
  3993. setsignal(SIGQUIT);
  3994. setsignal(SIGTERM);
  3995. }
  3996. for (jp = curjob; jp; jp = jp->prev_job)
  3997. freejob(jp);
  3998. jobless = 0;
  3999. }
  4000. /* Called after fork(), in parent */
  4001. static void
  4002. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4003. {
  4004. TRACE(("In parent shell: child = %d\n", pid));
  4005. if (!jp) {
  4006. while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
  4007. jobless++;
  4008. return;
  4009. }
  4010. #if JOBS
  4011. if (mode != FORK_NOJOB && jp->jobctl) {
  4012. int pgrp;
  4013. if (jp->nprocs == 0)
  4014. pgrp = pid;
  4015. else
  4016. pgrp = jp->ps[0].pid;
  4017. /* This can fail because we are doing it in the child also */
  4018. setpgid(pid, pgrp);
  4019. }
  4020. #endif
  4021. if (mode == FORK_BG) {
  4022. backgndpid = pid; /* set $! */
  4023. set_curjob(jp, CUR_RUNNING);
  4024. }
  4025. if (jp) {
  4026. struct procstat *ps = &jp->ps[jp->nprocs++];
  4027. ps->pid = pid;
  4028. ps->status = -1;
  4029. ps->cmd = nullstr;
  4030. #if JOBS
  4031. if (jobctl && n)
  4032. ps->cmd = commandtext(n);
  4033. #endif
  4034. }
  4035. }
  4036. static int
  4037. forkshell(struct job *jp, union node *n, int mode)
  4038. {
  4039. int pid;
  4040. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4041. pid = fork();
  4042. if (pid < 0) {
  4043. TRACE(("Fork failed, errno=%d", errno));
  4044. if (jp)
  4045. freejob(jp);
  4046. ash_msg_and_raise_error("cannot fork");
  4047. }
  4048. if (pid == 0)
  4049. forkchild(jp, n, mode);
  4050. else
  4051. forkparent(jp, n, mode, pid);
  4052. return pid;
  4053. }
  4054. /*
  4055. * Wait for job to finish.
  4056. *
  4057. * Under job control we have the problem that while a child process is
  4058. * running interrupts generated by the user are sent to the child but not
  4059. * to the shell. This means that an infinite loop started by an inter-
  4060. * active user may be hard to kill. With job control turned off, an
  4061. * interactive user may place an interactive program inside a loop. If
  4062. * the interactive program catches interrupts, the user doesn't want
  4063. * these interrupts to also abort the loop. The approach we take here
  4064. * is to have the shell ignore interrupt signals while waiting for a
  4065. * foreground process to terminate, and then send itself an interrupt
  4066. * signal if the child process was terminated by an interrupt signal.
  4067. * Unfortunately, some programs want to do a bit of cleanup and then
  4068. * exit on interrupt; unless these processes terminate themselves by
  4069. * sending a signal to themselves (instead of calling exit) they will
  4070. * confuse this approach.
  4071. *
  4072. * Called with interrupts off.
  4073. */
  4074. static int
  4075. waitforjob(struct job *jp)
  4076. {
  4077. int st;
  4078. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4079. while (jp->state == JOBRUNNING) {
  4080. dowait(DOWAIT_BLOCK, jp);
  4081. }
  4082. st = getstatus(jp);
  4083. #if JOBS
  4084. if (jp->jobctl) {
  4085. xtcsetpgrp(ttyfd, rootpid);
  4086. /*
  4087. * This is truly gross.
  4088. * If we're doing job control, then we did a TIOCSPGRP which
  4089. * caused us (the shell) to no longer be in the controlling
  4090. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4091. * intuit from the subprocess exit status whether a SIGINT
  4092. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4093. */
  4094. if (jp->sigint)
  4095. raise(SIGINT);
  4096. }
  4097. if (jp->state == JOBDONE)
  4098. #endif
  4099. freejob(jp);
  4100. return st;
  4101. }
  4102. /*
  4103. * return 1 if there are stopped jobs, otherwise 0
  4104. */
  4105. static int
  4106. stoppedjobs(void)
  4107. {
  4108. struct job *jp;
  4109. int retval;
  4110. retval = 0;
  4111. if (job_warning)
  4112. goto out;
  4113. jp = curjob;
  4114. if (jp && jp->state == JOBSTOPPED) {
  4115. out2str("You have stopped jobs.\n");
  4116. job_warning = 2;
  4117. retval++;
  4118. }
  4119. out:
  4120. return retval;
  4121. }
  4122. /* ============ redir.c
  4123. *
  4124. * Code for dealing with input/output redirection.
  4125. */
  4126. #define EMPTY -2 /* marks an unused slot in redirtab */
  4127. #ifndef PIPE_BUF
  4128. # define PIPESIZE 4096 /* amount of buffering in a pipe */
  4129. #else
  4130. # define PIPESIZE PIPE_BUF
  4131. #endif
  4132. /*
  4133. * Open a file in noclobber mode.
  4134. * The code was copied from bash.
  4135. */
  4136. static int
  4137. noclobberopen(const char *fname)
  4138. {
  4139. int r, fd;
  4140. struct stat finfo, finfo2;
  4141. /*
  4142. * If the file exists and is a regular file, return an error
  4143. * immediately.
  4144. */
  4145. r = stat(fname, &finfo);
  4146. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4147. errno = EEXIST;
  4148. return -1;
  4149. }
  4150. /*
  4151. * If the file was not present (r != 0), make sure we open it
  4152. * exclusively so that if it is created before we open it, our open
  4153. * will fail. Make sure that we do not truncate an existing file.
  4154. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4155. * file was not a regular file, we leave O_EXCL off.
  4156. */
  4157. if (r != 0)
  4158. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4159. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4160. /* If the open failed, return the file descriptor right away. */
  4161. if (fd < 0)
  4162. return fd;
  4163. /*
  4164. * OK, the open succeeded, but the file may have been changed from a
  4165. * non-regular file to a regular file between the stat and the open.
  4166. * We are assuming that the O_EXCL open handles the case where FILENAME
  4167. * did not exist and is symlinked to an existing file between the stat
  4168. * and open.
  4169. */
  4170. /*
  4171. * If we can open it and fstat the file descriptor, and neither check
  4172. * revealed that it was a regular file, and the file has not been
  4173. * replaced, return the file descriptor.
  4174. */
  4175. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4176. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4177. return fd;
  4178. /* The file has been replaced. badness. */
  4179. close(fd);
  4180. errno = EEXIST;
  4181. return -1;
  4182. }
  4183. /*
  4184. * Handle here documents. Normally we fork off a process to write the
  4185. * data to a pipe. If the document is short, we can stuff the data in
  4186. * the pipe without forking.
  4187. */
  4188. /* openhere needs this forward reference */
  4189. static void expandhere(union node *arg, int fd);
  4190. static int
  4191. openhere(union node *redir)
  4192. {
  4193. int pip[2];
  4194. size_t len = 0;
  4195. if (pipe(pip) < 0)
  4196. ash_msg_and_raise_error("pipe call failed");
  4197. if (redir->type == NHERE) {
  4198. len = strlen(redir->nhere.doc->narg.text);
  4199. if (len <= PIPESIZE) {
  4200. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4201. goto out;
  4202. }
  4203. }
  4204. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4205. close(pip[0]);
  4206. signal(SIGINT, SIG_IGN);
  4207. signal(SIGQUIT, SIG_IGN);
  4208. signal(SIGHUP, SIG_IGN);
  4209. #ifdef SIGTSTP
  4210. signal(SIGTSTP, SIG_IGN);
  4211. #endif
  4212. signal(SIGPIPE, SIG_DFL);
  4213. if (redir->type == NHERE)
  4214. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4215. else
  4216. expandhere(redir->nhere.doc, pip[1]);
  4217. _exit(0);
  4218. }
  4219. out:
  4220. close(pip[1]);
  4221. return pip[0];
  4222. }
  4223. static int
  4224. openredirect(union node *redir)
  4225. {
  4226. char *fname;
  4227. int f;
  4228. switch (redir->nfile.type) {
  4229. case NFROM:
  4230. fname = redir->nfile.expfname;
  4231. f = open(fname, O_RDONLY);
  4232. if (f < 0)
  4233. goto eopen;
  4234. break;
  4235. case NFROMTO:
  4236. fname = redir->nfile.expfname;
  4237. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4238. if (f < 0)
  4239. goto ecreate;
  4240. break;
  4241. case NTO:
  4242. /* Take care of noclobber mode. */
  4243. if (Cflag) {
  4244. fname = redir->nfile.expfname;
  4245. f = noclobberopen(fname);
  4246. if (f < 0)
  4247. goto ecreate;
  4248. break;
  4249. }
  4250. /* FALLTHROUGH */
  4251. case NCLOBBER:
  4252. fname = redir->nfile.expfname;
  4253. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4254. if (f < 0)
  4255. goto ecreate;
  4256. break;
  4257. case NAPPEND:
  4258. fname = redir->nfile.expfname;
  4259. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4260. if (f < 0)
  4261. goto ecreate;
  4262. break;
  4263. default:
  4264. #if DEBUG
  4265. abort();
  4266. #endif
  4267. /* Fall through to eliminate warning. */
  4268. case NTOFD:
  4269. case NFROMFD:
  4270. f = -1;
  4271. break;
  4272. case NHERE:
  4273. case NXHERE:
  4274. f = openhere(redir);
  4275. break;
  4276. }
  4277. return f;
  4278. ecreate:
  4279. ash_msg_and_raise_error("cannot create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4280. eopen:
  4281. ash_msg_and_raise_error("cannot open %s: %s", fname, errmsg(errno, "no such file"));
  4282. }
  4283. /*
  4284. * Copy a file descriptor to be >= to. Returns -1
  4285. * if the source file descriptor is closed, EMPTY if there are no unused
  4286. * file descriptors left.
  4287. */
  4288. static int
  4289. copyfd(int from, int to)
  4290. {
  4291. int newfd;
  4292. newfd = fcntl(from, F_DUPFD, to);
  4293. if (newfd < 0) {
  4294. if (errno == EMFILE)
  4295. return EMPTY;
  4296. ash_msg_and_raise_error("%d: %m", from);
  4297. }
  4298. return newfd;
  4299. }
  4300. static void
  4301. dupredirect(union node *redir, int f)
  4302. {
  4303. int fd = redir->nfile.fd;
  4304. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4305. if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
  4306. copyfd(redir->ndup.dupfd, fd);
  4307. }
  4308. return;
  4309. }
  4310. if (f != fd) {
  4311. copyfd(f, fd);
  4312. close(f);
  4313. }
  4314. }
  4315. /*
  4316. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4317. * old file descriptors are stashed away so that the redirection can be
  4318. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4319. * standard output, and the standard error if it becomes a duplicate of
  4320. * stdout, is saved in memory.
  4321. */
  4322. /* flags passed to redirect */
  4323. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4324. #define REDIR_SAVEFD2 03 /* set preverrout */
  4325. static void
  4326. redirect(union node *redir, int flags)
  4327. {
  4328. union node *n;
  4329. struct redirtab *sv;
  4330. int i;
  4331. int fd;
  4332. int newfd;
  4333. int *p;
  4334. nullredirs++;
  4335. if (!redir) {
  4336. return;
  4337. }
  4338. sv = NULL;
  4339. INT_OFF;
  4340. if (flags & REDIR_PUSH) {
  4341. struct redirtab *q;
  4342. q = ckmalloc(sizeof(struct redirtab));
  4343. q->next = redirlist;
  4344. redirlist = q;
  4345. q->nullredirs = nullredirs - 1;
  4346. for (i = 0; i < 10; i++)
  4347. q->renamed[i] = EMPTY;
  4348. nullredirs = 0;
  4349. sv = q;
  4350. }
  4351. n = redir;
  4352. do {
  4353. fd = n->nfile.fd;
  4354. if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD)
  4355. && n->ndup.dupfd == fd)
  4356. continue; /* redirect from/to same file descriptor */
  4357. newfd = openredirect(n);
  4358. if (fd == newfd)
  4359. continue;
  4360. if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
  4361. i = fcntl(fd, F_DUPFD, 10);
  4362. if (i == -1) {
  4363. i = errno;
  4364. if (i != EBADF) {
  4365. close(newfd);
  4366. errno = i;
  4367. ash_msg_and_raise_error("%d: %m", fd);
  4368. /* NOTREACHED */
  4369. }
  4370. } else {
  4371. *p = i;
  4372. close(fd);
  4373. }
  4374. } else {
  4375. close(fd);
  4376. }
  4377. dupredirect(n, newfd);
  4378. } while ((n = n->nfile.next));
  4379. INT_ON;
  4380. if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
  4381. preverrout_fd = sv->renamed[2];
  4382. }
  4383. /*
  4384. * Undo the effects of the last redirection.
  4385. */
  4386. static void
  4387. popredir(int drop)
  4388. {
  4389. struct redirtab *rp;
  4390. int i;
  4391. if (--nullredirs >= 0)
  4392. return;
  4393. INT_OFF;
  4394. rp = redirlist;
  4395. for (i = 0; i < 10; i++) {
  4396. if (rp->renamed[i] != EMPTY) {
  4397. if (!drop) {
  4398. close(i);
  4399. copyfd(rp->renamed[i], i);
  4400. }
  4401. close(rp->renamed[i]);
  4402. }
  4403. }
  4404. redirlist = rp->next;
  4405. nullredirs = rp->nullredirs;
  4406. free(rp);
  4407. INT_ON;
  4408. }
  4409. /*
  4410. * Undo all redirections. Called on error or interrupt.
  4411. */
  4412. /*
  4413. * Discard all saved file descriptors.
  4414. */
  4415. static void
  4416. clearredir(int drop)
  4417. {
  4418. for (;;) {
  4419. nullredirs = 0;
  4420. if (!redirlist)
  4421. break;
  4422. popredir(drop);
  4423. }
  4424. }
  4425. static int
  4426. redirectsafe(union node *redir, int flags)
  4427. {
  4428. int err;
  4429. volatile int saveint;
  4430. struct jmploc *volatile savehandler = exception_handler;
  4431. struct jmploc jmploc;
  4432. SAVE_INT(saveint);
  4433. err = setjmp(jmploc.loc) * 2;
  4434. if (!err) {
  4435. exception_handler = &jmploc;
  4436. redirect(redir, flags);
  4437. }
  4438. exception_handler = savehandler;
  4439. if (err && exception != EXERROR)
  4440. longjmp(exception_handler->loc, 1);
  4441. RESTORE_INT(saveint);
  4442. return err;
  4443. }
  4444. /* ============ Routines to expand arguments to commands
  4445. *
  4446. * We have to deal with backquotes, shell variables, and file metacharacters.
  4447. */
  4448. /*
  4449. * expandarg flags
  4450. */
  4451. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4452. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4453. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4454. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4455. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4456. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4457. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4458. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4459. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4460. /*
  4461. * _rmescape() flags
  4462. */
  4463. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4464. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4465. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4466. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4467. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4468. /*
  4469. * Structure specifying which parts of the string should be searched
  4470. * for IFS characters.
  4471. */
  4472. struct ifsregion {
  4473. struct ifsregion *next; /* next region in list */
  4474. int begoff; /* offset of start of region */
  4475. int endoff; /* offset of end of region */
  4476. int nulonly; /* search for nul bytes only */
  4477. };
  4478. struct arglist {
  4479. struct strlist *list;
  4480. struct strlist **lastp;
  4481. };
  4482. /* output of current string */
  4483. static char *expdest;
  4484. /* list of back quote expressions */
  4485. static struct nodelist *argbackq;
  4486. /* first struct in list of ifs regions */
  4487. static struct ifsregion ifsfirst;
  4488. /* last struct in list */
  4489. static struct ifsregion *ifslastp;
  4490. /* holds expanded arg list */
  4491. static struct arglist exparg;
  4492. /*
  4493. * Our own itoa().
  4494. */
  4495. static int
  4496. cvtnum(arith_t num)
  4497. {
  4498. int len;
  4499. expdest = makestrspace(32, expdest);
  4500. #if ENABLE_ASH_MATH_SUPPORT_64
  4501. len = fmtstr(expdest, 32, "%lld", (long long) num);
  4502. #else
  4503. len = fmtstr(expdest, 32, "%ld", num);
  4504. #endif
  4505. STADJUST(len, expdest);
  4506. return len;
  4507. }
  4508. static size_t
  4509. esclen(const char *start, const char *p)
  4510. {
  4511. size_t esc = 0;
  4512. while (p > start && *--p == CTLESC) {
  4513. esc++;
  4514. }
  4515. return esc;
  4516. }
  4517. /*
  4518. * Remove any CTLESC characters from a string.
  4519. */
  4520. static char *
  4521. _rmescapes(char *str, int flag)
  4522. {
  4523. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4524. char *p, *q, *r;
  4525. unsigned inquotes;
  4526. int notescaped;
  4527. int globbing;
  4528. p = strpbrk(str, qchars);
  4529. if (!p) {
  4530. return str;
  4531. }
  4532. q = p;
  4533. r = str;
  4534. if (flag & RMESCAPE_ALLOC) {
  4535. size_t len = p - str;
  4536. size_t fulllen = len + strlen(p) + 1;
  4537. if (flag & RMESCAPE_GROW) {
  4538. r = makestrspace(fulllen, expdest);
  4539. } else if (flag & RMESCAPE_HEAP) {
  4540. r = ckmalloc(fulllen);
  4541. } else {
  4542. r = stalloc(fulllen);
  4543. }
  4544. q = r;
  4545. if (len > 0) {
  4546. q = memcpy(q, str, len) + len;
  4547. }
  4548. }
  4549. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4550. globbing = flag & RMESCAPE_GLOB;
  4551. notescaped = globbing;
  4552. while (*p) {
  4553. if (*p == CTLQUOTEMARK) {
  4554. inquotes = ~inquotes;
  4555. p++;
  4556. notescaped = globbing;
  4557. continue;
  4558. }
  4559. if (*p == '\\') {
  4560. /* naked back slash */
  4561. notescaped = 0;
  4562. goto copy;
  4563. }
  4564. if (*p == CTLESC) {
  4565. p++;
  4566. if (notescaped && inquotes && *p != '/') {
  4567. *q++ = '\\';
  4568. }
  4569. }
  4570. notescaped = globbing;
  4571. copy:
  4572. *q++ = *p++;
  4573. }
  4574. *q = '\0';
  4575. if (flag & RMESCAPE_GROW) {
  4576. expdest = r;
  4577. STADJUST(q - r + 1, expdest);
  4578. }
  4579. return r;
  4580. }
  4581. #define rmescapes(p) _rmescapes((p), 0)
  4582. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4583. /*
  4584. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4585. *
  4586. * Returns an stalloced string.
  4587. */
  4588. static char *
  4589. preglob(const char *pattern, int quoted, int flag)
  4590. {
  4591. flag |= RMESCAPE_GLOB;
  4592. if (quoted) {
  4593. flag |= RMESCAPE_QUOTED;
  4594. }
  4595. return _rmescapes((char *)pattern, flag);
  4596. }
  4597. /*
  4598. * Put a string on the stack.
  4599. */
  4600. static void
  4601. memtodest(const char *p, size_t len, int syntax, int quotes)
  4602. {
  4603. char *q = expdest;
  4604. q = makestrspace(len * 2, q);
  4605. while (len--) {
  4606. int c = signed_char2int(*p++);
  4607. if (!c)
  4608. continue;
  4609. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4610. USTPUTC(CTLESC, q);
  4611. USTPUTC(c, q);
  4612. }
  4613. expdest = q;
  4614. }
  4615. static void
  4616. strtodest(const char *p, int syntax, int quotes)
  4617. {
  4618. memtodest(p, strlen(p), syntax, quotes);
  4619. }
  4620. /*
  4621. * Record the fact that we have to scan this region of the
  4622. * string for IFS characters.
  4623. */
  4624. static void
  4625. recordregion(int start, int end, int nulonly)
  4626. {
  4627. struct ifsregion *ifsp;
  4628. if (ifslastp == NULL) {
  4629. ifsp = &ifsfirst;
  4630. } else {
  4631. INT_OFF;
  4632. ifsp = ckmalloc(sizeof(*ifsp));
  4633. ifsp->next = NULL;
  4634. ifslastp->next = ifsp;
  4635. INT_ON;
  4636. }
  4637. ifslastp = ifsp;
  4638. ifslastp->begoff = start;
  4639. ifslastp->endoff = end;
  4640. ifslastp->nulonly = nulonly;
  4641. }
  4642. static void
  4643. removerecordregions(int endoff)
  4644. {
  4645. if (ifslastp == NULL)
  4646. return;
  4647. if (ifsfirst.endoff > endoff) {
  4648. while (ifsfirst.next != NULL) {
  4649. struct ifsregion *ifsp;
  4650. INT_OFF;
  4651. ifsp = ifsfirst.next->next;
  4652. free(ifsfirst.next);
  4653. ifsfirst.next = ifsp;
  4654. INT_ON;
  4655. }
  4656. if (ifsfirst.begoff > endoff)
  4657. ifslastp = NULL;
  4658. else {
  4659. ifslastp = &ifsfirst;
  4660. ifsfirst.endoff = endoff;
  4661. }
  4662. return;
  4663. }
  4664. ifslastp = &ifsfirst;
  4665. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4666. ifslastp=ifslastp->next;
  4667. while (ifslastp->next != NULL) {
  4668. struct ifsregion *ifsp;
  4669. INT_OFF;
  4670. ifsp = ifslastp->next->next;
  4671. free(ifslastp->next);
  4672. ifslastp->next = ifsp;
  4673. INT_ON;
  4674. }
  4675. if (ifslastp->endoff > endoff)
  4676. ifslastp->endoff = endoff;
  4677. }
  4678. static char *
  4679. exptilde(char *startp, char *p, int flag)
  4680. {
  4681. char c;
  4682. char *name;
  4683. struct passwd *pw;
  4684. const char *home;
  4685. int quotes = flag & (EXP_FULL | EXP_CASE);
  4686. int startloc;
  4687. name = p + 1;
  4688. while ((c = *++p) != '\0') {
  4689. switch (c) {
  4690. case CTLESC:
  4691. return startp;
  4692. case CTLQUOTEMARK:
  4693. return startp;
  4694. case ':':
  4695. if (flag & EXP_VARTILDE)
  4696. goto done;
  4697. break;
  4698. case '/':
  4699. case CTLENDVAR:
  4700. goto done;
  4701. }
  4702. }
  4703. done:
  4704. *p = '\0';
  4705. if (*name == '\0') {
  4706. home = lookupvar(homestr);
  4707. } else {
  4708. pw = getpwnam(name);
  4709. if (pw == NULL)
  4710. goto lose;
  4711. home = pw->pw_dir;
  4712. }
  4713. if (!home || !*home)
  4714. goto lose;
  4715. *p = c;
  4716. startloc = expdest - (char *)stackblock();
  4717. strtodest(home, SQSYNTAX, quotes);
  4718. recordregion(startloc, expdest - (char *)stackblock(), 0);
  4719. return p;
  4720. lose:
  4721. *p = c;
  4722. return startp;
  4723. }
  4724. /*
  4725. * Execute a command inside back quotes. If it's a builtin command, we
  4726. * want to save its output in a block obtained from malloc. Otherwise
  4727. * we fork off a subprocess and get the output of the command via a pipe.
  4728. * Should be called with interrupts off.
  4729. */
  4730. struct backcmd { /* result of evalbackcmd */
  4731. int fd; /* file descriptor to read from */
  4732. char *buf; /* buffer */
  4733. int nleft; /* number of chars in buffer */
  4734. struct job *jp; /* job structure for command */
  4735. };
  4736. /* These forward decls are needed to use "eval" code for backticks handling: */
  4737. static int back_exitstatus; /* exit status of backquoted command */
  4738. #define EV_EXIT 01 /* exit after evaluating tree */
  4739. static void evaltree(union node *, int);
  4740. static void
  4741. evalbackcmd(union node *n, struct backcmd *result)
  4742. {
  4743. int saveherefd;
  4744. result->fd = -1;
  4745. result->buf = NULL;
  4746. result->nleft = 0;
  4747. result->jp = NULL;
  4748. if (n == NULL) {
  4749. goto out;
  4750. }
  4751. saveherefd = herefd;
  4752. herefd = -1;
  4753. {
  4754. int pip[2];
  4755. struct job *jp;
  4756. if (pipe(pip) < 0)
  4757. ash_msg_and_raise_error("pipe call failed");
  4758. jp = makejob(n, 1);
  4759. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  4760. FORCE_INT_ON;
  4761. close(pip[0]);
  4762. if (pip[1] != 1) {
  4763. close(1);
  4764. copyfd(pip[1], 1);
  4765. close(pip[1]);
  4766. }
  4767. eflag = 0;
  4768. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  4769. /* NOTREACHED */
  4770. }
  4771. close(pip[1]);
  4772. result->fd = pip[0];
  4773. result->jp = jp;
  4774. }
  4775. herefd = saveherefd;
  4776. out:
  4777. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  4778. result->fd, result->buf, result->nleft, result->jp));
  4779. }
  4780. /*
  4781. * Expand stuff in backwards quotes.
  4782. */
  4783. static void
  4784. expbackq(union node *cmd, int quoted, int quotes)
  4785. {
  4786. struct backcmd in;
  4787. int i;
  4788. char buf[128];
  4789. char *p;
  4790. char *dest;
  4791. int startloc;
  4792. int syntax = quoted? DQSYNTAX : BASESYNTAX;
  4793. struct stackmark smark;
  4794. INT_OFF;
  4795. setstackmark(&smark);
  4796. dest = expdest;
  4797. startloc = dest - (char *)stackblock();
  4798. grabstackstr(dest);
  4799. evalbackcmd(cmd, &in);
  4800. popstackmark(&smark);
  4801. p = in.buf;
  4802. i = in.nleft;
  4803. if (i == 0)
  4804. goto read;
  4805. for (;;) {
  4806. memtodest(p, i, syntax, quotes);
  4807. read:
  4808. if (in.fd < 0)
  4809. break;
  4810. i = safe_read(in.fd, buf, sizeof(buf));
  4811. TRACE(("expbackq: read returns %d\n", i));
  4812. if (i <= 0)
  4813. break;
  4814. p = buf;
  4815. }
  4816. free(in.buf);
  4817. if (in.fd >= 0) {
  4818. close(in.fd);
  4819. back_exitstatus = waitforjob(in.jp);
  4820. }
  4821. INT_ON;
  4822. /* Eat all trailing newlines */
  4823. dest = expdest;
  4824. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  4825. STUNPUTC(dest);
  4826. expdest = dest;
  4827. if (quoted == 0)
  4828. recordregion(startloc, dest - (char *)stackblock(), 0);
  4829. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  4830. (dest - (char *)stackblock()) - startloc,
  4831. (dest - (char *)stackblock()) - startloc,
  4832. stackblock() + startloc));
  4833. }
  4834. #if ENABLE_ASH_MATH_SUPPORT
  4835. /*
  4836. * Expand arithmetic expression. Backup to start of expression,
  4837. * evaluate, place result in (backed up) result, adjust string position.
  4838. */
  4839. static void
  4840. expari(int quotes)
  4841. {
  4842. char *p, *start;
  4843. int begoff;
  4844. int flag;
  4845. int len;
  4846. /* ifsfree(); */
  4847. /*
  4848. * This routine is slightly over-complicated for
  4849. * efficiency. Next we scan backwards looking for the
  4850. * start of arithmetic.
  4851. */
  4852. start = stackblock();
  4853. p = expdest - 1;
  4854. *p = '\0';
  4855. p--;
  4856. do {
  4857. int esc;
  4858. while (*p != CTLARI) {
  4859. p--;
  4860. #if DEBUG
  4861. if (p < start) {
  4862. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  4863. }
  4864. #endif
  4865. }
  4866. esc = esclen(start, p);
  4867. if (!(esc % 2)) {
  4868. break;
  4869. }
  4870. p -= esc + 1;
  4871. } while (1);
  4872. begoff = p - start;
  4873. removerecordregions(begoff);
  4874. flag = p[1];
  4875. expdest = p;
  4876. if (quotes)
  4877. rmescapes(p + 2);
  4878. len = cvtnum(dash_arith(p + 2));
  4879. if (flag != '"')
  4880. recordregion(begoff, begoff + len, 0);
  4881. }
  4882. #endif
  4883. /* argstr needs it */
  4884. static char *evalvar(char *p, int flag);
  4885. /*
  4886. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  4887. * characters to allow for further processing. Otherwise treat
  4888. * $@ like $* since no splitting will be performed.
  4889. */
  4890. static void
  4891. argstr(char *p, int flag)
  4892. {
  4893. static const char spclchars[] ALIGN1 = {
  4894. '=',
  4895. ':',
  4896. CTLQUOTEMARK,
  4897. CTLENDVAR,
  4898. CTLESC,
  4899. CTLVAR,
  4900. CTLBACKQ,
  4901. CTLBACKQ | CTLQUOTE,
  4902. #if ENABLE_ASH_MATH_SUPPORT
  4903. CTLENDARI,
  4904. #endif
  4905. 0
  4906. };
  4907. const char *reject = spclchars;
  4908. int c;
  4909. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  4910. int breakall = flag & EXP_WORD;
  4911. int inquotes;
  4912. size_t length;
  4913. int startloc;
  4914. if (!(flag & EXP_VARTILDE)) {
  4915. reject += 2;
  4916. } else if (flag & EXP_VARTILDE2) {
  4917. reject++;
  4918. }
  4919. inquotes = 0;
  4920. length = 0;
  4921. if (flag & EXP_TILDE) {
  4922. char *q;
  4923. flag &= ~EXP_TILDE;
  4924. tilde:
  4925. q = p;
  4926. if (*q == CTLESC && (flag & EXP_QWORD))
  4927. q++;
  4928. if (*q == '~')
  4929. p = exptilde(p, q, flag);
  4930. }
  4931. start:
  4932. startloc = expdest - (char *)stackblock();
  4933. for (;;) {
  4934. length += strcspn(p + length, reject);
  4935. c = p[length];
  4936. if (c && (!(c & 0x80)
  4937. #if ENABLE_ASH_MATH_SUPPORT
  4938. || c == CTLENDARI
  4939. #endif
  4940. )) {
  4941. /* c == '=' || c == ':' || c == CTLENDARI */
  4942. length++;
  4943. }
  4944. if (length > 0) {
  4945. int newloc;
  4946. expdest = stack_nputstr(p, length, expdest);
  4947. newloc = expdest - (char *)stackblock();
  4948. if (breakall && !inquotes && newloc > startloc) {
  4949. recordregion(startloc, newloc, 0);
  4950. }
  4951. startloc = newloc;
  4952. }
  4953. p += length + 1;
  4954. length = 0;
  4955. switch (c) {
  4956. case '\0':
  4957. goto breakloop;
  4958. case '=':
  4959. if (flag & EXP_VARTILDE2) {
  4960. p--;
  4961. continue;
  4962. }
  4963. flag |= EXP_VARTILDE2;
  4964. reject++;
  4965. /* fall through */
  4966. case ':':
  4967. /*
  4968. * sort of a hack - expand tildes in variable
  4969. * assignments (after the first '=' and after ':'s).
  4970. */
  4971. if (*--p == '~') {
  4972. goto tilde;
  4973. }
  4974. continue;
  4975. }
  4976. switch (c) {
  4977. case CTLENDVAR: /* ??? */
  4978. goto breakloop;
  4979. case CTLQUOTEMARK:
  4980. /* "$@" syntax adherence hack */
  4981. if (
  4982. !inquotes &&
  4983. !memcmp(p, dolatstr, 4) &&
  4984. (p[4] == CTLQUOTEMARK || (
  4985. p[4] == CTLENDVAR &&
  4986. p[5] == CTLQUOTEMARK
  4987. ))
  4988. ) {
  4989. p = evalvar(p + 1, flag) + 1;
  4990. goto start;
  4991. }
  4992. inquotes = !inquotes;
  4993. addquote:
  4994. if (quotes) {
  4995. p--;
  4996. length++;
  4997. startloc++;
  4998. }
  4999. break;
  5000. case CTLESC:
  5001. startloc++;
  5002. length++;
  5003. goto addquote;
  5004. case CTLVAR:
  5005. p = evalvar(p, flag);
  5006. goto start;
  5007. case CTLBACKQ:
  5008. c = 0;
  5009. case CTLBACKQ|CTLQUOTE:
  5010. expbackq(argbackq->n, c, quotes);
  5011. argbackq = argbackq->next;
  5012. goto start;
  5013. #if ENABLE_ASH_MATH_SUPPORT
  5014. case CTLENDARI:
  5015. p--;
  5016. expari(quotes);
  5017. goto start;
  5018. #endif
  5019. }
  5020. }
  5021. breakloop:
  5022. ;
  5023. }
  5024. static char *
  5025. scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5026. int zero)
  5027. {
  5028. char *loc;
  5029. char *loc2;
  5030. char c;
  5031. loc = startp;
  5032. loc2 = rmesc;
  5033. do {
  5034. int match;
  5035. const char *s = loc2;
  5036. c = *loc2;
  5037. if (zero) {
  5038. *loc2 = '\0';
  5039. s = rmesc;
  5040. }
  5041. match = pmatch(str, s);
  5042. *loc2 = c;
  5043. if (match)
  5044. return loc;
  5045. if (quotes && *loc == CTLESC)
  5046. loc++;
  5047. loc++;
  5048. loc2++;
  5049. } while (c);
  5050. return 0;
  5051. }
  5052. static char *
  5053. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5054. int zero)
  5055. {
  5056. int esc = 0;
  5057. char *loc;
  5058. char *loc2;
  5059. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5060. int match;
  5061. char c = *loc2;
  5062. const char *s = loc2;
  5063. if (zero) {
  5064. *loc2 = '\0';
  5065. s = rmesc;
  5066. }
  5067. match = pmatch(str, s);
  5068. *loc2 = c;
  5069. if (match)
  5070. return loc;
  5071. loc--;
  5072. if (quotes) {
  5073. if (--esc < 0) {
  5074. esc = esclen(startp, loc);
  5075. }
  5076. if (esc % 2) {
  5077. esc--;
  5078. loc--;
  5079. }
  5080. }
  5081. }
  5082. return 0;
  5083. }
  5084. static void varunset(const char *, const char *, const char *, int) ATTRIBUTE_NORETURN;
  5085. static void
  5086. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5087. {
  5088. const char *msg;
  5089. const char *tail;
  5090. tail = nullstr;
  5091. msg = "parameter not set";
  5092. if (umsg) {
  5093. if (*end == CTLENDVAR) {
  5094. if (varflags & VSNUL)
  5095. tail = " or null";
  5096. } else
  5097. msg = umsg;
  5098. }
  5099. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5100. }
  5101. static const char *
  5102. subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
  5103. {
  5104. char *startp;
  5105. char *loc;
  5106. int saveherefd = herefd;
  5107. struct nodelist *saveargbackq = argbackq;
  5108. int amount;
  5109. char *rmesc, *rmescend;
  5110. int zero;
  5111. char *(*scan)(char *, char *, char *, char *, int , int);
  5112. herefd = -1;
  5113. argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
  5114. STPUTC('\0', expdest);
  5115. herefd = saveherefd;
  5116. argbackq = saveargbackq;
  5117. startp = stackblock() + startloc;
  5118. switch (subtype) {
  5119. case VSASSIGN:
  5120. setvar(str, startp, 0);
  5121. amount = startp - expdest;
  5122. STADJUST(amount, expdest);
  5123. return startp;
  5124. case VSQUESTION:
  5125. varunset(p, str, startp, varflags);
  5126. /* NOTREACHED */
  5127. }
  5128. subtype -= VSTRIMRIGHT;
  5129. #if DEBUG
  5130. if (subtype < 0 || subtype > 3)
  5131. abort();
  5132. #endif
  5133. rmesc = startp;
  5134. rmescend = stackblock() + strloc;
  5135. if (quotes) {
  5136. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5137. if (rmesc != startp) {
  5138. rmescend = expdest;
  5139. startp = stackblock() + startloc;
  5140. }
  5141. }
  5142. rmescend--;
  5143. str = stackblock() + strloc;
  5144. preglob(str, varflags & VSQUOTE, 0);
  5145. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  5146. zero = subtype >> 1;
  5147. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5148. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5149. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5150. if (loc) {
  5151. if (zero) {
  5152. memmove(startp, loc, str - loc);
  5153. loc = startp + (str - loc) - 1;
  5154. }
  5155. *loc = '\0';
  5156. amount = loc - expdest;
  5157. STADJUST(amount, expdest);
  5158. }
  5159. return loc;
  5160. }
  5161. /*
  5162. * Add the value of a specialized variable to the stack string.
  5163. */
  5164. static ssize_t
  5165. varvalue(char *name, int varflags, int flags)
  5166. {
  5167. int num;
  5168. char *p;
  5169. int i;
  5170. int sep = 0;
  5171. int sepq = 0;
  5172. ssize_t len = 0;
  5173. char **ap;
  5174. int syntax;
  5175. int quoted = varflags & VSQUOTE;
  5176. int subtype = varflags & VSTYPE;
  5177. int quotes = flags & (EXP_FULL | EXP_CASE);
  5178. if (quoted && (flags & EXP_FULL))
  5179. sep = 1 << CHAR_BIT;
  5180. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5181. switch (*name) {
  5182. case '$':
  5183. num = rootpid;
  5184. goto numvar;
  5185. case '?':
  5186. num = exitstatus;
  5187. goto numvar;
  5188. case '#':
  5189. num = shellparam.nparam;
  5190. goto numvar;
  5191. case '!':
  5192. num = backgndpid;
  5193. if (num == 0)
  5194. return -1;
  5195. numvar:
  5196. len = cvtnum(num);
  5197. break;
  5198. case '-':
  5199. p = makestrspace(NOPTS, expdest);
  5200. for (i = NOPTS - 1; i >= 0; i--) {
  5201. if (optlist[i]) {
  5202. USTPUTC(optletters(i), p);
  5203. len++;
  5204. }
  5205. }
  5206. expdest = p;
  5207. break;
  5208. case '@':
  5209. if (sep)
  5210. goto param;
  5211. /* fall through */
  5212. case '*':
  5213. sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
  5214. if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
  5215. sepq = 1;
  5216. param:
  5217. ap = shellparam.p;
  5218. if (!ap)
  5219. return -1;
  5220. while ((p = *ap++)) {
  5221. size_t partlen;
  5222. partlen = strlen(p);
  5223. len += partlen;
  5224. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5225. memtodest(p, partlen, syntax, quotes);
  5226. if (*ap && sep) {
  5227. char *q;
  5228. len++;
  5229. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5230. continue;
  5231. }
  5232. q = expdest;
  5233. if (sepq)
  5234. STPUTC(CTLESC, q);
  5235. STPUTC(sep, q);
  5236. expdest = q;
  5237. }
  5238. }
  5239. return len;
  5240. case '0':
  5241. case '1':
  5242. case '2':
  5243. case '3':
  5244. case '4':
  5245. case '5':
  5246. case '6':
  5247. case '7':
  5248. case '8':
  5249. case '9':
  5250. num = atoi(name);
  5251. if (num < 0 || num > shellparam.nparam)
  5252. return -1;
  5253. p = num ? shellparam.p[num - 1] : arg0;
  5254. goto value;
  5255. default:
  5256. p = lookupvar(name);
  5257. value:
  5258. if (!p)
  5259. return -1;
  5260. len = strlen(p);
  5261. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5262. memtodest(p, len, syntax, quotes);
  5263. return len;
  5264. }
  5265. if (subtype == VSPLUS || subtype == VSLENGTH)
  5266. STADJUST(-len, expdest);
  5267. return len;
  5268. }
  5269. /*
  5270. * Expand a variable, and return a pointer to the next character in the
  5271. * input string.
  5272. */
  5273. static char *
  5274. evalvar(char *p, int flag)
  5275. {
  5276. int subtype;
  5277. int varflags;
  5278. char *var;
  5279. int patloc;
  5280. int c;
  5281. int startloc;
  5282. ssize_t varlen;
  5283. int easy;
  5284. int quotes;
  5285. int quoted;
  5286. quotes = flag & (EXP_FULL | EXP_CASE);
  5287. varflags = *p++;
  5288. subtype = varflags & VSTYPE;
  5289. quoted = varflags & VSQUOTE;
  5290. var = p;
  5291. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5292. startloc = expdest - (char *)stackblock();
  5293. p = strchr(p, '=') + 1;
  5294. again:
  5295. varlen = varvalue(var, varflags, flag);
  5296. if (varflags & VSNUL)
  5297. varlen--;
  5298. if (subtype == VSPLUS) {
  5299. varlen = -1 - varlen;
  5300. goto vsplus;
  5301. }
  5302. if (subtype == VSMINUS) {
  5303. vsplus:
  5304. if (varlen < 0) {
  5305. argstr(
  5306. p, flag | EXP_TILDE |
  5307. (quoted ? EXP_QWORD : EXP_WORD)
  5308. );
  5309. goto end;
  5310. }
  5311. if (easy)
  5312. goto record;
  5313. goto end;
  5314. }
  5315. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  5316. if (varlen < 0) {
  5317. if (subevalvar(p, var, 0, subtype, startloc, varflags, 0)) {
  5318. varflags &= ~VSNUL;
  5319. /*
  5320. * Remove any recorded regions beyond
  5321. * start of variable
  5322. */
  5323. removerecordregions(startloc);
  5324. goto again;
  5325. }
  5326. goto end;
  5327. }
  5328. if (easy)
  5329. goto record;
  5330. goto end;
  5331. }
  5332. if (varlen < 0 && uflag)
  5333. varunset(p, var, 0, 0);
  5334. if (subtype == VSLENGTH) {
  5335. cvtnum(varlen > 0 ? varlen : 0);
  5336. goto record;
  5337. }
  5338. if (subtype == VSNORMAL) {
  5339. if (!easy)
  5340. goto end;
  5341. record:
  5342. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  5343. goto end;
  5344. }
  5345. #if DEBUG
  5346. switch (subtype) {
  5347. case VSTRIMLEFT:
  5348. case VSTRIMLEFTMAX:
  5349. case VSTRIMRIGHT:
  5350. case VSTRIMRIGHTMAX:
  5351. break;
  5352. default:
  5353. abort();
  5354. }
  5355. #endif
  5356. if (varlen >= 0) {
  5357. /*
  5358. * Terminate the string and start recording the pattern
  5359. * right after it
  5360. */
  5361. STPUTC('\0', expdest);
  5362. patloc = expdest - (char *)stackblock();
  5363. if (subevalvar(p, NULL, patloc, subtype,
  5364. startloc, varflags, quotes) == 0) {
  5365. int amount = expdest - (
  5366. (char *)stackblock() + patloc - 1
  5367. );
  5368. STADJUST(-amount, expdest);
  5369. }
  5370. /* Remove any recorded regions beyond start of variable */
  5371. removerecordregions(startloc);
  5372. goto record;
  5373. }
  5374. end:
  5375. if (subtype != VSNORMAL) { /* skip to end of alternative */
  5376. int nesting = 1;
  5377. for (;;) {
  5378. c = *p++;
  5379. if (c == CTLESC)
  5380. p++;
  5381. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  5382. if (varlen >= 0)
  5383. argbackq = argbackq->next;
  5384. } else if (c == CTLVAR) {
  5385. if ((*p++ & VSTYPE) != VSNORMAL)
  5386. nesting++;
  5387. } else if (c == CTLENDVAR) {
  5388. if (--nesting == 0)
  5389. break;
  5390. }
  5391. }
  5392. }
  5393. return p;
  5394. }
  5395. /*
  5396. * Break the argument string into pieces based upon IFS and add the
  5397. * strings to the argument list. The regions of the string to be
  5398. * searched for IFS characters have been stored by recordregion.
  5399. */
  5400. static void
  5401. ifsbreakup(char *string, struct arglist *arglist)
  5402. {
  5403. struct ifsregion *ifsp;
  5404. struct strlist *sp;
  5405. char *start;
  5406. char *p;
  5407. char *q;
  5408. const char *ifs, *realifs;
  5409. int ifsspc;
  5410. int nulonly;
  5411. start = string;
  5412. if (ifslastp != NULL) {
  5413. ifsspc = 0;
  5414. nulonly = 0;
  5415. realifs = ifsset() ? ifsval() : defifs;
  5416. ifsp = &ifsfirst;
  5417. do {
  5418. p = string + ifsp->begoff;
  5419. nulonly = ifsp->nulonly;
  5420. ifs = nulonly ? nullstr : realifs;
  5421. ifsspc = 0;
  5422. while (p < string + ifsp->endoff) {
  5423. q = p;
  5424. if (*p == CTLESC)
  5425. p++;
  5426. if (!strchr(ifs, *p)) {
  5427. p++;
  5428. continue;
  5429. }
  5430. if (!nulonly)
  5431. ifsspc = (strchr(defifs, *p) != NULL);
  5432. /* Ignore IFS whitespace at start */
  5433. if (q == start && ifsspc) {
  5434. p++;
  5435. start = p;
  5436. continue;
  5437. }
  5438. *q = '\0';
  5439. sp = stalloc(sizeof(*sp));
  5440. sp->text = start;
  5441. *arglist->lastp = sp;
  5442. arglist->lastp = &sp->next;
  5443. p++;
  5444. if (!nulonly) {
  5445. for (;;) {
  5446. if (p >= string + ifsp->endoff) {
  5447. break;
  5448. }
  5449. q = p;
  5450. if (*p == CTLESC)
  5451. p++;
  5452. if (strchr(ifs, *p) == NULL ) {
  5453. p = q;
  5454. break;
  5455. } else if (strchr(defifs, *p) == NULL) {
  5456. if (ifsspc) {
  5457. p++;
  5458. ifsspc = 0;
  5459. } else {
  5460. p = q;
  5461. break;
  5462. }
  5463. } else
  5464. p++;
  5465. }
  5466. }
  5467. start = p;
  5468. } /* while */
  5469. ifsp = ifsp->next;
  5470. } while (ifsp != NULL);
  5471. if (nulonly)
  5472. goto add;
  5473. }
  5474. if (!*start)
  5475. return;
  5476. add:
  5477. sp = stalloc(sizeof(*sp));
  5478. sp->text = start;
  5479. *arglist->lastp = sp;
  5480. arglist->lastp = &sp->next;
  5481. }
  5482. static void
  5483. ifsfree(void)
  5484. {
  5485. struct ifsregion *p;
  5486. INT_OFF;
  5487. p = ifsfirst.next;
  5488. do {
  5489. struct ifsregion *ifsp;
  5490. ifsp = p->next;
  5491. free(p);
  5492. p = ifsp;
  5493. } while (p);
  5494. ifslastp = NULL;
  5495. ifsfirst.next = NULL;
  5496. INT_ON;
  5497. }
  5498. /*
  5499. * Add a file name to the list.
  5500. */
  5501. static void
  5502. addfname(const char *name)
  5503. {
  5504. struct strlist *sp;
  5505. sp = stalloc(sizeof(*sp));
  5506. sp->text = ststrdup(name);
  5507. *exparg.lastp = sp;
  5508. exparg.lastp = &sp->next;
  5509. }
  5510. static char *expdir;
  5511. /*
  5512. * Do metacharacter (i.e. *, ?, [...]) expansion.
  5513. */
  5514. static void
  5515. expmeta(char *enddir, char *name)
  5516. {
  5517. char *p;
  5518. const char *cp;
  5519. char *start;
  5520. char *endname;
  5521. int metaflag;
  5522. struct stat statb;
  5523. DIR *dirp;
  5524. struct dirent *dp;
  5525. int atend;
  5526. int matchdot;
  5527. metaflag = 0;
  5528. start = name;
  5529. for (p = name; *p; p++) {
  5530. if (*p == '*' || *p == '?')
  5531. metaflag = 1;
  5532. else if (*p == '[') {
  5533. char *q = p + 1;
  5534. if (*q == '!')
  5535. q++;
  5536. for (;;) {
  5537. if (*q == '\\')
  5538. q++;
  5539. if (*q == '/' || *q == '\0')
  5540. break;
  5541. if (*++q == ']') {
  5542. metaflag = 1;
  5543. break;
  5544. }
  5545. }
  5546. } else if (*p == '\\')
  5547. p++;
  5548. else if (*p == '/') {
  5549. if (metaflag)
  5550. goto out;
  5551. start = p + 1;
  5552. }
  5553. }
  5554. out:
  5555. if (metaflag == 0) { /* we've reached the end of the file name */
  5556. if (enddir != expdir)
  5557. metaflag++;
  5558. p = name;
  5559. do {
  5560. if (*p == '\\')
  5561. p++;
  5562. *enddir++ = *p;
  5563. } while (*p++);
  5564. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  5565. addfname(expdir);
  5566. return;
  5567. }
  5568. endname = p;
  5569. if (name < start) {
  5570. p = name;
  5571. do {
  5572. if (*p == '\\')
  5573. p++;
  5574. *enddir++ = *p++;
  5575. } while (p < start);
  5576. }
  5577. if (enddir == expdir) {
  5578. cp = ".";
  5579. } else if (enddir == expdir + 1 && *expdir == '/') {
  5580. cp = "/";
  5581. } else {
  5582. cp = expdir;
  5583. enddir[-1] = '\0';
  5584. }
  5585. dirp = opendir(cp);
  5586. if (dirp == NULL)
  5587. return;
  5588. if (enddir != expdir)
  5589. enddir[-1] = '/';
  5590. if (*endname == 0) {
  5591. atend = 1;
  5592. } else {
  5593. atend = 0;
  5594. *endname++ = '\0';
  5595. }
  5596. matchdot = 0;
  5597. p = start;
  5598. if (*p == '\\')
  5599. p++;
  5600. if (*p == '.')
  5601. matchdot++;
  5602. while (! intpending && (dp = readdir(dirp)) != NULL) {
  5603. if (dp->d_name[0] == '.' && ! matchdot)
  5604. continue;
  5605. if (pmatch(start, dp->d_name)) {
  5606. if (atend) {
  5607. strcpy(enddir, dp->d_name);
  5608. addfname(expdir);
  5609. } else {
  5610. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  5611. continue;
  5612. p[-1] = '/';
  5613. expmeta(p, endname);
  5614. }
  5615. }
  5616. }
  5617. closedir(dirp);
  5618. if (! atend)
  5619. endname[-1] = '/';
  5620. }
  5621. static struct strlist *
  5622. msort(struct strlist *list, int len)
  5623. {
  5624. struct strlist *p, *q = NULL;
  5625. struct strlist **lpp;
  5626. int half;
  5627. int n;
  5628. if (len <= 1)
  5629. return list;
  5630. half = len >> 1;
  5631. p = list;
  5632. for (n = half; --n >= 0; ) {
  5633. q = p;
  5634. p = p->next;
  5635. }
  5636. q->next = NULL; /* terminate first half of list */
  5637. q = msort(list, half); /* sort first half of list */
  5638. p = msort(p, len - half); /* sort second half */
  5639. lpp = &list;
  5640. for (;;) {
  5641. #if ENABLE_LOCALE_SUPPORT
  5642. if (strcoll(p->text, q->text) < 0)
  5643. #else
  5644. if (strcmp(p->text, q->text) < 0)
  5645. #endif
  5646. {
  5647. *lpp = p;
  5648. lpp = &p->next;
  5649. p = *lpp;
  5650. if (p == NULL) {
  5651. *lpp = q;
  5652. break;
  5653. }
  5654. } else {
  5655. *lpp = q;
  5656. lpp = &q->next;
  5657. q = *lpp;
  5658. if (q == NULL) {
  5659. *lpp = p;
  5660. break;
  5661. }
  5662. }
  5663. }
  5664. return list;
  5665. }
  5666. /*
  5667. * Sort the results of file name expansion. It calculates the number of
  5668. * strings to sort and then calls msort (short for merge sort) to do the
  5669. * work.
  5670. */
  5671. static struct strlist *
  5672. expsort(struct strlist *str)
  5673. {
  5674. int len;
  5675. struct strlist *sp;
  5676. len = 0;
  5677. for (sp = str; sp; sp = sp->next)
  5678. len++;
  5679. return msort(str, len);
  5680. }
  5681. static void
  5682. expandmeta(struct strlist *str, int flag)
  5683. {
  5684. static const char metachars[] ALIGN1 = {
  5685. '*', '?', '[', 0
  5686. };
  5687. /* TODO - EXP_REDIR */
  5688. while (str) {
  5689. struct strlist **savelastp;
  5690. struct strlist *sp;
  5691. char *p;
  5692. if (fflag)
  5693. goto nometa;
  5694. if (!strpbrk(str->text, metachars))
  5695. goto nometa;
  5696. savelastp = exparg.lastp;
  5697. INT_OFF;
  5698. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  5699. {
  5700. int i = strlen(str->text);
  5701. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  5702. }
  5703. expmeta(expdir, p);
  5704. free(expdir);
  5705. if (p != str->text)
  5706. free(p);
  5707. INT_ON;
  5708. if (exparg.lastp == savelastp) {
  5709. /*
  5710. * no matches
  5711. */
  5712. nometa:
  5713. *exparg.lastp = str;
  5714. rmescapes(str->text);
  5715. exparg.lastp = &str->next;
  5716. } else {
  5717. *exparg.lastp = NULL;
  5718. *savelastp = sp = expsort(*savelastp);
  5719. while (sp->next != NULL)
  5720. sp = sp->next;
  5721. exparg.lastp = &sp->next;
  5722. }
  5723. str = str->next;
  5724. }
  5725. }
  5726. /*
  5727. * Perform variable substitution and command substitution on an argument,
  5728. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  5729. * perform splitting and file name expansion. When arglist is NULL, perform
  5730. * here document expansion.
  5731. */
  5732. static void
  5733. expandarg(union node *arg, struct arglist *arglist, int flag)
  5734. {
  5735. struct strlist *sp;
  5736. char *p;
  5737. argbackq = arg->narg.backquote;
  5738. STARTSTACKSTR(expdest);
  5739. ifsfirst.next = NULL;
  5740. ifslastp = NULL;
  5741. argstr(arg->narg.text, flag);
  5742. p = _STPUTC('\0', expdest);
  5743. expdest = p - 1;
  5744. if (arglist == NULL) {
  5745. return; /* here document expanded */
  5746. }
  5747. p = grabstackstr(p);
  5748. exparg.lastp = &exparg.list;
  5749. /*
  5750. * TODO - EXP_REDIR
  5751. */
  5752. if (flag & EXP_FULL) {
  5753. ifsbreakup(p, &exparg);
  5754. *exparg.lastp = NULL;
  5755. exparg.lastp = &exparg.list;
  5756. expandmeta(exparg.list, flag);
  5757. } else {
  5758. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  5759. rmescapes(p);
  5760. sp = stalloc(sizeof(*sp));
  5761. sp->text = p;
  5762. *exparg.lastp = sp;
  5763. exparg.lastp = &sp->next;
  5764. }
  5765. if (ifsfirst.next)
  5766. ifsfree();
  5767. *exparg.lastp = NULL;
  5768. if (exparg.list) {
  5769. *arglist->lastp = exparg.list;
  5770. arglist->lastp = exparg.lastp;
  5771. }
  5772. }
  5773. /*
  5774. * Expand shell variables and backquotes inside a here document.
  5775. */
  5776. static void
  5777. expandhere(union node *arg, int fd)
  5778. {
  5779. herefd = fd;
  5780. expandarg(arg, (struct arglist *)NULL, 0);
  5781. full_write(fd, stackblock(), expdest - (char *)stackblock());
  5782. }
  5783. /*
  5784. * Returns true if the pattern matches the string.
  5785. */
  5786. static int
  5787. patmatch(char *pattern, const char *string)
  5788. {
  5789. return pmatch(preglob(pattern, 0, 0), string);
  5790. }
  5791. /*
  5792. * See if a pattern matches in a case statement.
  5793. */
  5794. static int
  5795. casematch(union node *pattern, char *val)
  5796. {
  5797. struct stackmark smark;
  5798. int result;
  5799. setstackmark(&smark);
  5800. argbackq = pattern->narg.backquote;
  5801. STARTSTACKSTR(expdest);
  5802. ifslastp = NULL;
  5803. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  5804. STACKSTRNUL(expdest);
  5805. result = patmatch(stackblock(), val);
  5806. popstackmark(&smark);
  5807. return result;
  5808. }
  5809. /* ============ find_command */
  5810. struct builtincmd {
  5811. const char *name;
  5812. int (*builtin)(int, char **);
  5813. /* unsigned flags; */
  5814. };
  5815. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  5816. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  5817. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  5818. struct cmdentry {
  5819. int cmdtype;
  5820. union param {
  5821. int index;
  5822. const struct builtincmd *cmd;
  5823. struct funcnode *func;
  5824. } u;
  5825. };
  5826. /* values of cmdtype */
  5827. #define CMDUNKNOWN -1 /* no entry in table for command */
  5828. #define CMDNORMAL 0 /* command is an executable program */
  5829. #define CMDFUNCTION 1 /* command is a shell function */
  5830. #define CMDBUILTIN 2 /* command is a shell builtin */
  5831. /* action to find_command() */
  5832. #define DO_ERR 0x01 /* prints errors */
  5833. #define DO_ABS 0x02 /* checks absolute paths */
  5834. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  5835. #define DO_ALTPATH 0x08 /* using alternate path */
  5836. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  5837. static void find_command(char *, struct cmdentry *, int, const char *);
  5838. /* ============ Hashing commands */
  5839. /*
  5840. * When commands are first encountered, they are entered in a hash table.
  5841. * This ensures that a full path search will not have to be done for them
  5842. * on each invocation.
  5843. *
  5844. * We should investigate converting to a linear search, even though that
  5845. * would make the command name "hash" a misnomer.
  5846. */
  5847. #define CMDTABLESIZE 31 /* should be prime */
  5848. #define ARB 1 /* actual size determined at run time */
  5849. struct tblentry {
  5850. struct tblentry *next; /* next entry in hash chain */
  5851. union param param; /* definition of builtin function */
  5852. short cmdtype; /* index identifying command */
  5853. char rehash; /* if set, cd done since entry created */
  5854. char cmdname[ARB]; /* name of command */
  5855. };
  5856. static struct tblentry *cmdtable[CMDTABLESIZE];
  5857. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  5858. static void
  5859. tryexec(char *cmd, char **argv, char **envp)
  5860. {
  5861. int repeated = 0;
  5862. #if ENABLE_FEATURE_SH_STANDALONE
  5863. if (strchr(cmd, '/') == NULL) {
  5864. const struct bb_applet *a;
  5865. a = find_applet_by_name(cmd);
  5866. if (a) {
  5867. if (a->noexec)
  5868. run_appletstruct_and_exit(a, argv);
  5869. /* re-exec ourselves with the new arguments */
  5870. execve(bb_busybox_exec_path, argv, envp);
  5871. /* If they called chroot or otherwise made the binary no longer
  5872. * executable, fall through */
  5873. }
  5874. }
  5875. #endif
  5876. repeat:
  5877. #ifdef SYSV
  5878. do {
  5879. execve(cmd, argv, envp);
  5880. } while (errno == EINTR);
  5881. #else
  5882. execve(cmd, argv, envp);
  5883. #endif
  5884. if (repeated++) {
  5885. free(argv);
  5886. } else if (errno == ENOEXEC) {
  5887. char **ap;
  5888. char **new;
  5889. for (ap = argv; *ap; ap++)
  5890. ;
  5891. ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
  5892. ap[1] = cmd;
  5893. ap[0] = cmd = (char *)DEFAULT_SHELL;
  5894. ap += 2;
  5895. argv++;
  5896. while ((*ap++ = *argv++))
  5897. ;
  5898. argv = new;
  5899. goto repeat;
  5900. }
  5901. }
  5902. /*
  5903. * Exec a program. Never returns. If you change this routine, you may
  5904. * have to change the find_command routine as well.
  5905. */
  5906. #define environment() listvars(VEXPORT, VUNSET, 0)
  5907. static void shellexec(char **, const char *, int) ATTRIBUTE_NORETURN;
  5908. static void
  5909. shellexec(char **argv, const char *path, int idx)
  5910. {
  5911. char *cmdname;
  5912. int e;
  5913. char **envp;
  5914. int exerrno;
  5915. clearredir(1);
  5916. envp = environment();
  5917. if (strchr(argv[0], '/')
  5918. #if ENABLE_FEATURE_SH_STANDALONE
  5919. || find_applet_by_name(argv[0])
  5920. #endif
  5921. ) {
  5922. tryexec(argv[0], argv, envp);
  5923. e = errno;
  5924. } else {
  5925. e = ENOENT;
  5926. while ((cmdname = padvance(&path, argv[0])) != NULL) {
  5927. if (--idx < 0 && pathopt == NULL) {
  5928. tryexec(cmdname, argv, envp);
  5929. if (errno != ENOENT && errno != ENOTDIR)
  5930. e = errno;
  5931. }
  5932. stunalloc(cmdname);
  5933. }
  5934. }
  5935. /* Map to POSIX errors */
  5936. switch (e) {
  5937. case EACCES:
  5938. exerrno = 126;
  5939. break;
  5940. case ENOENT:
  5941. exerrno = 127;
  5942. break;
  5943. default:
  5944. exerrno = 2;
  5945. break;
  5946. }
  5947. exitstatus = exerrno;
  5948. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  5949. argv[0], e, suppressint ));
  5950. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  5951. /* NOTREACHED */
  5952. }
  5953. static void
  5954. printentry(struct tblentry *cmdp)
  5955. {
  5956. int idx;
  5957. const char *path;
  5958. char *name;
  5959. idx = cmdp->param.index;
  5960. path = pathval();
  5961. do {
  5962. name = padvance(&path, cmdp->cmdname);
  5963. stunalloc(name);
  5964. } while (--idx >= 0);
  5965. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  5966. }
  5967. /*
  5968. * Clear out command entries. The argument specifies the first entry in
  5969. * PATH which has changed.
  5970. */
  5971. static void
  5972. clearcmdentry(int firstchange)
  5973. {
  5974. struct tblentry **tblp;
  5975. struct tblentry **pp;
  5976. struct tblentry *cmdp;
  5977. INT_OFF;
  5978. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  5979. pp = tblp;
  5980. while ((cmdp = *pp) != NULL) {
  5981. if ((cmdp->cmdtype == CMDNORMAL &&
  5982. cmdp->param.index >= firstchange)
  5983. || (cmdp->cmdtype == CMDBUILTIN &&
  5984. builtinloc >= firstchange)
  5985. ) {
  5986. *pp = cmdp->next;
  5987. free(cmdp);
  5988. } else {
  5989. pp = &cmdp->next;
  5990. }
  5991. }
  5992. }
  5993. INT_ON;
  5994. }
  5995. /*
  5996. * Locate a command in the command hash table. If "add" is nonzero,
  5997. * add the command to the table if it is not already present. The
  5998. * variable "lastcmdentry" is set to point to the address of the link
  5999. * pointing to the entry, so that delete_cmd_entry can delete the
  6000. * entry.
  6001. *
  6002. * Interrupts must be off if called with add != 0.
  6003. */
  6004. static struct tblentry **lastcmdentry;
  6005. static struct tblentry *
  6006. cmdlookup(const char *name, int add)
  6007. {
  6008. unsigned int hashval;
  6009. const char *p;
  6010. struct tblentry *cmdp;
  6011. struct tblentry **pp;
  6012. p = name;
  6013. hashval = (unsigned char)*p << 4;
  6014. while (*p)
  6015. hashval += (unsigned char)*p++;
  6016. hashval &= 0x7FFF;
  6017. pp = &cmdtable[hashval % CMDTABLESIZE];
  6018. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6019. if (strcmp(cmdp->cmdname, name) == 0)
  6020. break;
  6021. pp = &cmdp->next;
  6022. }
  6023. if (add && cmdp == NULL) {
  6024. cmdp = *pp = ckmalloc(sizeof(struct tblentry) - ARB
  6025. + strlen(name) + 1);
  6026. cmdp->next = NULL;
  6027. cmdp->cmdtype = CMDUNKNOWN;
  6028. strcpy(cmdp->cmdname, name);
  6029. }
  6030. lastcmdentry = pp;
  6031. return cmdp;
  6032. }
  6033. /*
  6034. * Delete the command entry returned on the last lookup.
  6035. */
  6036. static void
  6037. delete_cmd_entry(void)
  6038. {
  6039. struct tblentry *cmdp;
  6040. INT_OFF;
  6041. cmdp = *lastcmdentry;
  6042. *lastcmdentry = cmdp->next;
  6043. if (cmdp->cmdtype == CMDFUNCTION)
  6044. freefunc(cmdp->param.func);
  6045. free(cmdp);
  6046. INT_ON;
  6047. }
  6048. /*
  6049. * Add a new command entry, replacing any existing command entry for
  6050. * the same name - except special builtins.
  6051. */
  6052. static void
  6053. addcmdentry(char *name, struct cmdentry *entry)
  6054. {
  6055. struct tblentry *cmdp;
  6056. cmdp = cmdlookup(name, 1);
  6057. if (cmdp->cmdtype == CMDFUNCTION) {
  6058. freefunc(cmdp->param.func);
  6059. }
  6060. cmdp->cmdtype = entry->cmdtype;
  6061. cmdp->param = entry->u;
  6062. cmdp->rehash = 0;
  6063. }
  6064. static int
  6065. hashcmd(int argc, char **argv)
  6066. {
  6067. struct tblentry **pp;
  6068. struct tblentry *cmdp;
  6069. int c;
  6070. struct cmdentry entry;
  6071. char *name;
  6072. while ((c = nextopt("r")) != '\0') {
  6073. clearcmdentry(0);
  6074. return 0;
  6075. }
  6076. if (*argptr == NULL) {
  6077. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6078. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6079. if (cmdp->cmdtype == CMDNORMAL)
  6080. printentry(cmdp);
  6081. }
  6082. }
  6083. return 0;
  6084. }
  6085. c = 0;
  6086. while ((name = *argptr) != NULL) {
  6087. cmdp = cmdlookup(name, 0);
  6088. if (cmdp != NULL
  6089. && (cmdp->cmdtype == CMDNORMAL
  6090. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
  6091. delete_cmd_entry();
  6092. find_command(name, &entry, DO_ERR, pathval());
  6093. if (entry.cmdtype == CMDUNKNOWN)
  6094. c = 1;
  6095. argptr++;
  6096. }
  6097. return c;
  6098. }
  6099. /*
  6100. * Called when a cd is done. Marks all commands so the next time they
  6101. * are executed they will be rehashed.
  6102. */
  6103. static void
  6104. hashcd(void)
  6105. {
  6106. struct tblentry **pp;
  6107. struct tblentry *cmdp;
  6108. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6109. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6110. if (cmdp->cmdtype == CMDNORMAL || (
  6111. cmdp->cmdtype == CMDBUILTIN &&
  6112. !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
  6113. builtinloc > 0
  6114. ))
  6115. cmdp->rehash = 1;
  6116. }
  6117. }
  6118. }
  6119. /*
  6120. * Fix command hash table when PATH changed.
  6121. * Called before PATH is changed. The argument is the new value of PATH;
  6122. * pathval() still returns the old value at this point.
  6123. * Called with interrupts off.
  6124. */
  6125. static void
  6126. changepath(const char *newval)
  6127. {
  6128. const char *old, *new;
  6129. int idx;
  6130. int firstchange;
  6131. int idx_bltin;
  6132. old = pathval();
  6133. new = newval;
  6134. firstchange = 9999; /* assume no change */
  6135. idx = 0;
  6136. idx_bltin = -1;
  6137. for (;;) {
  6138. if (*old != *new) {
  6139. firstchange = idx;
  6140. if ((*old == '\0' && *new == ':')
  6141. || (*old == ':' && *new == '\0'))
  6142. firstchange++;
  6143. old = new; /* ignore subsequent differences */
  6144. }
  6145. if (*new == '\0')
  6146. break;
  6147. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6148. idx_bltin = idx;
  6149. if (*new == ':') {
  6150. idx++;
  6151. }
  6152. new++, old++;
  6153. }
  6154. if (builtinloc < 0 && idx_bltin >= 0)
  6155. builtinloc = idx_bltin; /* zap builtins */
  6156. if (builtinloc >= 0 && idx_bltin < 0)
  6157. firstchange = 0;
  6158. clearcmdentry(firstchange);
  6159. builtinloc = idx_bltin;
  6160. }
  6161. #define TEOF 0
  6162. #define TNL 1
  6163. #define TREDIR 2
  6164. #define TWORD 3
  6165. #define TSEMI 4
  6166. #define TBACKGND 5
  6167. #define TAND 6
  6168. #define TOR 7
  6169. #define TPIPE 8
  6170. #define TLP 9
  6171. #define TRP 10
  6172. #define TENDCASE 11
  6173. #define TENDBQUOTE 12
  6174. #define TNOT 13
  6175. #define TCASE 14
  6176. #define TDO 15
  6177. #define TDONE 16
  6178. #define TELIF 17
  6179. #define TELSE 18
  6180. #define TESAC 19
  6181. #define TFI 20
  6182. #define TFOR 21
  6183. #define TIF 22
  6184. #define TIN 23
  6185. #define TTHEN 24
  6186. #define TUNTIL 25
  6187. #define TWHILE 26
  6188. #define TBEGIN 27
  6189. #define TEND 28
  6190. /* first char is indicating which tokens mark the end of a list */
  6191. static const char *const tokname_array[] = {
  6192. "\1end of file",
  6193. "\0newline",
  6194. "\0redirection",
  6195. "\0word",
  6196. "\0;",
  6197. "\0&",
  6198. "\0&&",
  6199. "\0||",
  6200. "\0|",
  6201. "\0(",
  6202. "\1)",
  6203. "\1;;",
  6204. "\1`",
  6205. #define KWDOFFSET 13
  6206. /* the following are keywords */
  6207. "\0!",
  6208. "\0case",
  6209. "\1do",
  6210. "\1done",
  6211. "\1elif",
  6212. "\1else",
  6213. "\1esac",
  6214. "\1fi",
  6215. "\0for",
  6216. "\0if",
  6217. "\0in",
  6218. "\1then",
  6219. "\0until",
  6220. "\0while",
  6221. "\0{",
  6222. "\1}",
  6223. };
  6224. static const char *
  6225. tokname(int tok)
  6226. {
  6227. static char buf[16];
  6228. //try this:
  6229. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6230. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6231. //return buf;
  6232. if (tok >= TSEMI)
  6233. buf[0] = '"';
  6234. sprintf(buf + (tok >= TSEMI), "%s%c",
  6235. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6236. return buf;
  6237. }
  6238. /* Wrapper around strcmp for qsort/bsearch/... */
  6239. static int
  6240. pstrcmp(const void *a, const void *b)
  6241. {
  6242. return strcmp((char*) a, (*(char**) b) + 1);
  6243. }
  6244. static const char *const *
  6245. findkwd(const char *s)
  6246. {
  6247. return bsearch(s, tokname_array + KWDOFFSET,
  6248. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6249. sizeof(tokname_array[0]), pstrcmp);
  6250. }
  6251. /*
  6252. * Locate and print what a word is...
  6253. */
  6254. static int
  6255. describe_command(char *command, int describe_command_verbose)
  6256. {
  6257. struct cmdentry entry;
  6258. struct tblentry *cmdp;
  6259. #if ENABLE_ASH_ALIAS
  6260. const struct alias *ap;
  6261. #endif
  6262. const char *path = pathval();
  6263. if (describe_command_verbose) {
  6264. out1str(command);
  6265. }
  6266. /* First look at the keywords */
  6267. if (findkwd(command)) {
  6268. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6269. goto out;
  6270. }
  6271. #if ENABLE_ASH_ALIAS
  6272. /* Then look at the aliases */
  6273. ap = lookupalias(command, 0);
  6274. if (ap != NULL) {
  6275. if (!describe_command_verbose) {
  6276. out1str("alias ");
  6277. printalias(ap);
  6278. return 0;
  6279. }
  6280. out1fmt(" is an alias for %s", ap->val);
  6281. goto out;
  6282. }
  6283. #endif
  6284. /* Then check if it is a tracked alias */
  6285. cmdp = cmdlookup(command, 0);
  6286. if (cmdp != NULL) {
  6287. entry.cmdtype = cmdp->cmdtype;
  6288. entry.u = cmdp->param;
  6289. } else {
  6290. /* Finally use brute force */
  6291. find_command(command, &entry, DO_ABS, path);
  6292. }
  6293. switch (entry.cmdtype) {
  6294. case CMDNORMAL: {
  6295. int j = entry.u.index;
  6296. char *p;
  6297. if (j == -1) {
  6298. p = command;
  6299. } else {
  6300. do {
  6301. p = padvance(&path, command);
  6302. stunalloc(p);
  6303. } while (--j >= 0);
  6304. }
  6305. if (describe_command_verbose) {
  6306. out1fmt(" is%s %s",
  6307. (cmdp ? " a tracked alias for" : nullstr), p
  6308. );
  6309. } else {
  6310. out1str(p);
  6311. }
  6312. break;
  6313. }
  6314. case CMDFUNCTION:
  6315. if (describe_command_verbose) {
  6316. out1str(" is a shell function");
  6317. } else {
  6318. out1str(command);
  6319. }
  6320. break;
  6321. case CMDBUILTIN:
  6322. if (describe_command_verbose) {
  6323. out1fmt(" is a %sshell builtin",
  6324. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  6325. "special " : nullstr
  6326. );
  6327. } else {
  6328. out1str(command);
  6329. }
  6330. break;
  6331. default:
  6332. if (describe_command_verbose) {
  6333. out1str(": not found\n");
  6334. }
  6335. return 127;
  6336. }
  6337. out:
  6338. outstr("\n", stdout);
  6339. return 0;
  6340. }
  6341. static int
  6342. typecmd(int argc, char **argv)
  6343. {
  6344. int i = 1;
  6345. int err = 0;
  6346. int verbose = 1;
  6347. /* type -p ... ? (we don't bother checking for 'p') */
  6348. if (argv[1] && argv[1][0] == '-') {
  6349. i++;
  6350. verbose = 0;
  6351. }
  6352. while (i < argc) {
  6353. err |= describe_command(argv[i++], verbose);
  6354. }
  6355. return err;
  6356. }
  6357. #if ENABLE_ASH_CMDCMD
  6358. static int
  6359. commandcmd(int argc, char **argv)
  6360. {
  6361. int c;
  6362. enum {
  6363. VERIFY_BRIEF = 1,
  6364. VERIFY_VERBOSE = 2,
  6365. } verify = 0;
  6366. while ((c = nextopt("pvV")) != '\0')
  6367. if (c == 'V')
  6368. verify |= VERIFY_VERBOSE;
  6369. else if (c == 'v')
  6370. verify |= VERIFY_BRIEF;
  6371. #if DEBUG
  6372. else if (c != 'p')
  6373. abort();
  6374. #endif
  6375. if (verify)
  6376. return describe_command(*argptr, verify - VERIFY_BRIEF);
  6377. return 0;
  6378. }
  6379. #endif
  6380. /* ============ eval.c */
  6381. static int funcblocksize; /* size of structures in function */
  6382. static int funcstringsize; /* size of strings in node */
  6383. static void *funcblock; /* block to allocate function from */
  6384. static char *funcstring; /* block to allocate strings from */
  6385. /* flags in argument to evaltree */
  6386. #define EV_EXIT 01 /* exit after evaluating tree */
  6387. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  6388. #define EV_BACKCMD 04 /* command executing within back quotes */
  6389. static const short nodesize[26] = {
  6390. SHELL_ALIGN(sizeof(struct ncmd)),
  6391. SHELL_ALIGN(sizeof(struct npipe)),
  6392. SHELL_ALIGN(sizeof(struct nredir)),
  6393. SHELL_ALIGN(sizeof(struct nredir)),
  6394. SHELL_ALIGN(sizeof(struct nredir)),
  6395. SHELL_ALIGN(sizeof(struct nbinary)),
  6396. SHELL_ALIGN(sizeof(struct nbinary)),
  6397. SHELL_ALIGN(sizeof(struct nbinary)),
  6398. SHELL_ALIGN(sizeof(struct nif)),
  6399. SHELL_ALIGN(sizeof(struct nbinary)),
  6400. SHELL_ALIGN(sizeof(struct nbinary)),
  6401. SHELL_ALIGN(sizeof(struct nfor)),
  6402. SHELL_ALIGN(sizeof(struct ncase)),
  6403. SHELL_ALIGN(sizeof(struct nclist)),
  6404. SHELL_ALIGN(sizeof(struct narg)),
  6405. SHELL_ALIGN(sizeof(struct narg)),
  6406. SHELL_ALIGN(sizeof(struct nfile)),
  6407. SHELL_ALIGN(sizeof(struct nfile)),
  6408. SHELL_ALIGN(sizeof(struct nfile)),
  6409. SHELL_ALIGN(sizeof(struct nfile)),
  6410. SHELL_ALIGN(sizeof(struct nfile)),
  6411. SHELL_ALIGN(sizeof(struct ndup)),
  6412. SHELL_ALIGN(sizeof(struct ndup)),
  6413. SHELL_ALIGN(sizeof(struct nhere)),
  6414. SHELL_ALIGN(sizeof(struct nhere)),
  6415. SHELL_ALIGN(sizeof(struct nnot)),
  6416. };
  6417. static void calcsize(union node *n);
  6418. static void
  6419. sizenodelist(struct nodelist *lp)
  6420. {
  6421. while (lp) {
  6422. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  6423. calcsize(lp->n);
  6424. lp = lp->next;
  6425. }
  6426. }
  6427. static void
  6428. calcsize(union node *n)
  6429. {
  6430. if (n == NULL)
  6431. return;
  6432. funcblocksize += nodesize[n->type];
  6433. switch (n->type) {
  6434. case NCMD:
  6435. calcsize(n->ncmd.redirect);
  6436. calcsize(n->ncmd.args);
  6437. calcsize(n->ncmd.assign);
  6438. break;
  6439. case NPIPE:
  6440. sizenodelist(n->npipe.cmdlist);
  6441. break;
  6442. case NREDIR:
  6443. case NBACKGND:
  6444. case NSUBSHELL:
  6445. calcsize(n->nredir.redirect);
  6446. calcsize(n->nredir.n);
  6447. break;
  6448. case NAND:
  6449. case NOR:
  6450. case NSEMI:
  6451. case NWHILE:
  6452. case NUNTIL:
  6453. calcsize(n->nbinary.ch2);
  6454. calcsize(n->nbinary.ch1);
  6455. break;
  6456. case NIF:
  6457. calcsize(n->nif.elsepart);
  6458. calcsize(n->nif.ifpart);
  6459. calcsize(n->nif.test);
  6460. break;
  6461. case NFOR:
  6462. funcstringsize += strlen(n->nfor.var) + 1;
  6463. calcsize(n->nfor.body);
  6464. calcsize(n->nfor.args);
  6465. break;
  6466. case NCASE:
  6467. calcsize(n->ncase.cases);
  6468. calcsize(n->ncase.expr);
  6469. break;
  6470. case NCLIST:
  6471. calcsize(n->nclist.body);
  6472. calcsize(n->nclist.pattern);
  6473. calcsize(n->nclist.next);
  6474. break;
  6475. case NDEFUN:
  6476. case NARG:
  6477. sizenodelist(n->narg.backquote);
  6478. funcstringsize += strlen(n->narg.text) + 1;
  6479. calcsize(n->narg.next);
  6480. break;
  6481. case NTO:
  6482. case NCLOBBER:
  6483. case NFROM:
  6484. case NFROMTO:
  6485. case NAPPEND:
  6486. calcsize(n->nfile.fname);
  6487. calcsize(n->nfile.next);
  6488. break;
  6489. case NTOFD:
  6490. case NFROMFD:
  6491. calcsize(n->ndup.vname);
  6492. calcsize(n->ndup.next);
  6493. break;
  6494. case NHERE:
  6495. case NXHERE:
  6496. calcsize(n->nhere.doc);
  6497. calcsize(n->nhere.next);
  6498. break;
  6499. case NNOT:
  6500. calcsize(n->nnot.com);
  6501. break;
  6502. };
  6503. }
  6504. static char *
  6505. nodeckstrdup(char *s)
  6506. {
  6507. char *rtn = funcstring;
  6508. strcpy(funcstring, s);
  6509. funcstring += strlen(s) + 1;
  6510. return rtn;
  6511. }
  6512. static union node *copynode(union node *);
  6513. static struct nodelist *
  6514. copynodelist(struct nodelist *lp)
  6515. {
  6516. struct nodelist *start;
  6517. struct nodelist **lpp;
  6518. lpp = &start;
  6519. while (lp) {
  6520. *lpp = funcblock;
  6521. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  6522. (*lpp)->n = copynode(lp->n);
  6523. lp = lp->next;
  6524. lpp = &(*lpp)->next;
  6525. }
  6526. *lpp = NULL;
  6527. return start;
  6528. }
  6529. static union node *
  6530. copynode(union node *n)
  6531. {
  6532. union node *new;
  6533. if (n == NULL)
  6534. return NULL;
  6535. new = funcblock;
  6536. funcblock = (char *) funcblock + nodesize[n->type];
  6537. switch (n->type) {
  6538. case NCMD:
  6539. new->ncmd.redirect = copynode(n->ncmd.redirect);
  6540. new->ncmd.args = copynode(n->ncmd.args);
  6541. new->ncmd.assign = copynode(n->ncmd.assign);
  6542. break;
  6543. case NPIPE:
  6544. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  6545. new->npipe.backgnd = n->npipe.backgnd;
  6546. break;
  6547. case NREDIR:
  6548. case NBACKGND:
  6549. case NSUBSHELL:
  6550. new->nredir.redirect = copynode(n->nredir.redirect);
  6551. new->nredir.n = copynode(n->nredir.n);
  6552. break;
  6553. case NAND:
  6554. case NOR:
  6555. case NSEMI:
  6556. case NWHILE:
  6557. case NUNTIL:
  6558. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  6559. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  6560. break;
  6561. case NIF:
  6562. new->nif.elsepart = copynode(n->nif.elsepart);
  6563. new->nif.ifpart = copynode(n->nif.ifpart);
  6564. new->nif.test = copynode(n->nif.test);
  6565. break;
  6566. case NFOR:
  6567. new->nfor.var = nodeckstrdup(n->nfor.var);
  6568. new->nfor.body = copynode(n->nfor.body);
  6569. new->nfor.args = copynode(n->nfor.args);
  6570. break;
  6571. case NCASE:
  6572. new->ncase.cases = copynode(n->ncase.cases);
  6573. new->ncase.expr = copynode(n->ncase.expr);
  6574. break;
  6575. case NCLIST:
  6576. new->nclist.body = copynode(n->nclist.body);
  6577. new->nclist.pattern = copynode(n->nclist.pattern);
  6578. new->nclist.next = copynode(n->nclist.next);
  6579. break;
  6580. case NDEFUN:
  6581. case NARG:
  6582. new->narg.backquote = copynodelist(n->narg.backquote);
  6583. new->narg.text = nodeckstrdup(n->narg.text);
  6584. new->narg.next = copynode(n->narg.next);
  6585. break;
  6586. case NTO:
  6587. case NCLOBBER:
  6588. case NFROM:
  6589. case NFROMTO:
  6590. case NAPPEND:
  6591. new->nfile.fname = copynode(n->nfile.fname);
  6592. new->nfile.fd = n->nfile.fd;
  6593. new->nfile.next = copynode(n->nfile.next);
  6594. break;
  6595. case NTOFD:
  6596. case NFROMFD:
  6597. new->ndup.vname = copynode(n->ndup.vname);
  6598. new->ndup.dupfd = n->ndup.dupfd;
  6599. new->ndup.fd = n->ndup.fd;
  6600. new->ndup.next = copynode(n->ndup.next);
  6601. break;
  6602. case NHERE:
  6603. case NXHERE:
  6604. new->nhere.doc = copynode(n->nhere.doc);
  6605. new->nhere.fd = n->nhere.fd;
  6606. new->nhere.next = copynode(n->nhere.next);
  6607. break;
  6608. case NNOT:
  6609. new->nnot.com = copynode(n->nnot.com);
  6610. break;
  6611. };
  6612. new->type = n->type;
  6613. return new;
  6614. }
  6615. /*
  6616. * Make a copy of a parse tree.
  6617. */
  6618. static struct funcnode *
  6619. copyfunc(union node *n)
  6620. {
  6621. struct funcnode *f;
  6622. size_t blocksize;
  6623. funcblocksize = offsetof(struct funcnode, n);
  6624. funcstringsize = 0;
  6625. calcsize(n);
  6626. blocksize = funcblocksize;
  6627. f = ckmalloc(blocksize + funcstringsize);
  6628. funcblock = (char *) f + offsetof(struct funcnode, n);
  6629. funcstring = (char *) f + blocksize;
  6630. copynode(n);
  6631. f->count = 0;
  6632. return f;
  6633. }
  6634. /*
  6635. * Define a shell function.
  6636. */
  6637. static void
  6638. defun(char *name, union node *func)
  6639. {
  6640. struct cmdentry entry;
  6641. INT_OFF;
  6642. entry.cmdtype = CMDFUNCTION;
  6643. entry.u.func = copyfunc(func);
  6644. addcmdentry(name, &entry);
  6645. INT_ON;
  6646. }
  6647. static int evalskip; /* set if we are skipping commands */
  6648. /* reasons for skipping commands (see comment on breakcmd routine) */
  6649. #define SKIPBREAK (1 << 0)
  6650. #define SKIPCONT (1 << 1)
  6651. #define SKIPFUNC (1 << 2)
  6652. #define SKIPFILE (1 << 3)
  6653. #define SKIPEVAL (1 << 4)
  6654. static int skipcount; /* number of levels to skip */
  6655. static int funcnest; /* depth of function calls */
  6656. /* forward decl way out to parsing code - dotrap needs it */
  6657. static int evalstring(char *s, int mask);
  6658. /*
  6659. * Called to execute a trap. Perhaps we should avoid entering new trap
  6660. * handlers while we are executing a trap handler.
  6661. */
  6662. static int
  6663. dotrap(void)
  6664. {
  6665. char *p;
  6666. char *q;
  6667. int i;
  6668. int savestatus;
  6669. int skip = 0;
  6670. savestatus = exitstatus;
  6671. pendingsig = 0;
  6672. xbarrier();
  6673. for (i = 0, q = gotsig; i < NSIG - 1; i++, q++) {
  6674. if (!*q)
  6675. continue;
  6676. *q = '\0';
  6677. p = trap[i + 1];
  6678. if (!p)
  6679. continue;
  6680. skip = evalstring(p, SKIPEVAL);
  6681. exitstatus = savestatus;
  6682. if (skip)
  6683. break;
  6684. }
  6685. return skip;
  6686. }
  6687. /* forward declarations - evaluation is fairly recursive business... */
  6688. static void evalloop(union node *, int);
  6689. static void evalfor(union node *, int);
  6690. static void evalcase(union node *, int);
  6691. static void evalsubshell(union node *, int);
  6692. static void expredir(union node *);
  6693. static void evalpipe(union node *, int);
  6694. static void evalcommand(union node *, int);
  6695. static int evalbltin(const struct builtincmd *, int, char **);
  6696. static void prehash(union node *);
  6697. /*
  6698. * Evaluate a parse tree. The value is left in the global variable
  6699. * exitstatus.
  6700. */
  6701. static void
  6702. evaltree(union node *n, int flags)
  6703. {
  6704. int checkexit = 0;
  6705. void (*evalfn)(union node *, int);
  6706. unsigned isor;
  6707. int status;
  6708. if (n == NULL) {
  6709. TRACE(("evaltree(NULL) called\n"));
  6710. goto out;
  6711. }
  6712. TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
  6713. getpid(), n, n->type, flags));
  6714. switch (n->type) {
  6715. default:
  6716. #if DEBUG
  6717. out1fmt("Node type = %d\n", n->type);
  6718. fflush(stdout);
  6719. break;
  6720. #endif
  6721. case NNOT:
  6722. evaltree(n->nnot.com, EV_TESTED);
  6723. status = !exitstatus;
  6724. goto setstatus;
  6725. case NREDIR:
  6726. expredir(n->nredir.redirect);
  6727. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  6728. if (!status) {
  6729. evaltree(n->nredir.n, flags & EV_TESTED);
  6730. status = exitstatus;
  6731. }
  6732. popredir(0);
  6733. goto setstatus;
  6734. case NCMD:
  6735. evalfn = evalcommand;
  6736. checkexit:
  6737. if (eflag && !(flags & EV_TESTED))
  6738. checkexit = ~0;
  6739. goto calleval;
  6740. case NFOR:
  6741. evalfn = evalfor;
  6742. goto calleval;
  6743. case NWHILE:
  6744. case NUNTIL:
  6745. evalfn = evalloop;
  6746. goto calleval;
  6747. case NSUBSHELL:
  6748. case NBACKGND:
  6749. evalfn = evalsubshell;
  6750. goto calleval;
  6751. case NPIPE:
  6752. evalfn = evalpipe;
  6753. goto checkexit;
  6754. case NCASE:
  6755. evalfn = evalcase;
  6756. goto calleval;
  6757. case NAND:
  6758. case NOR:
  6759. case NSEMI:
  6760. #if NAND + 1 != NOR
  6761. #error NAND + 1 != NOR
  6762. #endif
  6763. #if NOR + 1 != NSEMI
  6764. #error NOR + 1 != NSEMI
  6765. #endif
  6766. isor = n->type - NAND;
  6767. evaltree(
  6768. n->nbinary.ch1,
  6769. (flags | ((isor >> 1) - 1)) & EV_TESTED
  6770. );
  6771. if (!exitstatus == isor)
  6772. break;
  6773. if (!evalskip) {
  6774. n = n->nbinary.ch2;
  6775. evaln:
  6776. evalfn = evaltree;
  6777. calleval:
  6778. evalfn(n, flags);
  6779. break;
  6780. }
  6781. break;
  6782. case NIF:
  6783. evaltree(n->nif.test, EV_TESTED);
  6784. if (evalskip)
  6785. break;
  6786. if (exitstatus == 0) {
  6787. n = n->nif.ifpart;
  6788. goto evaln;
  6789. } else if (n->nif.elsepart) {
  6790. n = n->nif.elsepart;
  6791. goto evaln;
  6792. }
  6793. goto success;
  6794. case NDEFUN:
  6795. defun(n->narg.text, n->narg.next);
  6796. success:
  6797. status = 0;
  6798. setstatus:
  6799. exitstatus = status;
  6800. break;
  6801. }
  6802. out:
  6803. if ((checkexit & exitstatus))
  6804. evalskip |= SKIPEVAL;
  6805. else if (pendingsig && dotrap())
  6806. goto exexit;
  6807. if (flags & EV_EXIT) {
  6808. exexit:
  6809. raise_exception(EXEXIT);
  6810. }
  6811. }
  6812. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  6813. static
  6814. #endif
  6815. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  6816. static int loopnest; /* current loop nesting level */
  6817. static void
  6818. evalloop(union node *n, int flags)
  6819. {
  6820. int status;
  6821. loopnest++;
  6822. status = 0;
  6823. flags &= EV_TESTED;
  6824. for (;;) {
  6825. int i;
  6826. evaltree(n->nbinary.ch1, EV_TESTED);
  6827. if (evalskip) {
  6828. skipping:
  6829. if (evalskip == SKIPCONT && --skipcount <= 0) {
  6830. evalskip = 0;
  6831. continue;
  6832. }
  6833. if (evalskip == SKIPBREAK && --skipcount <= 0)
  6834. evalskip = 0;
  6835. break;
  6836. }
  6837. i = exitstatus;
  6838. if (n->type != NWHILE)
  6839. i = !i;
  6840. if (i != 0)
  6841. break;
  6842. evaltree(n->nbinary.ch2, flags);
  6843. status = exitstatus;
  6844. if (evalskip)
  6845. goto skipping;
  6846. }
  6847. loopnest--;
  6848. exitstatus = status;
  6849. }
  6850. static void
  6851. evalfor(union node *n, int flags)
  6852. {
  6853. struct arglist arglist;
  6854. union node *argp;
  6855. struct strlist *sp;
  6856. struct stackmark smark;
  6857. setstackmark(&smark);
  6858. arglist.lastp = &arglist.list;
  6859. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  6860. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  6861. /* XXX */
  6862. if (evalskip)
  6863. goto out;
  6864. }
  6865. *arglist.lastp = NULL;
  6866. exitstatus = 0;
  6867. loopnest++;
  6868. flags &= EV_TESTED;
  6869. for (sp = arglist.list; sp; sp = sp->next) {
  6870. setvar(n->nfor.var, sp->text, 0);
  6871. evaltree(n->nfor.body, flags);
  6872. if (evalskip) {
  6873. if (evalskip == SKIPCONT && --skipcount <= 0) {
  6874. evalskip = 0;
  6875. continue;
  6876. }
  6877. if (evalskip == SKIPBREAK && --skipcount <= 0)
  6878. evalskip = 0;
  6879. break;
  6880. }
  6881. }
  6882. loopnest--;
  6883. out:
  6884. popstackmark(&smark);
  6885. }
  6886. static void
  6887. evalcase(union node *n, int flags)
  6888. {
  6889. union node *cp;
  6890. union node *patp;
  6891. struct arglist arglist;
  6892. struct stackmark smark;
  6893. setstackmark(&smark);
  6894. arglist.lastp = &arglist.list;
  6895. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  6896. exitstatus = 0;
  6897. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  6898. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  6899. if (casematch(patp, arglist.list->text)) {
  6900. if (evalskip == 0) {
  6901. evaltree(cp->nclist.body, flags);
  6902. }
  6903. goto out;
  6904. }
  6905. }
  6906. }
  6907. out:
  6908. popstackmark(&smark);
  6909. }
  6910. /*
  6911. * Kick off a subshell to evaluate a tree.
  6912. */
  6913. static void
  6914. evalsubshell(union node *n, int flags)
  6915. {
  6916. struct job *jp;
  6917. int backgnd = (n->type == NBACKGND);
  6918. int status;
  6919. expredir(n->nredir.redirect);
  6920. if (!backgnd && flags & EV_EXIT && !trap[0])
  6921. goto nofork;
  6922. INT_OFF;
  6923. jp = makejob(n, 1);
  6924. if (forkshell(jp, n, backgnd) == 0) {
  6925. INT_ON;
  6926. flags |= EV_EXIT;
  6927. if (backgnd)
  6928. flags &=~ EV_TESTED;
  6929. nofork:
  6930. redirect(n->nredir.redirect, 0);
  6931. evaltreenr(n->nredir.n, flags);
  6932. /* never returns */
  6933. }
  6934. status = 0;
  6935. if (! backgnd)
  6936. status = waitforjob(jp);
  6937. exitstatus = status;
  6938. INT_ON;
  6939. }
  6940. /*
  6941. * Compute the names of the files in a redirection list.
  6942. */
  6943. static void fixredir(union node *, const char *, int);
  6944. static void
  6945. expredir(union node *n)
  6946. {
  6947. union node *redir;
  6948. for (redir = n; redir; redir = redir->nfile.next) {
  6949. struct arglist fn;
  6950. memset(&fn, 0, sizeof(fn));
  6951. fn.lastp = &fn.list;
  6952. switch (redir->type) {
  6953. case NFROMTO:
  6954. case NFROM:
  6955. case NTO:
  6956. case NCLOBBER:
  6957. case NAPPEND:
  6958. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  6959. redir->nfile.expfname = fn.list->text;
  6960. break;
  6961. case NFROMFD:
  6962. case NTOFD:
  6963. if (redir->ndup.vname) {
  6964. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  6965. if (fn.list == NULL)
  6966. ash_msg_and_raise_error("redir error");
  6967. fixredir(redir, fn.list->text, 1);
  6968. }
  6969. break;
  6970. }
  6971. }
  6972. }
  6973. /*
  6974. * Evaluate a pipeline. All the processes in the pipeline are children
  6975. * of the process creating the pipeline. (This differs from some versions
  6976. * of the shell, which make the last process in a pipeline the parent
  6977. * of all the rest.)
  6978. */
  6979. static void
  6980. evalpipe(union node *n, int flags)
  6981. {
  6982. struct job *jp;
  6983. struct nodelist *lp;
  6984. int pipelen;
  6985. int prevfd;
  6986. int pip[2];
  6987. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  6988. pipelen = 0;
  6989. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  6990. pipelen++;
  6991. flags |= EV_EXIT;
  6992. INT_OFF;
  6993. jp = makejob(n, pipelen);
  6994. prevfd = -1;
  6995. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  6996. prehash(lp->n);
  6997. pip[1] = -1;
  6998. if (lp->next) {
  6999. if (pipe(pip) < 0) {
  7000. close(prevfd);
  7001. ash_msg_and_raise_error("pipe call failed");
  7002. }
  7003. }
  7004. if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
  7005. INT_ON;
  7006. if (pip[1] >= 0) {
  7007. close(pip[0]);
  7008. }
  7009. if (prevfd > 0) {
  7010. dup2(prevfd, 0);
  7011. close(prevfd);
  7012. }
  7013. if (pip[1] > 1) {
  7014. dup2(pip[1], 1);
  7015. close(pip[1]);
  7016. }
  7017. evaltreenr(lp->n, flags);
  7018. /* never returns */
  7019. }
  7020. if (prevfd >= 0)
  7021. close(prevfd);
  7022. prevfd = pip[0];
  7023. close(pip[1]);
  7024. }
  7025. if (n->npipe.backgnd == 0) {
  7026. exitstatus = waitforjob(jp);
  7027. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7028. }
  7029. INT_ON;
  7030. }
  7031. /*
  7032. * Controls whether the shell is interactive or not.
  7033. */
  7034. static void
  7035. setinteractive(int on)
  7036. {
  7037. static int is_interactive;
  7038. if (++on == is_interactive)
  7039. return;
  7040. is_interactive = on;
  7041. setsignal(SIGINT);
  7042. setsignal(SIGQUIT);
  7043. setsignal(SIGTERM);
  7044. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7045. if (is_interactive > 1) {
  7046. /* Looks like they want an interactive shell */
  7047. static smallint did_banner;
  7048. if (!did_banner) {
  7049. out1fmt(
  7050. "\n\n"
  7051. "%s built-in shell (ash)\n"
  7052. "Enter 'help' for a list of built-in commands."
  7053. "\n\n",
  7054. bb_banner);
  7055. did_banner = 1;
  7056. }
  7057. }
  7058. #endif
  7059. }
  7060. #if ENABLE_FEATURE_EDITING_VI
  7061. #define setvimode(on) do { \
  7062. if (on) line_input_state->flags |= VI_MODE; \
  7063. else line_input_state->flags &= ~VI_MODE; \
  7064. } while (0)
  7065. #else
  7066. #define setvimode(on) viflag = 0 /* forcibly keep the option off */
  7067. #endif
  7068. static void
  7069. optschanged(void)
  7070. {
  7071. #if DEBUG
  7072. opentrace();
  7073. #endif
  7074. setinteractive(iflag);
  7075. setjobctl(mflag);
  7076. setvimode(viflag);
  7077. }
  7078. static struct localvar *localvars;
  7079. /*
  7080. * Called after a function returns.
  7081. * Interrupts must be off.
  7082. */
  7083. static void
  7084. poplocalvars(void)
  7085. {
  7086. struct localvar *lvp;
  7087. struct var *vp;
  7088. while ((lvp = localvars) != NULL) {
  7089. localvars = lvp->next;
  7090. vp = lvp->vp;
  7091. TRACE(("poplocalvar %s", vp ? vp->text : "-"));
  7092. if (vp == NULL) { /* $- saved */
  7093. memcpy(optlist, lvp->text, sizeof(optlist));
  7094. free((char*)lvp->text);
  7095. optschanged();
  7096. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7097. unsetvar(vp->text);
  7098. } else {
  7099. if (vp->func)
  7100. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7101. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7102. free((char*)vp->text);
  7103. vp->flags = lvp->flags;
  7104. vp->text = lvp->text;
  7105. }
  7106. free(lvp);
  7107. }
  7108. }
  7109. static int
  7110. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7111. {
  7112. volatile struct shparam saveparam;
  7113. struct localvar *volatile savelocalvars;
  7114. struct jmploc *volatile savehandler;
  7115. struct jmploc jmploc;
  7116. int e;
  7117. saveparam = shellparam;
  7118. savelocalvars = localvars;
  7119. e = setjmp(jmploc.loc);
  7120. if (e) {
  7121. goto funcdone;
  7122. }
  7123. INT_OFF;
  7124. savehandler = exception_handler;
  7125. exception_handler = &jmploc;
  7126. localvars = NULL;
  7127. shellparam.malloc = 0;
  7128. func->count++;
  7129. funcnest++;
  7130. INT_ON;
  7131. shellparam.nparam = argc - 1;
  7132. shellparam.p = argv + 1;
  7133. #if ENABLE_ASH_GETOPTS
  7134. shellparam.optind = 1;
  7135. shellparam.optoff = -1;
  7136. #endif
  7137. evaltree(&func->n, flags & EV_TESTED);
  7138. funcdone:
  7139. INT_OFF;
  7140. funcnest--;
  7141. freefunc(func);
  7142. poplocalvars();
  7143. localvars = savelocalvars;
  7144. freeparam(&shellparam);
  7145. shellparam = saveparam;
  7146. exception_handler = savehandler;
  7147. INT_ON;
  7148. evalskip &= ~SKIPFUNC;
  7149. return e;
  7150. }
  7151. #if ENABLE_ASH_CMDCMD
  7152. static char **
  7153. parse_command_args(char **argv, const char **path)
  7154. {
  7155. char *cp, c;
  7156. for (;;) {
  7157. cp = *++argv;
  7158. if (!cp)
  7159. return 0;
  7160. if (*cp++ != '-')
  7161. break;
  7162. c = *cp++;
  7163. if (!c)
  7164. break;
  7165. if (c == '-' && !*cp) {
  7166. argv++;
  7167. break;
  7168. }
  7169. do {
  7170. switch (c) {
  7171. case 'p':
  7172. *path = bb_default_path;
  7173. break;
  7174. default:
  7175. /* run 'typecmd' for other options */
  7176. return 0;
  7177. }
  7178. c = *cp++;
  7179. } while (c);
  7180. }
  7181. return argv;
  7182. }
  7183. #endif
  7184. /*
  7185. * Make a variable a local variable. When a variable is made local, it's
  7186. * value and flags are saved in a localvar structure. The saved values
  7187. * will be restored when the shell function returns. We handle the name
  7188. * "-" as a special case.
  7189. */
  7190. static void
  7191. mklocal(char *name)
  7192. {
  7193. struct localvar *lvp;
  7194. struct var **vpp;
  7195. struct var *vp;
  7196. INT_OFF;
  7197. lvp = ckmalloc(sizeof(struct localvar));
  7198. if (LONE_DASH(name)) {
  7199. char *p;
  7200. p = ckmalloc(sizeof(optlist));
  7201. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7202. vp = NULL;
  7203. } else {
  7204. char *eq;
  7205. vpp = hashvar(name);
  7206. vp = *findvar(vpp, name);
  7207. eq = strchr(name, '=');
  7208. if (vp == NULL) {
  7209. if (eq)
  7210. setvareq(name, VSTRFIXED);
  7211. else
  7212. setvar(name, NULL, VSTRFIXED);
  7213. vp = *vpp; /* the new variable */
  7214. lvp->flags = VUNSET;
  7215. } else {
  7216. lvp->text = vp->text;
  7217. lvp->flags = vp->flags;
  7218. vp->flags |= VSTRFIXED|VTEXTFIXED;
  7219. if (eq)
  7220. setvareq(name, 0);
  7221. }
  7222. }
  7223. lvp->vp = vp;
  7224. lvp->next = localvars;
  7225. localvars = lvp;
  7226. INT_ON;
  7227. }
  7228. /*
  7229. * The "local" command.
  7230. */
  7231. static int
  7232. localcmd(int argc, char **argv)
  7233. {
  7234. char *name;
  7235. argv = argptr;
  7236. while ((name = *argv++) != NULL) {
  7237. mklocal(name);
  7238. }
  7239. return 0;
  7240. }
  7241. static int
  7242. falsecmd(int argc, char **argv)
  7243. {
  7244. return 1;
  7245. }
  7246. static int
  7247. truecmd(int argc, char **argv)
  7248. {
  7249. return 0;
  7250. }
  7251. static int
  7252. execcmd(int argc, char **argv)
  7253. {
  7254. if (argc > 1) {
  7255. iflag = 0; /* exit on error */
  7256. mflag = 0;
  7257. optschanged();
  7258. shellexec(argv + 1, pathval(), 0);
  7259. }
  7260. return 0;
  7261. }
  7262. /*
  7263. * The return command.
  7264. */
  7265. static int
  7266. returncmd(int argc, char **argv)
  7267. {
  7268. /*
  7269. * If called outside a function, do what ksh does;
  7270. * skip the rest of the file.
  7271. */
  7272. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  7273. return argv[1] ? number(argv[1]) : exitstatus;
  7274. }
  7275. /* Forward declarations for builtintab[] */
  7276. static int breakcmd(int, char **);
  7277. static int dotcmd(int, char **);
  7278. static int evalcmd(int, char **);
  7279. #if ENABLE_ASH_BUILTIN_ECHO
  7280. static int echocmd(int, char **);
  7281. #endif
  7282. #if ENABLE_ASH_BUILTIN_TEST
  7283. static int testcmd(int, char **);
  7284. #endif
  7285. static int exitcmd(int, char **);
  7286. static int exportcmd(int, char **);
  7287. #if ENABLE_ASH_GETOPTS
  7288. static int getoptscmd(int, char **);
  7289. #endif
  7290. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7291. static int helpcmd(int argc, char **argv);
  7292. #endif
  7293. #if ENABLE_ASH_MATH_SUPPORT
  7294. static int letcmd(int, char **);
  7295. #endif
  7296. static int readcmd(int, char **);
  7297. static int setcmd(int, char **);
  7298. static int shiftcmd(int, char **);
  7299. static int timescmd(int, char **);
  7300. static int trapcmd(int, char **);
  7301. static int umaskcmd(int, char **);
  7302. static int unsetcmd(int, char **);
  7303. static int ulimitcmd(int, char **);
  7304. #define BUILTIN_NOSPEC "0"
  7305. #define BUILTIN_SPECIAL "1"
  7306. #define BUILTIN_REGULAR "2"
  7307. #define BUILTIN_SPEC_REG "3"
  7308. #define BUILTIN_ASSIGN "4"
  7309. #define BUILTIN_SPEC_ASSG "5"
  7310. #define BUILTIN_REG_ASSG "6"
  7311. #define BUILTIN_SPEC_REG_ASSG "7"
  7312. /* make sure to keep these in proper order since it is searched via bsearch() */
  7313. static const struct builtincmd builtintab[] = {
  7314. { BUILTIN_SPEC_REG ".", dotcmd },
  7315. { BUILTIN_SPEC_REG ":", truecmd },
  7316. #if ENABLE_ASH_BUILTIN_TEST
  7317. { BUILTIN_REGULAR "[", testcmd },
  7318. { BUILTIN_REGULAR "[[", testcmd },
  7319. #endif
  7320. #if ENABLE_ASH_ALIAS
  7321. { BUILTIN_REG_ASSG "alias", aliascmd },
  7322. #endif
  7323. #if JOBS
  7324. { BUILTIN_REGULAR "bg", fg_bgcmd },
  7325. #endif
  7326. { BUILTIN_SPEC_REG "break", breakcmd },
  7327. { BUILTIN_REGULAR "cd", cdcmd },
  7328. { BUILTIN_NOSPEC "chdir", cdcmd },
  7329. #if ENABLE_ASH_CMDCMD
  7330. { BUILTIN_REGULAR "command", commandcmd },
  7331. #endif
  7332. { BUILTIN_SPEC_REG "continue", breakcmd },
  7333. #if ENABLE_ASH_BUILTIN_ECHO
  7334. { BUILTIN_REGULAR "echo", echocmd },
  7335. #endif
  7336. { BUILTIN_SPEC_REG "eval", evalcmd },
  7337. { BUILTIN_SPEC_REG "exec", execcmd },
  7338. { BUILTIN_SPEC_REG "exit", exitcmd },
  7339. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  7340. { BUILTIN_REGULAR "false", falsecmd },
  7341. #if JOBS
  7342. { BUILTIN_REGULAR "fg", fg_bgcmd },
  7343. #endif
  7344. #if ENABLE_ASH_GETOPTS
  7345. { BUILTIN_REGULAR "getopts", getoptscmd },
  7346. #endif
  7347. { BUILTIN_NOSPEC "hash", hashcmd },
  7348. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7349. { BUILTIN_NOSPEC "help", helpcmd },
  7350. #endif
  7351. #if JOBS
  7352. { BUILTIN_REGULAR "jobs", jobscmd },
  7353. { BUILTIN_REGULAR "kill", killcmd },
  7354. #endif
  7355. #if ENABLE_ASH_MATH_SUPPORT
  7356. { BUILTIN_NOSPEC "let", letcmd },
  7357. #endif
  7358. { BUILTIN_ASSIGN "local", localcmd },
  7359. { BUILTIN_NOSPEC "pwd", pwdcmd },
  7360. { BUILTIN_REGULAR "read", readcmd },
  7361. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  7362. { BUILTIN_SPEC_REG "return", returncmd },
  7363. { BUILTIN_SPEC_REG "set", setcmd },
  7364. { BUILTIN_SPEC_REG "shift", shiftcmd },
  7365. { BUILTIN_SPEC_REG "source", dotcmd },
  7366. #if ENABLE_ASH_BUILTIN_TEST
  7367. { BUILTIN_REGULAR "test", testcmd },
  7368. #endif
  7369. { BUILTIN_SPEC_REG "times", timescmd },
  7370. { BUILTIN_SPEC_REG "trap", trapcmd },
  7371. { BUILTIN_REGULAR "true", truecmd },
  7372. { BUILTIN_NOSPEC "type", typecmd },
  7373. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  7374. { BUILTIN_REGULAR "umask", umaskcmd },
  7375. #if ENABLE_ASH_ALIAS
  7376. { BUILTIN_REGULAR "unalias", unaliascmd },
  7377. #endif
  7378. { BUILTIN_SPEC_REG "unset", unsetcmd },
  7379. { BUILTIN_REGULAR "wait", waitcmd },
  7380. };
  7381. #define COMMANDCMD (builtintab + 5 + \
  7382. 2 * ENABLE_ASH_BUILTIN_TEST + \
  7383. ENABLE_ASH_ALIAS + \
  7384. ENABLE_ASH_JOB_CONTROL)
  7385. #define EXECCMD (builtintab + 7 + \
  7386. 2 * ENABLE_ASH_BUILTIN_TEST + \
  7387. ENABLE_ASH_ALIAS + \
  7388. ENABLE_ASH_JOB_CONTROL + \
  7389. ENABLE_ASH_CMDCMD + \
  7390. ENABLE_ASH_BUILTIN_ECHO)
  7391. /*
  7392. * Search the table of builtin commands.
  7393. */
  7394. static struct builtincmd *
  7395. find_builtin(const char *name)
  7396. {
  7397. struct builtincmd *bp;
  7398. bp = bsearch(
  7399. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  7400. pstrcmp
  7401. );
  7402. return bp;
  7403. }
  7404. /*
  7405. * Execute a simple command.
  7406. */
  7407. static int back_exitstatus; /* exit status of backquoted command */
  7408. static int
  7409. isassignment(const char *p)
  7410. {
  7411. const char *q = endofname(p);
  7412. if (p == q)
  7413. return 0;
  7414. return *q == '=';
  7415. }
  7416. static int
  7417. bltincmd(int argc, char **argv)
  7418. {
  7419. /* Preserve exitstatus of a previous possible redirection
  7420. * as POSIX mandates */
  7421. return back_exitstatus;
  7422. }
  7423. static void
  7424. evalcommand(union node *cmd, int flags)
  7425. {
  7426. static const struct builtincmd bltin = {
  7427. "\0\0", bltincmd
  7428. };
  7429. struct stackmark smark;
  7430. union node *argp;
  7431. struct arglist arglist;
  7432. struct arglist varlist;
  7433. char **argv;
  7434. int argc;
  7435. const struct strlist *sp;
  7436. struct cmdentry cmdentry;
  7437. struct job *jp;
  7438. char *lastarg;
  7439. const char *path;
  7440. int spclbltin;
  7441. int cmd_is_exec;
  7442. int status;
  7443. char **nargv;
  7444. struct builtincmd *bcmd;
  7445. int pseudovarflag = 0;
  7446. /* First expand the arguments. */
  7447. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  7448. setstackmark(&smark);
  7449. back_exitstatus = 0;
  7450. cmdentry.cmdtype = CMDBUILTIN;
  7451. cmdentry.u.cmd = &bltin;
  7452. varlist.lastp = &varlist.list;
  7453. *varlist.lastp = NULL;
  7454. arglist.lastp = &arglist.list;
  7455. *arglist.lastp = NULL;
  7456. argc = 0;
  7457. if (cmd->ncmd.args) {
  7458. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  7459. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  7460. }
  7461. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  7462. struct strlist **spp;
  7463. spp = arglist.lastp;
  7464. if (pseudovarflag && isassignment(argp->narg.text))
  7465. expandarg(argp, &arglist, EXP_VARTILDE);
  7466. else
  7467. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  7468. for (sp = *spp; sp; sp = sp->next)
  7469. argc++;
  7470. }
  7471. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  7472. for (sp = arglist.list; sp; sp = sp->next) {
  7473. TRACE(("evalcommand arg: %s\n", sp->text));
  7474. *nargv++ = sp->text;
  7475. }
  7476. *nargv = NULL;
  7477. lastarg = NULL;
  7478. if (iflag && funcnest == 0 && argc > 0)
  7479. lastarg = nargv[-1];
  7480. preverrout_fd = 2;
  7481. expredir(cmd->ncmd.redirect);
  7482. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  7483. path = vpath.text;
  7484. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  7485. struct strlist **spp;
  7486. char *p;
  7487. spp = varlist.lastp;
  7488. expandarg(argp, &varlist, EXP_VARTILDE);
  7489. /*
  7490. * Modify the command lookup path, if a PATH= assignment
  7491. * is present
  7492. */
  7493. p = (*spp)->text;
  7494. if (varequal(p, path))
  7495. path = p;
  7496. }
  7497. /* Print the command if xflag is set. */
  7498. if (xflag) {
  7499. int n;
  7500. const char *p = " %s";
  7501. p++;
  7502. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  7503. sp = varlist.list;
  7504. for (n = 0; n < 2; n++) {
  7505. while (sp) {
  7506. fdprintf(preverrout_fd, p, sp->text);
  7507. sp = sp->next;
  7508. if (*p == '%') {
  7509. p--;
  7510. }
  7511. }
  7512. sp = arglist.list;
  7513. }
  7514. full_write(preverrout_fd, "\n", 1);
  7515. }
  7516. cmd_is_exec = 0;
  7517. spclbltin = -1;
  7518. /* Now locate the command. */
  7519. if (argc) {
  7520. const char *oldpath;
  7521. int cmd_flag = DO_ERR;
  7522. path += 5;
  7523. oldpath = path;
  7524. for (;;) {
  7525. find_command(argv[0], &cmdentry, cmd_flag, path);
  7526. if (cmdentry.cmdtype == CMDUNKNOWN) {
  7527. status = 127;
  7528. flush_stderr();
  7529. goto bail;
  7530. }
  7531. /* implement bltin and command here */
  7532. if (cmdentry.cmdtype != CMDBUILTIN)
  7533. break;
  7534. if (spclbltin < 0)
  7535. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  7536. if (cmdentry.u.cmd == EXECCMD)
  7537. cmd_is_exec++;
  7538. #if ENABLE_ASH_CMDCMD
  7539. if (cmdentry.u.cmd == COMMANDCMD) {
  7540. path = oldpath;
  7541. nargv = parse_command_args(argv, &path);
  7542. if (!nargv)
  7543. break;
  7544. argc -= nargv - argv;
  7545. argv = nargv;
  7546. cmd_flag |= DO_NOFUNC;
  7547. } else
  7548. #endif
  7549. break;
  7550. }
  7551. }
  7552. if (status) {
  7553. /* We have a redirection error. */
  7554. if (spclbltin > 0)
  7555. raise_exception(EXERROR);
  7556. bail:
  7557. exitstatus = status;
  7558. goto out;
  7559. }
  7560. /* Execute the command. */
  7561. switch (cmdentry.cmdtype) {
  7562. default:
  7563. /* Fork off a child process if necessary. */
  7564. if (!(flags & EV_EXIT) || trap[0]) {
  7565. INT_OFF;
  7566. jp = makejob(cmd, 1);
  7567. if (forkshell(jp, cmd, FORK_FG) != 0) {
  7568. exitstatus = waitforjob(jp);
  7569. INT_ON;
  7570. break;
  7571. }
  7572. FORCE_INT_ON;
  7573. }
  7574. listsetvar(varlist.list, VEXPORT|VSTACK);
  7575. shellexec(argv, path, cmdentry.u.index);
  7576. /* NOTREACHED */
  7577. case CMDBUILTIN:
  7578. cmdenviron = varlist.list;
  7579. if (cmdenviron) {
  7580. struct strlist *list = cmdenviron;
  7581. int i = VNOSET;
  7582. if (spclbltin > 0 || argc == 0) {
  7583. i = 0;
  7584. if (cmd_is_exec && argc > 1)
  7585. i = VEXPORT;
  7586. }
  7587. listsetvar(list, i);
  7588. }
  7589. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  7590. int exit_status;
  7591. int i, j;
  7592. i = exception;
  7593. if (i == EXEXIT)
  7594. goto raise;
  7595. exit_status = 2;
  7596. j = 0;
  7597. if (i == EXINT)
  7598. j = SIGINT;
  7599. if (i == EXSIG)
  7600. j = pendingsig;
  7601. if (j)
  7602. exit_status = j + 128;
  7603. exitstatus = exit_status;
  7604. if (i == EXINT || spclbltin > 0) {
  7605. raise:
  7606. longjmp(exception_handler->loc, 1);
  7607. }
  7608. FORCE_INT_ON;
  7609. }
  7610. break;
  7611. case CMDFUNCTION:
  7612. listsetvar(varlist.list, 0);
  7613. if (evalfun(cmdentry.u.func, argc, argv, flags))
  7614. goto raise;
  7615. break;
  7616. }
  7617. out:
  7618. popredir(cmd_is_exec);
  7619. if (lastarg)
  7620. /* dsl: I think this is intended to be used to support
  7621. * '_' in 'vi' command mode during line editing...
  7622. * However I implemented that within libedit itself.
  7623. */
  7624. setvar("_", lastarg, 0);
  7625. popstackmark(&smark);
  7626. }
  7627. static int
  7628. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  7629. {
  7630. char *volatile savecmdname;
  7631. struct jmploc *volatile savehandler;
  7632. struct jmploc jmploc;
  7633. int i;
  7634. savecmdname = commandname;
  7635. i = setjmp(jmploc.loc);
  7636. if (i)
  7637. goto cmddone;
  7638. savehandler = exception_handler;
  7639. exception_handler = &jmploc;
  7640. commandname = argv[0];
  7641. argptr = argv + 1;
  7642. optptr = NULL; /* initialize nextopt */
  7643. exitstatus = (*cmd->builtin)(argc, argv);
  7644. flush_stdout_stderr();
  7645. cmddone:
  7646. exitstatus |= ferror(stdout);
  7647. clearerr(stdout);
  7648. commandname = savecmdname;
  7649. exsig = 0;
  7650. exception_handler = savehandler;
  7651. return i;
  7652. }
  7653. static int
  7654. goodname(const char *p)
  7655. {
  7656. return !*endofname(p);
  7657. }
  7658. /*
  7659. * Search for a command. This is called before we fork so that the
  7660. * location of the command will be available in the parent as well as
  7661. * the child. The check for "goodname" is an overly conservative
  7662. * check that the name will not be subject to expansion.
  7663. */
  7664. static void
  7665. prehash(union node *n)
  7666. {
  7667. struct cmdentry entry;
  7668. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  7669. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  7670. }
  7671. /* ============ Builtin commands
  7672. *
  7673. * Builtin commands whose functions are closely tied to evaluation
  7674. * are implemented here.
  7675. */
  7676. /*
  7677. * Handle break and continue commands. Break, continue, and return are
  7678. * all handled by setting the evalskip flag. The evaluation routines
  7679. * above all check this flag, and if it is set they start skipping
  7680. * commands rather than executing them. The variable skipcount is
  7681. * the number of loops to break/continue, or the number of function
  7682. * levels to return. (The latter is always 1.) It should probably
  7683. * be an error to break out of more loops than exist, but it isn't
  7684. * in the standard shell so we don't make it one here.
  7685. */
  7686. static int
  7687. breakcmd(int argc, char **argv)
  7688. {
  7689. int n = argc > 1 ? number(argv[1]) : 1;
  7690. if (n <= 0)
  7691. ash_msg_and_raise_error(illnum, argv[1]);
  7692. if (n > loopnest)
  7693. n = loopnest;
  7694. if (n > 0) {
  7695. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  7696. skipcount = n;
  7697. }
  7698. return 0;
  7699. }
  7700. /* ============ input.c
  7701. *
  7702. * This implements the input routines used by the parser.
  7703. */
  7704. #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
  7705. enum {
  7706. INPUT_PUSH_FILE = 1,
  7707. INPUT_NOFILE_OK = 2,
  7708. };
  7709. static int plinno = 1; /* input line number */
  7710. /* number of characters left in input buffer */
  7711. static int parsenleft; /* copy of parsefile->nleft */
  7712. static int parselleft; /* copy of parsefile->lleft */
  7713. /* next character in input buffer */
  7714. static char *parsenextc; /* copy of parsefile->nextc */
  7715. static int checkkwd;
  7716. /* values of checkkwd variable */
  7717. #define CHKALIAS 0x1
  7718. #define CHKKWD 0x2
  7719. #define CHKNL 0x4
  7720. static void
  7721. popstring(void)
  7722. {
  7723. struct strpush *sp = parsefile->strpush;
  7724. INT_OFF;
  7725. #if ENABLE_ASH_ALIAS
  7726. if (sp->ap) {
  7727. if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
  7728. checkkwd |= CHKALIAS;
  7729. }
  7730. if (sp->string != sp->ap->val) {
  7731. free(sp->string);
  7732. }
  7733. sp->ap->flag &= ~ALIASINUSE;
  7734. if (sp->ap->flag & ALIASDEAD) {
  7735. unalias(sp->ap->name);
  7736. }
  7737. }
  7738. #endif
  7739. parsenextc = sp->prevstring;
  7740. parsenleft = sp->prevnleft;
  7741. /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
  7742. parsefile->strpush = sp->prev;
  7743. if (sp != &(parsefile->basestrpush))
  7744. free(sp);
  7745. INT_ON;
  7746. }
  7747. static int
  7748. preadfd(void)
  7749. {
  7750. int nr;
  7751. char *buf = parsefile->buf;
  7752. parsenextc = buf;
  7753. retry:
  7754. #if ENABLE_FEATURE_EDITING
  7755. if (!iflag || parsefile->fd)
  7756. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  7757. else {
  7758. #if ENABLE_FEATURE_TAB_COMPLETION
  7759. line_input_state->path_lookup = pathval();
  7760. #endif
  7761. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  7762. if (nr == 0) {
  7763. /* Ctrl+C pressed */
  7764. if (trap[SIGINT]) {
  7765. buf[0] = '\n';
  7766. buf[1] = '\0';
  7767. raise(SIGINT);
  7768. return 1;
  7769. }
  7770. goto retry;
  7771. }
  7772. if (nr < 0 && errno == 0) {
  7773. /* Ctrl+D presend */
  7774. nr = 0;
  7775. }
  7776. }
  7777. #else
  7778. nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
  7779. #endif
  7780. if (nr < 0) {
  7781. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  7782. int flags = fcntl(0, F_GETFL);
  7783. if (flags >= 0 && flags & O_NONBLOCK) {
  7784. flags &=~ O_NONBLOCK;
  7785. if (fcntl(0, F_SETFL, flags) >= 0) {
  7786. out2str("sh: turning off NDELAY mode\n");
  7787. goto retry;
  7788. }
  7789. }
  7790. }
  7791. }
  7792. return nr;
  7793. }
  7794. /*
  7795. * Refill the input buffer and return the next input character:
  7796. *
  7797. * 1) If a string was pushed back on the input, pop it;
  7798. * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
  7799. * from a string so we can't refill the buffer, return EOF.
  7800. * 3) If the is more stuff in this buffer, use it else call read to fill it.
  7801. * 4) Process input up to the next newline, deleting nul characters.
  7802. */
  7803. static int
  7804. preadbuffer(void)
  7805. {
  7806. char *q;
  7807. int more;
  7808. char savec;
  7809. while (parsefile->strpush) {
  7810. #if ENABLE_ASH_ALIAS
  7811. if (parsenleft == -1 && parsefile->strpush->ap &&
  7812. parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
  7813. return PEOA;
  7814. }
  7815. #endif
  7816. popstring();
  7817. if (--parsenleft >= 0)
  7818. return signed_char2int(*parsenextc++);
  7819. }
  7820. if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
  7821. return PEOF;
  7822. flush_stdout_stderr();
  7823. more = parselleft;
  7824. if (more <= 0) {
  7825. again:
  7826. more = preadfd();
  7827. if (more <= 0) {
  7828. parselleft = parsenleft = EOF_NLEFT;
  7829. return PEOF;
  7830. }
  7831. }
  7832. q = parsenextc;
  7833. /* delete nul characters */
  7834. for (;;) {
  7835. int c;
  7836. more--;
  7837. c = *q;
  7838. if (!c)
  7839. memmove(q, q + 1, more);
  7840. else {
  7841. q++;
  7842. if (c == '\n') {
  7843. parsenleft = q - parsenextc - 1;
  7844. break;
  7845. }
  7846. }
  7847. if (more <= 0) {
  7848. parsenleft = q - parsenextc - 1;
  7849. if (parsenleft < 0)
  7850. goto again;
  7851. break;
  7852. }
  7853. }
  7854. parselleft = more;
  7855. savec = *q;
  7856. *q = '\0';
  7857. if (vflag) {
  7858. out2str(parsenextc);
  7859. }
  7860. *q = savec;
  7861. return signed_char2int(*parsenextc++);
  7862. }
  7863. #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
  7864. static int
  7865. pgetc(void)
  7866. {
  7867. return pgetc_as_macro();
  7868. }
  7869. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  7870. #define pgetc_macro() pgetc()
  7871. #else
  7872. #define pgetc_macro() pgetc_as_macro()
  7873. #endif
  7874. /*
  7875. * Same as pgetc(), but ignores PEOA.
  7876. */
  7877. #if ENABLE_ASH_ALIAS
  7878. static int
  7879. pgetc2(void)
  7880. {
  7881. int c;
  7882. do {
  7883. c = pgetc_macro();
  7884. } while (c == PEOA);
  7885. return c;
  7886. }
  7887. #else
  7888. static int
  7889. pgetc2(void)
  7890. {
  7891. return pgetc_macro();
  7892. }
  7893. #endif
  7894. /*
  7895. * Read a line from the script.
  7896. */
  7897. static char *
  7898. pfgets(char *line, int len)
  7899. {
  7900. char *p = line;
  7901. int nleft = len;
  7902. int c;
  7903. while (--nleft > 0) {
  7904. c = pgetc2();
  7905. if (c == PEOF) {
  7906. if (p == line)
  7907. return NULL;
  7908. break;
  7909. }
  7910. *p++ = c;
  7911. if (c == '\n')
  7912. break;
  7913. }
  7914. *p = '\0';
  7915. return line;
  7916. }
  7917. /*
  7918. * Undo the last call to pgetc. Only one character may be pushed back.
  7919. * PEOF may be pushed back.
  7920. */
  7921. static void
  7922. pungetc(void)
  7923. {
  7924. parsenleft++;
  7925. parsenextc--;
  7926. }
  7927. /*
  7928. * Push a string back onto the input at this current parsefile level.
  7929. * We handle aliases this way.
  7930. */
  7931. static void
  7932. pushstring(char *s, void *ap)
  7933. {
  7934. struct strpush *sp;
  7935. size_t len;
  7936. len = strlen(s);
  7937. INT_OFF;
  7938. /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
  7939. if (parsefile->strpush) {
  7940. sp = ckmalloc(sizeof(struct strpush));
  7941. sp->prev = parsefile->strpush;
  7942. parsefile->strpush = sp;
  7943. } else
  7944. sp = parsefile->strpush = &(parsefile->basestrpush);
  7945. sp->prevstring = parsenextc;
  7946. sp->prevnleft = parsenleft;
  7947. #if ENABLE_ASH_ALIAS
  7948. sp->ap = (struct alias *)ap;
  7949. if (ap) {
  7950. ((struct alias *)ap)->flag |= ALIASINUSE;
  7951. sp->string = s;
  7952. }
  7953. #endif
  7954. parsenextc = s;
  7955. parsenleft = len;
  7956. INT_ON;
  7957. }
  7958. /*
  7959. * To handle the "." command, a stack of input files is used. Pushfile
  7960. * adds a new entry to the stack and popfile restores the previous level.
  7961. */
  7962. static void
  7963. pushfile(void)
  7964. {
  7965. struct parsefile *pf;
  7966. parsefile->nleft = parsenleft;
  7967. parsefile->lleft = parselleft;
  7968. parsefile->nextc = parsenextc;
  7969. parsefile->linno = plinno;
  7970. pf = ckmalloc(sizeof(*pf));
  7971. pf->prev = parsefile;
  7972. pf->fd = -1;
  7973. pf->strpush = NULL;
  7974. pf->basestrpush.prev = NULL;
  7975. parsefile = pf;
  7976. }
  7977. static void
  7978. popfile(void)
  7979. {
  7980. struct parsefile *pf = parsefile;
  7981. INT_OFF;
  7982. if (pf->fd >= 0)
  7983. close(pf->fd);
  7984. free(pf->buf);
  7985. while (pf->strpush)
  7986. popstring();
  7987. parsefile = pf->prev;
  7988. free(pf);
  7989. parsenleft = parsefile->nleft;
  7990. parselleft = parsefile->lleft;
  7991. parsenextc = parsefile->nextc;
  7992. plinno = parsefile->linno;
  7993. INT_ON;
  7994. }
  7995. /*
  7996. * Return to top level.
  7997. */
  7998. static void
  7999. popallfiles(void)
  8000. {
  8001. while (parsefile != &basepf)
  8002. popfile();
  8003. }
  8004. /*
  8005. * Close the file(s) that the shell is reading commands from. Called
  8006. * after a fork is done.
  8007. */
  8008. static void
  8009. closescript(void)
  8010. {
  8011. popallfiles();
  8012. if (parsefile->fd > 0) {
  8013. close(parsefile->fd);
  8014. parsefile->fd = 0;
  8015. }
  8016. }
  8017. /*
  8018. * Like setinputfile, but takes an open file descriptor. Call this with
  8019. * interrupts off.
  8020. */
  8021. static void
  8022. setinputfd(int fd, int push)
  8023. {
  8024. close_on_exec_on(fd);
  8025. if (push) {
  8026. pushfile();
  8027. parsefile->buf = 0;
  8028. }
  8029. parsefile->fd = fd;
  8030. if (parsefile->buf == NULL)
  8031. parsefile->buf = ckmalloc(IBUFSIZ);
  8032. parselleft = parsenleft = 0;
  8033. plinno = 1;
  8034. }
  8035. /*
  8036. * Set the input to take input from a file. If push is set, push the
  8037. * old input onto the stack first.
  8038. */
  8039. static int
  8040. setinputfile(const char *fname, int flags)
  8041. {
  8042. int fd;
  8043. int fd2;
  8044. INT_OFF;
  8045. fd = open(fname, O_RDONLY);
  8046. if (fd < 0) {
  8047. if (flags & INPUT_NOFILE_OK)
  8048. goto out;
  8049. ash_msg_and_raise_error("can't open %s", fname);
  8050. }
  8051. if (fd < 10) {
  8052. fd2 = copyfd(fd, 10);
  8053. close(fd);
  8054. if (fd2 < 0)
  8055. ash_msg_and_raise_error("out of file descriptors");
  8056. fd = fd2;
  8057. }
  8058. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8059. out:
  8060. INT_ON;
  8061. return fd;
  8062. }
  8063. /*
  8064. * Like setinputfile, but takes input from a string.
  8065. */
  8066. static void
  8067. setinputstring(char *string)
  8068. {
  8069. INT_OFF;
  8070. pushfile();
  8071. parsenextc = string;
  8072. parsenleft = strlen(string);
  8073. parsefile->buf = NULL;
  8074. plinno = 1;
  8075. INT_ON;
  8076. }
  8077. /* ============ mail.c
  8078. *
  8079. * Routines to check for mail.
  8080. */
  8081. #if ENABLE_ASH_MAIL
  8082. #define MAXMBOXES 10
  8083. /* times of mailboxes */
  8084. static time_t mailtime[MAXMBOXES];
  8085. /* Set if MAIL or MAILPATH is changed. */
  8086. static smallint mail_var_path_changed;
  8087. /*
  8088. * Print appropriate message(s) if mail has arrived.
  8089. * If mail_var_path_changed is set,
  8090. * then the value of MAIL has mail_var_path_changed,
  8091. * so we just update the values.
  8092. */
  8093. static void
  8094. chkmail(void)
  8095. {
  8096. const char *mpath;
  8097. char *p;
  8098. char *q;
  8099. time_t *mtp;
  8100. struct stackmark smark;
  8101. struct stat statb;
  8102. setstackmark(&smark);
  8103. mpath = mpathset() ? mpathval() : mailval();
  8104. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8105. p = padvance(&mpath, nullstr);
  8106. if (p == NULL)
  8107. break;
  8108. if (*p == '\0')
  8109. continue;
  8110. for (q = p; *q; q++);
  8111. #if DEBUG
  8112. if (q[-1] != '/')
  8113. abort();
  8114. #endif
  8115. q[-1] = '\0'; /* delete trailing '/' */
  8116. if (stat(p, &statb) < 0) {
  8117. *mtp = 0;
  8118. continue;
  8119. }
  8120. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8121. fprintf(
  8122. stderr, snlfmt,
  8123. pathopt ? pathopt : "you have mail"
  8124. );
  8125. }
  8126. *mtp = statb.st_mtime;
  8127. }
  8128. mail_var_path_changed = 0;
  8129. popstackmark(&smark);
  8130. }
  8131. static void
  8132. changemail(const char *val)
  8133. {
  8134. mail_var_path_changed = 1;
  8135. }
  8136. #endif /* ASH_MAIL */
  8137. /* ============ ??? */
  8138. /*
  8139. * Set the shell parameters.
  8140. */
  8141. static void
  8142. setparam(char **argv)
  8143. {
  8144. char **newparam;
  8145. char **ap;
  8146. int nparam;
  8147. for (nparam = 0; argv[nparam]; nparam++);
  8148. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  8149. while (*argv) {
  8150. *ap++ = ckstrdup(*argv++);
  8151. }
  8152. *ap = NULL;
  8153. freeparam(&shellparam);
  8154. shellparam.malloc = 1;
  8155. shellparam.nparam = nparam;
  8156. shellparam.p = newparam;
  8157. #if ENABLE_ASH_GETOPTS
  8158. shellparam.optind = 1;
  8159. shellparam.optoff = -1;
  8160. #endif
  8161. }
  8162. /*
  8163. * Process shell options. The global variable argptr contains a pointer
  8164. * to the argument list; we advance it past the options.
  8165. */
  8166. static void
  8167. minus_o(char *name, int val)
  8168. {
  8169. int i;
  8170. if (name) {
  8171. for (i = 0; i < NOPTS; i++) {
  8172. if (strcmp(name, optnames(i)) == 0) {
  8173. optlist[i] = val;
  8174. return;
  8175. }
  8176. }
  8177. ash_msg_and_raise_error("illegal option -o %s", name);
  8178. }
  8179. out1str("Current option settings\n");
  8180. for (i = 0; i < NOPTS; i++)
  8181. out1fmt("%-16s%s\n", optnames(i),
  8182. optlist[i] ? "on" : "off");
  8183. }
  8184. static void
  8185. setoption(int flag, int val)
  8186. {
  8187. int i;
  8188. for (i = 0; i < NOPTS; i++) {
  8189. if (optletters(i) == flag) {
  8190. optlist[i] = val;
  8191. return;
  8192. }
  8193. }
  8194. ash_msg_and_raise_error("illegal option -%c", flag);
  8195. /* NOTREACHED */
  8196. }
  8197. static void
  8198. options(int cmdline)
  8199. {
  8200. char *p;
  8201. int val;
  8202. int c;
  8203. if (cmdline)
  8204. minusc = NULL;
  8205. while ((p = *argptr) != NULL) {
  8206. c = *p++;
  8207. if (c != '-' && c != '+')
  8208. break;
  8209. argptr++;
  8210. val = 0; /* val = 0 if c == '+' */
  8211. if (c == '-') {
  8212. val = 1;
  8213. if (p[0] == '\0' || LONE_DASH(p)) {
  8214. if (!cmdline) {
  8215. /* "-" means turn off -x and -v */
  8216. if (p[0] == '\0')
  8217. xflag = vflag = 0;
  8218. /* "--" means reset params */
  8219. else if (*argptr == NULL)
  8220. setparam(argptr);
  8221. }
  8222. break; /* "-" or "--" terminates options */
  8223. }
  8224. }
  8225. /* first char was + or - */
  8226. while ((c = *p++) != '\0') {
  8227. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  8228. if (c == 'c' && cmdline) {
  8229. minusc = p; /* command is after shell args */
  8230. } else if (c == 'o') {
  8231. minus_o(*argptr, val);
  8232. if (*argptr)
  8233. argptr++;
  8234. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  8235. isloginsh = 1;
  8236. /* bash does not accept +-login, we also won't */
  8237. } else if (cmdline && val && (c == '-')) { /* long options */
  8238. if (strcmp(p, "login") == 0)
  8239. isloginsh = 1;
  8240. break;
  8241. } else {
  8242. setoption(c, val);
  8243. }
  8244. }
  8245. }
  8246. }
  8247. /*
  8248. * The shift builtin command.
  8249. */
  8250. static int
  8251. shiftcmd(int argc, char **argv)
  8252. {
  8253. int n;
  8254. char **ap1, **ap2;
  8255. n = 1;
  8256. if (argc > 1)
  8257. n = number(argv[1]);
  8258. if (n > shellparam.nparam)
  8259. ash_msg_and_raise_error("can't shift that many");
  8260. INT_OFF;
  8261. shellparam.nparam -= n;
  8262. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  8263. if (shellparam.malloc)
  8264. free(*ap1);
  8265. }
  8266. ap2 = shellparam.p;
  8267. while ((*ap2++ = *ap1++) != NULL);
  8268. #if ENABLE_ASH_GETOPTS
  8269. shellparam.optind = 1;
  8270. shellparam.optoff = -1;
  8271. #endif
  8272. INT_ON;
  8273. return 0;
  8274. }
  8275. /*
  8276. * POSIX requires that 'set' (but not export or readonly) output the
  8277. * variables in lexicographic order - by the locale's collating order (sigh).
  8278. * Maybe we could keep them in an ordered balanced binary tree
  8279. * instead of hashed lists.
  8280. * For now just roll 'em through qsort for printing...
  8281. */
  8282. static int
  8283. showvars(const char *sep_prefix, int on, int off)
  8284. {
  8285. const char *sep;
  8286. char **ep, **epend;
  8287. ep = listvars(on, off, &epend);
  8288. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  8289. sep = *sep_prefix ? " " : sep_prefix;
  8290. for (; ep < epend; ep++) {
  8291. const char *p;
  8292. const char *q;
  8293. p = strchrnul(*ep, '=');
  8294. q = nullstr;
  8295. if (*p)
  8296. q = single_quote(++p);
  8297. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  8298. }
  8299. return 0;
  8300. }
  8301. /*
  8302. * The set command builtin.
  8303. */
  8304. static int
  8305. setcmd(int argc, char **argv)
  8306. {
  8307. if (argc == 1)
  8308. return showvars(nullstr, 0, VUNSET);
  8309. INT_OFF;
  8310. options(0);
  8311. optschanged();
  8312. if (*argptr != NULL) {
  8313. setparam(argptr);
  8314. }
  8315. INT_ON;
  8316. return 0;
  8317. }
  8318. #if ENABLE_ASH_RANDOM_SUPPORT
  8319. /* Roughly copied from bash.. */
  8320. static void
  8321. change_random(const char *value)
  8322. {
  8323. if (value == NULL) {
  8324. /* "get", generate */
  8325. char buf[16];
  8326. rseed = rseed * 1103515245 + 12345;
  8327. sprintf(buf, "%d", (unsigned int)((rseed & 32767)));
  8328. /* set without recursion */
  8329. setvar(vrandom.text, buf, VNOFUNC);
  8330. vrandom.flags &= ~VNOFUNC;
  8331. } else {
  8332. /* set/reset */
  8333. rseed = strtoul(value, (char **)NULL, 10);
  8334. }
  8335. }
  8336. #endif
  8337. #if ENABLE_ASH_GETOPTS
  8338. static int
  8339. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  8340. {
  8341. char *p, *q;
  8342. char c = '?';
  8343. int done = 0;
  8344. int err = 0;
  8345. char s[12];
  8346. char **optnext;
  8347. if (*param_optind < 1)
  8348. return 1;
  8349. optnext = optfirst + *param_optind - 1;
  8350. if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
  8351. p = NULL;
  8352. else
  8353. p = optnext[-1] + *optoff;
  8354. if (p == NULL || *p == '\0') {
  8355. /* Current word is done, advance */
  8356. p = *optnext;
  8357. if (p == NULL || *p != '-' || *++p == '\0') {
  8358. atend:
  8359. p = NULL;
  8360. done = 1;
  8361. goto out;
  8362. }
  8363. optnext++;
  8364. if (LONE_DASH(p)) /* check for "--" */
  8365. goto atend;
  8366. }
  8367. c = *p++;
  8368. for (q = optstr; *q != c; ) {
  8369. if (*q == '\0') {
  8370. if (optstr[0] == ':') {
  8371. s[0] = c;
  8372. s[1] = '\0';
  8373. err |= setvarsafe("OPTARG", s, 0);
  8374. } else {
  8375. fprintf(stderr, "Illegal option -%c\n", c);
  8376. unsetvar("OPTARG");
  8377. }
  8378. c = '?';
  8379. goto out;
  8380. }
  8381. if (*++q == ':')
  8382. q++;
  8383. }
  8384. if (*++q == ':') {
  8385. if (*p == '\0' && (p = *optnext) == NULL) {
  8386. if (optstr[0] == ':') {
  8387. s[0] = c;
  8388. s[1] = '\0';
  8389. err |= setvarsafe("OPTARG", s, 0);
  8390. c = ':';
  8391. } else {
  8392. fprintf(stderr, "No arg for -%c option\n", c);
  8393. unsetvar("OPTARG");
  8394. c = '?';
  8395. }
  8396. goto out;
  8397. }
  8398. if (p == *optnext)
  8399. optnext++;
  8400. err |= setvarsafe("OPTARG", p, 0);
  8401. p = NULL;
  8402. } else
  8403. err |= setvarsafe("OPTARG", nullstr, 0);
  8404. out:
  8405. *optoff = p ? p - *(optnext - 1) : -1;
  8406. *param_optind = optnext - optfirst + 1;
  8407. fmtstr(s, sizeof(s), "%d", *param_optind);
  8408. err |= setvarsafe("OPTIND", s, VNOFUNC);
  8409. s[0] = c;
  8410. s[1] = '\0';
  8411. err |= setvarsafe(optvar, s, 0);
  8412. if (err) {
  8413. *param_optind = 1;
  8414. *optoff = -1;
  8415. flush_stdout_stderr();
  8416. raise_exception(EXERROR);
  8417. }
  8418. return done;
  8419. }
  8420. /*
  8421. * The getopts builtin. Shellparam.optnext points to the next argument
  8422. * to be processed. Shellparam.optptr points to the next character to
  8423. * be processed in the current argument. If shellparam.optnext is NULL,
  8424. * then it's the first time getopts has been called.
  8425. */
  8426. static int
  8427. getoptscmd(int argc, char **argv)
  8428. {
  8429. char **optbase;
  8430. if (argc < 3)
  8431. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  8432. if (argc == 3) {
  8433. optbase = shellparam.p;
  8434. if (shellparam.optind > shellparam.nparam + 1) {
  8435. shellparam.optind = 1;
  8436. shellparam.optoff = -1;
  8437. }
  8438. } else {
  8439. optbase = &argv[3];
  8440. if (shellparam.optind > argc - 2) {
  8441. shellparam.optind = 1;
  8442. shellparam.optoff = -1;
  8443. }
  8444. }
  8445. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  8446. &shellparam.optoff);
  8447. }
  8448. #endif /* ASH_GETOPTS */
  8449. /* ============ Shell parser */
  8450. /*
  8451. * NEOF is returned by parsecmd when it encounters an end of file. It
  8452. * must be distinct from NULL, so we use the address of a variable that
  8453. * happens to be handy.
  8454. */
  8455. static smallint tokpushback; /* last token pushed back */
  8456. #define NEOF ((union node *)&tokpushback)
  8457. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  8458. static int lasttoken; /* last token read */
  8459. static char *wordtext; /* text of last word returned by readtoken */
  8460. static struct nodelist *backquotelist;
  8461. static union node *redirnode;
  8462. static struct heredoc *heredoc;
  8463. static smallint quoteflag; /* set if (part of) last token was quoted */
  8464. static void raise_error_syntax(const char *) ATTRIBUTE_NORETURN;
  8465. static void
  8466. raise_error_syntax(const char *msg)
  8467. {
  8468. ash_msg_and_raise_error("syntax error: %s", msg);
  8469. /* NOTREACHED */
  8470. }
  8471. /*
  8472. * Called when an unexpected token is read during the parse. The argument
  8473. * is the token that is expected, or -1 if more than one type of token can
  8474. * occur at this point.
  8475. */
  8476. static void raise_error_unexpected_syntax(int) ATTRIBUTE_NORETURN;
  8477. static void
  8478. raise_error_unexpected_syntax(int token)
  8479. {
  8480. char msg[64];
  8481. int l;
  8482. l = sprintf(msg, "%s unexpected", tokname(lasttoken));
  8483. if (token >= 0)
  8484. sprintf(msg + l, " (expecting %s)", tokname(token));
  8485. raise_error_syntax(msg);
  8486. /* NOTREACHED */
  8487. }
  8488. #define EOFMARKLEN 79
  8489. struct heredoc {
  8490. struct heredoc *next; /* next here document in list */
  8491. union node *here; /* redirection node */
  8492. char *eofmark; /* string indicating end of input */
  8493. int striptabs; /* if set, strip leading tabs */
  8494. };
  8495. static struct heredoc *heredoclist; /* list of here documents to read */
  8496. /* parsing is heavily cross-recursive, need these forward decls */
  8497. static union node *andor(void);
  8498. static union node *pipeline(void);
  8499. static union node *parse_command(void);
  8500. static void parseheredoc(void);
  8501. static char peektoken(void);
  8502. static int readtoken(void);
  8503. static union node *
  8504. list(int nlflag)
  8505. {
  8506. union node *n1, *n2, *n3;
  8507. int tok;
  8508. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8509. if (nlflag == 2 && peektoken())
  8510. return NULL;
  8511. n1 = NULL;
  8512. for (;;) {
  8513. n2 = andor();
  8514. tok = readtoken();
  8515. if (tok == TBACKGND) {
  8516. if (n2->type == NPIPE) {
  8517. n2->npipe.backgnd = 1;
  8518. } else {
  8519. if (n2->type != NREDIR) {
  8520. n3 = stalloc(sizeof(struct nredir));
  8521. n3->nredir.n = n2;
  8522. n3->nredir.redirect = NULL;
  8523. n2 = n3;
  8524. }
  8525. n2->type = NBACKGND;
  8526. }
  8527. }
  8528. if (n1 == NULL) {
  8529. n1 = n2;
  8530. } else {
  8531. n3 = stalloc(sizeof(struct nbinary));
  8532. n3->type = NSEMI;
  8533. n3->nbinary.ch1 = n1;
  8534. n3->nbinary.ch2 = n2;
  8535. n1 = n3;
  8536. }
  8537. switch (tok) {
  8538. case TBACKGND:
  8539. case TSEMI:
  8540. tok = readtoken();
  8541. /* fall through */
  8542. case TNL:
  8543. if (tok == TNL) {
  8544. parseheredoc();
  8545. if (nlflag == 1)
  8546. return n1;
  8547. } else {
  8548. tokpushback = 1;
  8549. }
  8550. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8551. if (peektoken())
  8552. return n1;
  8553. break;
  8554. case TEOF:
  8555. if (heredoclist)
  8556. parseheredoc();
  8557. else
  8558. pungetc(); /* push back EOF on input */
  8559. return n1;
  8560. default:
  8561. if (nlflag == 1)
  8562. raise_error_unexpected_syntax(-1);
  8563. tokpushback = 1;
  8564. return n1;
  8565. }
  8566. }
  8567. }
  8568. static union node *
  8569. andor(void)
  8570. {
  8571. union node *n1, *n2, *n3;
  8572. int t;
  8573. n1 = pipeline();
  8574. for (;;) {
  8575. t = readtoken();
  8576. if (t == TAND) {
  8577. t = NAND;
  8578. } else if (t == TOR) {
  8579. t = NOR;
  8580. } else {
  8581. tokpushback = 1;
  8582. return n1;
  8583. }
  8584. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8585. n2 = pipeline();
  8586. n3 = stalloc(sizeof(struct nbinary));
  8587. n3->type = t;
  8588. n3->nbinary.ch1 = n1;
  8589. n3->nbinary.ch2 = n2;
  8590. n1 = n3;
  8591. }
  8592. }
  8593. static union node *
  8594. pipeline(void)
  8595. {
  8596. union node *n1, *n2, *pipenode;
  8597. struct nodelist *lp, *prev;
  8598. int negate;
  8599. negate = 0;
  8600. TRACE(("pipeline: entered\n"));
  8601. if (readtoken() == TNOT) {
  8602. negate = !negate;
  8603. checkkwd = CHKKWD | CHKALIAS;
  8604. } else
  8605. tokpushback = 1;
  8606. n1 = parse_command();
  8607. if (readtoken() == TPIPE) {
  8608. pipenode = stalloc(sizeof(struct npipe));
  8609. pipenode->type = NPIPE;
  8610. pipenode->npipe.backgnd = 0;
  8611. lp = stalloc(sizeof(struct nodelist));
  8612. pipenode->npipe.cmdlist = lp;
  8613. lp->n = n1;
  8614. do {
  8615. prev = lp;
  8616. lp = stalloc(sizeof(struct nodelist));
  8617. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8618. lp->n = parse_command();
  8619. prev->next = lp;
  8620. } while (readtoken() == TPIPE);
  8621. lp->next = NULL;
  8622. n1 = pipenode;
  8623. }
  8624. tokpushback = 1;
  8625. if (negate) {
  8626. n2 = stalloc(sizeof(struct nnot));
  8627. n2->type = NNOT;
  8628. n2->nnot.com = n1;
  8629. return n2;
  8630. }
  8631. return n1;
  8632. }
  8633. static union node *
  8634. makename(void)
  8635. {
  8636. union node *n;
  8637. n = stalloc(sizeof(struct narg));
  8638. n->type = NARG;
  8639. n->narg.next = NULL;
  8640. n->narg.text = wordtext;
  8641. n->narg.backquote = backquotelist;
  8642. return n;
  8643. }
  8644. static void
  8645. fixredir(union node *n, const char *text, int err)
  8646. {
  8647. TRACE(("Fix redir %s %d\n", text, err));
  8648. if (!err)
  8649. n->ndup.vname = NULL;
  8650. if (isdigit(text[0]) && text[1] == '\0')
  8651. n->ndup.dupfd = text[0] - '0';
  8652. else if (LONE_DASH(text))
  8653. n->ndup.dupfd = -1;
  8654. else {
  8655. if (err)
  8656. raise_error_syntax("Bad fd number");
  8657. n->ndup.vname = makename();
  8658. }
  8659. }
  8660. /*
  8661. * Returns true if the text contains nothing to expand (no dollar signs
  8662. * or backquotes).
  8663. */
  8664. static int
  8665. noexpand(char *text)
  8666. {
  8667. char *p;
  8668. char c;
  8669. p = text;
  8670. while ((c = *p++) != '\0') {
  8671. if (c == CTLQUOTEMARK)
  8672. continue;
  8673. if (c == CTLESC)
  8674. p++;
  8675. else if (SIT(c, BASESYNTAX) == CCTL)
  8676. return 0;
  8677. }
  8678. return 1;
  8679. }
  8680. static void
  8681. parsefname(void)
  8682. {
  8683. union node *n = redirnode;
  8684. if (readtoken() != TWORD)
  8685. raise_error_unexpected_syntax(-1);
  8686. if (n->type == NHERE) {
  8687. struct heredoc *here = heredoc;
  8688. struct heredoc *p;
  8689. int i;
  8690. if (quoteflag == 0)
  8691. n->type = NXHERE;
  8692. TRACE(("Here document %d\n", n->type));
  8693. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  8694. raise_error_syntax("Illegal eof marker for << redirection");
  8695. rmescapes(wordtext);
  8696. here->eofmark = wordtext;
  8697. here->next = NULL;
  8698. if (heredoclist == NULL)
  8699. heredoclist = here;
  8700. else {
  8701. for (p = heredoclist; p->next; p = p->next);
  8702. p->next = here;
  8703. }
  8704. } else if (n->type == NTOFD || n->type == NFROMFD) {
  8705. fixredir(n, wordtext, 0);
  8706. } else {
  8707. n->nfile.fname = makename();
  8708. }
  8709. }
  8710. static union node *
  8711. simplecmd(void)
  8712. {
  8713. union node *args, **app;
  8714. union node *n = NULL;
  8715. union node *vars, **vpp;
  8716. union node **rpp, *redir;
  8717. int savecheckkwd;
  8718. args = NULL;
  8719. app = &args;
  8720. vars = NULL;
  8721. vpp = &vars;
  8722. redir = NULL;
  8723. rpp = &redir;
  8724. savecheckkwd = CHKALIAS;
  8725. for (;;) {
  8726. checkkwd = savecheckkwd;
  8727. switch (readtoken()) {
  8728. case TWORD:
  8729. n = stalloc(sizeof(struct narg));
  8730. n->type = NARG;
  8731. n->narg.text = wordtext;
  8732. n->narg.backquote = backquotelist;
  8733. if (savecheckkwd && isassignment(wordtext)) {
  8734. *vpp = n;
  8735. vpp = &n->narg.next;
  8736. } else {
  8737. *app = n;
  8738. app = &n->narg.next;
  8739. savecheckkwd = 0;
  8740. }
  8741. break;
  8742. case TREDIR:
  8743. *rpp = n = redirnode;
  8744. rpp = &n->nfile.next;
  8745. parsefname(); /* read name of redirection file */
  8746. break;
  8747. case TLP:
  8748. if (args && app == &args->narg.next
  8749. && !vars && !redir
  8750. ) {
  8751. struct builtincmd *bcmd;
  8752. const char *name;
  8753. /* We have a function */
  8754. if (readtoken() != TRP)
  8755. raise_error_unexpected_syntax(TRP);
  8756. name = n->narg.text;
  8757. if (!goodname(name)
  8758. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  8759. ) {
  8760. raise_error_syntax("Bad function name");
  8761. }
  8762. n->type = NDEFUN;
  8763. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8764. n->narg.next = parse_command();
  8765. return n;
  8766. }
  8767. /* fall through */
  8768. default:
  8769. tokpushback = 1;
  8770. goto out;
  8771. }
  8772. }
  8773. out:
  8774. *app = NULL;
  8775. *vpp = NULL;
  8776. *rpp = NULL;
  8777. n = stalloc(sizeof(struct ncmd));
  8778. n->type = NCMD;
  8779. n->ncmd.args = args;
  8780. n->ncmd.assign = vars;
  8781. n->ncmd.redirect = redir;
  8782. return n;
  8783. }
  8784. static union node *
  8785. parse_command(void)
  8786. {
  8787. union node *n1, *n2;
  8788. union node *ap, **app;
  8789. union node *cp, **cpp;
  8790. union node *redir, **rpp;
  8791. union node **rpp2;
  8792. int t;
  8793. redir = NULL;
  8794. rpp2 = &redir;
  8795. switch (readtoken()) {
  8796. default:
  8797. raise_error_unexpected_syntax(-1);
  8798. /* NOTREACHED */
  8799. case TIF:
  8800. n1 = stalloc(sizeof(struct nif));
  8801. n1->type = NIF;
  8802. n1->nif.test = list(0);
  8803. if (readtoken() != TTHEN)
  8804. raise_error_unexpected_syntax(TTHEN);
  8805. n1->nif.ifpart = list(0);
  8806. n2 = n1;
  8807. while (readtoken() == TELIF) {
  8808. n2->nif.elsepart = stalloc(sizeof(struct nif));
  8809. n2 = n2->nif.elsepart;
  8810. n2->type = NIF;
  8811. n2->nif.test = list(0);
  8812. if (readtoken() != TTHEN)
  8813. raise_error_unexpected_syntax(TTHEN);
  8814. n2->nif.ifpart = list(0);
  8815. }
  8816. if (lasttoken == TELSE)
  8817. n2->nif.elsepart = list(0);
  8818. else {
  8819. n2->nif.elsepart = NULL;
  8820. tokpushback = 1;
  8821. }
  8822. t = TFI;
  8823. break;
  8824. case TWHILE:
  8825. case TUNTIL: {
  8826. int got;
  8827. n1 = stalloc(sizeof(struct nbinary));
  8828. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  8829. n1->nbinary.ch1 = list(0);
  8830. got = readtoken();
  8831. if (got != TDO) {
  8832. TRACE(("expecting DO got %s %s\n", tokname(got),
  8833. got == TWORD ? wordtext : ""));
  8834. raise_error_unexpected_syntax(TDO);
  8835. }
  8836. n1->nbinary.ch2 = list(0);
  8837. t = TDONE;
  8838. break;
  8839. }
  8840. case TFOR:
  8841. if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
  8842. raise_error_syntax("Bad for loop variable");
  8843. n1 = stalloc(sizeof(struct nfor));
  8844. n1->type = NFOR;
  8845. n1->nfor.var = wordtext;
  8846. checkkwd = CHKKWD | CHKALIAS;
  8847. if (readtoken() == TIN) {
  8848. app = &ap;
  8849. while (readtoken() == TWORD) {
  8850. n2 = stalloc(sizeof(struct narg));
  8851. n2->type = NARG;
  8852. n2->narg.text = wordtext;
  8853. n2->narg.backquote = backquotelist;
  8854. *app = n2;
  8855. app = &n2->narg.next;
  8856. }
  8857. *app = NULL;
  8858. n1->nfor.args = ap;
  8859. if (lasttoken != TNL && lasttoken != TSEMI)
  8860. raise_error_unexpected_syntax(-1);
  8861. } else {
  8862. n2 = stalloc(sizeof(struct narg));
  8863. n2->type = NARG;
  8864. n2->narg.text = (char *)dolatstr;
  8865. n2->narg.backquote = NULL;
  8866. n2->narg.next = NULL;
  8867. n1->nfor.args = n2;
  8868. /*
  8869. * Newline or semicolon here is optional (but note
  8870. * that the original Bourne shell only allowed NL).
  8871. */
  8872. if (lasttoken != TNL && lasttoken != TSEMI)
  8873. tokpushback = 1;
  8874. }
  8875. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  8876. if (readtoken() != TDO)
  8877. raise_error_unexpected_syntax(TDO);
  8878. n1->nfor.body = list(0);
  8879. t = TDONE;
  8880. break;
  8881. case TCASE:
  8882. n1 = stalloc(sizeof(struct ncase));
  8883. n1->type = NCASE;
  8884. if (readtoken() != TWORD)
  8885. raise_error_unexpected_syntax(TWORD);
  8886. n1->ncase.expr = n2 = stalloc(sizeof(struct narg));
  8887. n2->type = NARG;
  8888. n2->narg.text = wordtext;
  8889. n2->narg.backquote = backquotelist;
  8890. n2->narg.next = NULL;
  8891. do {
  8892. checkkwd = CHKKWD | CHKALIAS;
  8893. } while (readtoken() == TNL);
  8894. if (lasttoken != TIN)
  8895. raise_error_unexpected_syntax(TIN);
  8896. cpp = &n1->ncase.cases;
  8897. next_case:
  8898. checkkwd = CHKNL | CHKKWD;
  8899. t = readtoken();
  8900. while (t != TESAC) {
  8901. if (lasttoken == TLP)
  8902. readtoken();
  8903. *cpp = cp = stalloc(sizeof(struct nclist));
  8904. cp->type = NCLIST;
  8905. app = &cp->nclist.pattern;
  8906. for (;;) {
  8907. *app = ap = stalloc(sizeof(struct narg));
  8908. ap->type = NARG;
  8909. ap->narg.text = wordtext;
  8910. ap->narg.backquote = backquotelist;
  8911. if (readtoken() != TPIPE)
  8912. break;
  8913. app = &ap->narg.next;
  8914. readtoken();
  8915. }
  8916. ap->narg.next = NULL;
  8917. if (lasttoken != TRP)
  8918. raise_error_unexpected_syntax(TRP);
  8919. cp->nclist.body = list(2);
  8920. cpp = &cp->nclist.next;
  8921. checkkwd = CHKNL | CHKKWD;
  8922. t = readtoken();
  8923. if (t != TESAC) {
  8924. if (t != TENDCASE)
  8925. raise_error_unexpected_syntax(TENDCASE);
  8926. goto next_case;
  8927. }
  8928. }
  8929. *cpp = NULL;
  8930. goto redir;
  8931. case TLP:
  8932. n1 = stalloc(sizeof(struct nredir));
  8933. n1->type = NSUBSHELL;
  8934. n1->nredir.n = list(0);
  8935. n1->nredir.redirect = NULL;
  8936. t = TRP;
  8937. break;
  8938. case TBEGIN:
  8939. n1 = list(0);
  8940. t = TEND;
  8941. break;
  8942. case TWORD:
  8943. case TREDIR:
  8944. tokpushback = 1;
  8945. return simplecmd();
  8946. }
  8947. if (readtoken() != t)
  8948. raise_error_unexpected_syntax(t);
  8949. redir:
  8950. /* Now check for redirection which may follow command */
  8951. checkkwd = CHKKWD | CHKALIAS;
  8952. rpp = rpp2;
  8953. while (readtoken() == TREDIR) {
  8954. *rpp = n2 = redirnode;
  8955. rpp = &n2->nfile.next;
  8956. parsefname();
  8957. }
  8958. tokpushback = 1;
  8959. *rpp = NULL;
  8960. if (redir) {
  8961. if (n1->type != NSUBSHELL) {
  8962. n2 = stalloc(sizeof(struct nredir));
  8963. n2->type = NREDIR;
  8964. n2->nredir.n = n1;
  8965. n1 = n2;
  8966. }
  8967. n1->nredir.redirect = redir;
  8968. }
  8969. return n1;
  8970. }
  8971. /*
  8972. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  8973. * is not NULL, read a here document. In the latter case, eofmark is the
  8974. * word which marks the end of the document and striptabs is true if
  8975. * leading tabs should be stripped from the document. The argument firstc
  8976. * is the first character of the input token or document.
  8977. *
  8978. * Because C does not have internal subroutines, I have simulated them
  8979. * using goto's to implement the subroutine linkage. The following macros
  8980. * will run code that appears at the end of readtoken1.
  8981. */
  8982. #define CHECKEND() {goto checkend; checkend_return:;}
  8983. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  8984. #define PARSESUB() {goto parsesub; parsesub_return:;}
  8985. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  8986. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  8987. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  8988. static int
  8989. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  8990. {
  8991. /* NB: syntax parameter fits into smallint */
  8992. int c = firstc;
  8993. char *out;
  8994. int len;
  8995. char line[EOFMARKLEN + 1];
  8996. struct nodelist *bqlist;
  8997. smallint quotef;
  8998. smallint dblquote;
  8999. smallint oldstyle;
  9000. smallint prevsyntax; /* syntax before arithmetic */
  9001. #if ENABLE_ASH_EXPAND_PRMT
  9002. smallint pssyntax; /* we are expanding a prompt string */
  9003. #endif
  9004. int varnest; /* levels of variables expansion */
  9005. int arinest; /* levels of arithmetic expansion */
  9006. int parenlevel; /* levels of parens in arithmetic */
  9007. int dqvarnest; /* levels of variables expansion within double quotes */
  9008. #if __GNUC__
  9009. /* Avoid longjmp clobbering */
  9010. (void) &out;
  9011. (void) &quotef;
  9012. (void) &dblquote;
  9013. (void) &varnest;
  9014. (void) &arinest;
  9015. (void) &parenlevel;
  9016. (void) &dqvarnest;
  9017. (void) &oldstyle;
  9018. (void) &prevsyntax;
  9019. (void) &syntax;
  9020. #endif
  9021. startlinno = plinno;
  9022. bqlist = NULL;
  9023. quotef = 0;
  9024. oldstyle = 0;
  9025. prevsyntax = 0;
  9026. #if ENABLE_ASH_EXPAND_PRMT
  9027. pssyntax = (syntax == PSSYNTAX);
  9028. if (pssyntax)
  9029. syntax = DQSYNTAX;
  9030. #endif
  9031. dblquote = (syntax == DQSYNTAX);
  9032. varnest = 0;
  9033. arinest = 0;
  9034. parenlevel = 0;
  9035. dqvarnest = 0;
  9036. STARTSTACKSTR(out);
  9037. loop: { /* for each line, until end of word */
  9038. CHECKEND(); /* set c to PEOF if at end of here document */
  9039. for (;;) { /* until end of line or end of word */
  9040. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  9041. switch (SIT(c, syntax)) {
  9042. case CNL: /* '\n' */
  9043. if (syntax == BASESYNTAX)
  9044. goto endword; /* exit outer loop */
  9045. USTPUTC(c, out);
  9046. plinno++;
  9047. if (doprompt)
  9048. setprompt(2);
  9049. c = pgetc();
  9050. goto loop; /* continue outer loop */
  9051. case CWORD:
  9052. USTPUTC(c, out);
  9053. break;
  9054. case CCTL:
  9055. if (eofmark == NULL || dblquote)
  9056. USTPUTC(CTLESC, out);
  9057. USTPUTC(c, out);
  9058. break;
  9059. case CBACK: /* backslash */
  9060. c = pgetc2();
  9061. if (c == PEOF) {
  9062. USTPUTC(CTLESC, out);
  9063. USTPUTC('\\', out);
  9064. pungetc();
  9065. } else if (c == '\n') {
  9066. if (doprompt)
  9067. setprompt(2);
  9068. } else {
  9069. #if ENABLE_ASH_EXPAND_PRMT
  9070. if (c == '$' && pssyntax) {
  9071. USTPUTC(CTLESC, out);
  9072. USTPUTC('\\', out);
  9073. }
  9074. #endif
  9075. if (dblquote &&
  9076. c != '\\' && c != '`' &&
  9077. c != '$' && (
  9078. c != '"' ||
  9079. eofmark != NULL)
  9080. ) {
  9081. USTPUTC(CTLESC, out);
  9082. USTPUTC('\\', out);
  9083. }
  9084. if (SIT(c, SQSYNTAX) == CCTL)
  9085. USTPUTC(CTLESC, out);
  9086. USTPUTC(c, out);
  9087. quotef = 1;
  9088. }
  9089. break;
  9090. case CSQUOTE:
  9091. syntax = SQSYNTAX;
  9092. quotemark:
  9093. if (eofmark == NULL) {
  9094. USTPUTC(CTLQUOTEMARK, out);
  9095. }
  9096. break;
  9097. case CDQUOTE:
  9098. syntax = DQSYNTAX;
  9099. dblquote = 1;
  9100. goto quotemark;
  9101. case CENDQUOTE:
  9102. if (eofmark != NULL && arinest == 0
  9103. && varnest == 0
  9104. ) {
  9105. USTPUTC(c, out);
  9106. } else {
  9107. if (dqvarnest == 0) {
  9108. syntax = BASESYNTAX;
  9109. dblquote = 0;
  9110. }
  9111. quotef = 1;
  9112. goto quotemark;
  9113. }
  9114. break;
  9115. case CVAR: /* '$' */
  9116. PARSESUB(); /* parse substitution */
  9117. break;
  9118. case CENDVAR: /* '}' */
  9119. if (varnest > 0) {
  9120. varnest--;
  9121. if (dqvarnest > 0) {
  9122. dqvarnest--;
  9123. }
  9124. USTPUTC(CTLENDVAR, out);
  9125. } else {
  9126. USTPUTC(c, out);
  9127. }
  9128. break;
  9129. #if ENABLE_ASH_MATH_SUPPORT
  9130. case CLP: /* '(' in arithmetic */
  9131. parenlevel++;
  9132. USTPUTC(c, out);
  9133. break;
  9134. case CRP: /* ')' in arithmetic */
  9135. if (parenlevel > 0) {
  9136. USTPUTC(c, out);
  9137. --parenlevel;
  9138. } else {
  9139. if (pgetc() == ')') {
  9140. if (--arinest == 0) {
  9141. USTPUTC(CTLENDARI, out);
  9142. syntax = prevsyntax;
  9143. dblquote = (syntax == DQSYNTAX);
  9144. } else
  9145. USTPUTC(')', out);
  9146. } else {
  9147. /*
  9148. * unbalanced parens
  9149. * (don't 2nd guess - no error)
  9150. */
  9151. pungetc();
  9152. USTPUTC(')', out);
  9153. }
  9154. }
  9155. break;
  9156. #endif
  9157. case CBQUOTE: /* '`' */
  9158. PARSEBACKQOLD();
  9159. break;
  9160. case CENDFILE:
  9161. goto endword; /* exit outer loop */
  9162. case CIGN:
  9163. break;
  9164. default:
  9165. if (varnest == 0)
  9166. goto endword; /* exit outer loop */
  9167. #if ENABLE_ASH_ALIAS
  9168. if (c != PEOA)
  9169. #endif
  9170. USTPUTC(c, out);
  9171. }
  9172. c = pgetc_macro();
  9173. }
  9174. }
  9175. endword:
  9176. #if ENABLE_ASH_MATH_SUPPORT
  9177. if (syntax == ARISYNTAX)
  9178. raise_error_syntax("Missing '))'");
  9179. #endif
  9180. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  9181. raise_error_syntax("Unterminated quoted string");
  9182. if (varnest != 0) {
  9183. startlinno = plinno;
  9184. /* { */
  9185. raise_error_syntax("Missing '}'");
  9186. }
  9187. USTPUTC('\0', out);
  9188. len = out - (char *)stackblock();
  9189. out = stackblock();
  9190. if (eofmark == NULL) {
  9191. if ((c == '>' || c == '<')
  9192. && quotef == 0
  9193. && len <= 2
  9194. && (*out == '\0' || isdigit(*out))) {
  9195. PARSEREDIR();
  9196. return lasttoken = TREDIR;
  9197. } else {
  9198. pungetc();
  9199. }
  9200. }
  9201. quoteflag = quotef;
  9202. backquotelist = bqlist;
  9203. grabstackblock(len);
  9204. wordtext = out;
  9205. lasttoken = TWORD;
  9206. return lasttoken;
  9207. /* end of readtoken routine */
  9208. /*
  9209. * Check to see whether we are at the end of the here document. When this
  9210. * is called, c is set to the first character of the next input line. If
  9211. * we are at the end of the here document, this routine sets the c to PEOF.
  9212. */
  9213. checkend: {
  9214. if (eofmark) {
  9215. #if ENABLE_ASH_ALIAS
  9216. if (c == PEOA) {
  9217. c = pgetc2();
  9218. }
  9219. #endif
  9220. if (striptabs) {
  9221. while (c == '\t') {
  9222. c = pgetc2();
  9223. }
  9224. }
  9225. if (c == *eofmark) {
  9226. if (pfgets(line, sizeof(line)) != NULL) {
  9227. char *p, *q;
  9228. p = line;
  9229. for (q = eofmark + 1; *q && *p == *q; p++, q++);
  9230. if (*p == '\n' && *q == '\0') {
  9231. c = PEOF;
  9232. plinno++;
  9233. needprompt = doprompt;
  9234. } else {
  9235. pushstring(line, NULL);
  9236. }
  9237. }
  9238. }
  9239. }
  9240. goto checkend_return;
  9241. }
  9242. /*
  9243. * Parse a redirection operator. The variable "out" points to a string
  9244. * specifying the fd to be redirected. The variable "c" contains the
  9245. * first character of the redirection operator.
  9246. */
  9247. parseredir: {
  9248. char fd = *out;
  9249. union node *np;
  9250. np = stalloc(sizeof(struct nfile));
  9251. if (c == '>') {
  9252. np->nfile.fd = 1;
  9253. c = pgetc();
  9254. if (c == '>')
  9255. np->type = NAPPEND;
  9256. else if (c == '|')
  9257. np->type = NCLOBBER;
  9258. else if (c == '&')
  9259. np->type = NTOFD;
  9260. else {
  9261. np->type = NTO;
  9262. pungetc();
  9263. }
  9264. } else { /* c == '<' */
  9265. np->nfile.fd = 0;
  9266. c = pgetc();
  9267. switch (c) {
  9268. case '<':
  9269. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  9270. np = stalloc(sizeof(struct nhere));
  9271. np->nfile.fd = 0;
  9272. }
  9273. np->type = NHERE;
  9274. heredoc = stalloc(sizeof(struct heredoc));
  9275. heredoc->here = np;
  9276. c = pgetc();
  9277. if (c == '-') {
  9278. heredoc->striptabs = 1;
  9279. } else {
  9280. heredoc->striptabs = 0;
  9281. pungetc();
  9282. }
  9283. break;
  9284. case '&':
  9285. np->type = NFROMFD;
  9286. break;
  9287. case '>':
  9288. np->type = NFROMTO;
  9289. break;
  9290. default:
  9291. np->type = NFROM;
  9292. pungetc();
  9293. break;
  9294. }
  9295. }
  9296. if (fd != '\0')
  9297. np->nfile.fd = fd - '0';
  9298. redirnode = np;
  9299. goto parseredir_return;
  9300. }
  9301. /*
  9302. * Parse a substitution. At this point, we have read the dollar sign
  9303. * and nothing else.
  9304. */
  9305. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  9306. * (assuming ascii char codes, as the original implementation did) */
  9307. #define is_special(c) \
  9308. ((((unsigned int)c) - 33 < 32) \
  9309. && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
  9310. parsesub: {
  9311. int subtype;
  9312. int typeloc;
  9313. int flags;
  9314. char *p;
  9315. static const char types[] ALIGN1 = "}-+?=";
  9316. c = pgetc();
  9317. if (
  9318. c <= PEOA_OR_PEOF ||
  9319. (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  9320. ) {
  9321. USTPUTC('$', out);
  9322. pungetc();
  9323. } else if (c == '(') { /* $(command) or $((arith)) */
  9324. if (pgetc() == '(') {
  9325. #if ENABLE_ASH_MATH_SUPPORT
  9326. PARSEARITH();
  9327. #else
  9328. raise_error_syntax("We unsupport $((arith))");
  9329. #endif
  9330. } else {
  9331. pungetc();
  9332. PARSEBACKQNEW();
  9333. }
  9334. } else {
  9335. USTPUTC(CTLVAR, out);
  9336. typeloc = out - (char *)stackblock();
  9337. USTPUTC(VSNORMAL, out);
  9338. subtype = VSNORMAL;
  9339. if (c == '{') {
  9340. c = pgetc();
  9341. if (c == '#') {
  9342. c = pgetc();
  9343. if (c == '}')
  9344. c = '#';
  9345. else
  9346. subtype = VSLENGTH;
  9347. } else
  9348. subtype = 0;
  9349. }
  9350. if (c > PEOA_OR_PEOF && is_name(c)) {
  9351. do {
  9352. STPUTC(c, out);
  9353. c = pgetc();
  9354. } while (c > PEOA_OR_PEOF && is_in_name(c));
  9355. } else if (isdigit(c)) {
  9356. do {
  9357. STPUTC(c, out);
  9358. c = pgetc();
  9359. } while (isdigit(c));
  9360. } else if (is_special(c)) {
  9361. USTPUTC(c, out);
  9362. c = pgetc();
  9363. } else
  9364. badsub: raise_error_syntax("Bad substitution");
  9365. STPUTC('=', out);
  9366. flags = 0;
  9367. if (subtype == 0) {
  9368. switch (c) {
  9369. case ':':
  9370. flags = VSNUL;
  9371. c = pgetc();
  9372. /*FALLTHROUGH*/
  9373. default:
  9374. p = strchr(types, c);
  9375. if (p == NULL)
  9376. goto badsub;
  9377. subtype = p - types + VSNORMAL;
  9378. break;
  9379. case '%':
  9380. case '#':
  9381. {
  9382. int cc = c;
  9383. subtype = c == '#' ? VSTRIMLEFT :
  9384. VSTRIMRIGHT;
  9385. c = pgetc();
  9386. if (c == cc)
  9387. subtype++;
  9388. else
  9389. pungetc();
  9390. break;
  9391. }
  9392. }
  9393. } else {
  9394. pungetc();
  9395. }
  9396. if (dblquote || arinest)
  9397. flags |= VSQUOTE;
  9398. *((char *)stackblock() + typeloc) = subtype | flags;
  9399. if (subtype != VSNORMAL) {
  9400. varnest++;
  9401. if (dblquote || arinest) {
  9402. dqvarnest++;
  9403. }
  9404. }
  9405. }
  9406. goto parsesub_return;
  9407. }
  9408. /*
  9409. * Called to parse command substitutions. Newstyle is set if the command
  9410. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  9411. * list of commands (passed by reference), and savelen is the number of
  9412. * characters on the top of the stack which must be preserved.
  9413. */
  9414. parsebackq: {
  9415. struct nodelist **nlpp;
  9416. smallint savepbq;
  9417. union node *n;
  9418. char *volatile str;
  9419. struct jmploc jmploc;
  9420. struct jmploc *volatile savehandler;
  9421. size_t savelen;
  9422. smallint saveprompt = 0;
  9423. #ifdef __GNUC__
  9424. (void) &saveprompt;
  9425. #endif
  9426. savepbq = parsebackquote;
  9427. if (setjmp(jmploc.loc)) {
  9428. free(str);
  9429. parsebackquote = 0;
  9430. exception_handler = savehandler;
  9431. longjmp(exception_handler->loc, 1);
  9432. }
  9433. INT_OFF;
  9434. str = NULL;
  9435. savelen = out - (char *)stackblock();
  9436. if (savelen > 0) {
  9437. str = ckmalloc(savelen);
  9438. memcpy(str, stackblock(), savelen);
  9439. }
  9440. savehandler = exception_handler;
  9441. exception_handler = &jmploc;
  9442. INT_ON;
  9443. if (oldstyle) {
  9444. /* We must read until the closing backquote, giving special
  9445. treatment to some slashes, and then push the string and
  9446. reread it as input, interpreting it normally. */
  9447. char *pout;
  9448. int pc;
  9449. size_t psavelen;
  9450. char *pstr;
  9451. STARTSTACKSTR(pout);
  9452. for (;;) {
  9453. if (needprompt) {
  9454. setprompt(2);
  9455. }
  9456. pc = pgetc();
  9457. switch (pc) {
  9458. case '`':
  9459. goto done;
  9460. case '\\':
  9461. pc = pgetc();
  9462. if (pc == '\n') {
  9463. plinno++;
  9464. if (doprompt)
  9465. setprompt(2);
  9466. /*
  9467. * If eating a newline, avoid putting
  9468. * the newline into the new character
  9469. * stream (via the STPUTC after the
  9470. * switch).
  9471. */
  9472. continue;
  9473. }
  9474. if (pc != '\\' && pc != '`' && pc != '$'
  9475. && (!dblquote || pc != '"'))
  9476. STPUTC('\\', pout);
  9477. if (pc > PEOA_OR_PEOF) {
  9478. break;
  9479. }
  9480. /* fall through */
  9481. case PEOF:
  9482. #if ENABLE_ASH_ALIAS
  9483. case PEOA:
  9484. #endif
  9485. startlinno = plinno;
  9486. raise_error_syntax("EOF in backquote substitution");
  9487. case '\n':
  9488. plinno++;
  9489. needprompt = doprompt;
  9490. break;
  9491. default:
  9492. break;
  9493. }
  9494. STPUTC(pc, pout);
  9495. }
  9496. done:
  9497. STPUTC('\0', pout);
  9498. psavelen = pout - (char *)stackblock();
  9499. if (psavelen > 0) {
  9500. pstr = grabstackstr(pout);
  9501. setinputstring(pstr);
  9502. }
  9503. }
  9504. nlpp = &bqlist;
  9505. while (*nlpp)
  9506. nlpp = &(*nlpp)->next;
  9507. *nlpp = stalloc(sizeof(**nlpp));
  9508. (*nlpp)->next = NULL;
  9509. parsebackquote = oldstyle;
  9510. if (oldstyle) {
  9511. saveprompt = doprompt;
  9512. doprompt = 0;
  9513. }
  9514. n = list(2);
  9515. if (oldstyle)
  9516. doprompt = saveprompt;
  9517. else if (readtoken() != TRP)
  9518. raise_error_unexpected_syntax(TRP);
  9519. (*nlpp)->n = n;
  9520. if (oldstyle) {
  9521. /*
  9522. * Start reading from old file again, ignoring any pushed back
  9523. * tokens left from the backquote parsing
  9524. */
  9525. popfile();
  9526. tokpushback = 0;
  9527. }
  9528. while (stackblocksize() <= savelen)
  9529. growstackblock();
  9530. STARTSTACKSTR(out);
  9531. if (str) {
  9532. memcpy(out, str, savelen);
  9533. STADJUST(savelen, out);
  9534. INT_OFF;
  9535. free(str);
  9536. str = NULL;
  9537. INT_ON;
  9538. }
  9539. parsebackquote = savepbq;
  9540. exception_handler = savehandler;
  9541. if (arinest || dblquote)
  9542. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  9543. else
  9544. USTPUTC(CTLBACKQ, out);
  9545. if (oldstyle)
  9546. goto parsebackq_oldreturn;
  9547. goto parsebackq_newreturn;
  9548. }
  9549. #if ENABLE_ASH_MATH_SUPPORT
  9550. /*
  9551. * Parse an arithmetic expansion (indicate start of one and set state)
  9552. */
  9553. parsearith: {
  9554. if (++arinest == 1) {
  9555. prevsyntax = syntax;
  9556. syntax = ARISYNTAX;
  9557. USTPUTC(CTLARI, out);
  9558. if (dblquote)
  9559. USTPUTC('"', out);
  9560. else
  9561. USTPUTC(' ', out);
  9562. } else {
  9563. /*
  9564. * we collapse embedded arithmetic expansion to
  9565. * parenthesis, which should be equivalent
  9566. */
  9567. USTPUTC('(', out);
  9568. }
  9569. goto parsearith_return;
  9570. }
  9571. #endif
  9572. } /* end of readtoken */
  9573. /*
  9574. * Read the next input token.
  9575. * If the token is a word, we set backquotelist to the list of cmds in
  9576. * backquotes. We set quoteflag to true if any part of the word was
  9577. * quoted.
  9578. * If the token is TREDIR, then we set redirnode to a structure containing
  9579. * the redirection.
  9580. * In all cases, the variable startlinno is set to the number of the line
  9581. * on which the token starts.
  9582. *
  9583. * [Change comment: here documents and internal procedures]
  9584. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  9585. * word parsing code into a separate routine. In this case, readtoken
  9586. * doesn't need to have any internal procedures, but parseword does.
  9587. * We could also make parseoperator in essence the main routine, and
  9588. * have parseword (readtoken1?) handle both words and redirection.]
  9589. */
  9590. #define NEW_xxreadtoken
  9591. #ifdef NEW_xxreadtoken
  9592. /* singles must be first! */
  9593. static const char xxreadtoken_chars[7] ALIGN1 = {
  9594. '\n', '(', ')', '&', '|', ';', 0
  9595. };
  9596. static const char xxreadtoken_tokens[] ALIGN1 = {
  9597. TNL, TLP, TRP, /* only single occurrence allowed */
  9598. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  9599. TEOF, /* corresponds to trailing nul */
  9600. TAND, TOR, TENDCASE /* if double occurrence */
  9601. };
  9602. #define xxreadtoken_doubles \
  9603. (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
  9604. #define xxreadtoken_singles \
  9605. (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
  9606. static int
  9607. xxreadtoken(void)
  9608. {
  9609. int c;
  9610. if (tokpushback) {
  9611. tokpushback = 0;
  9612. return lasttoken;
  9613. }
  9614. if (needprompt) {
  9615. setprompt(2);
  9616. }
  9617. startlinno = plinno;
  9618. for (;;) { /* until token or start of word found */
  9619. c = pgetc_macro();
  9620. if ((c != ' ') && (c != '\t')
  9621. #if ENABLE_ASH_ALIAS
  9622. && (c != PEOA)
  9623. #endif
  9624. ) {
  9625. if (c == '#') {
  9626. while ((c = pgetc()) != '\n' && c != PEOF);
  9627. pungetc();
  9628. } else if (c == '\\') {
  9629. if (pgetc() != '\n') {
  9630. pungetc();
  9631. goto READTOKEN1;
  9632. }
  9633. startlinno = ++plinno;
  9634. if (doprompt)
  9635. setprompt(2);
  9636. } else {
  9637. const char *p
  9638. = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  9639. if (c != PEOF) {
  9640. if (c == '\n') {
  9641. plinno++;
  9642. needprompt = doprompt;
  9643. }
  9644. p = strchr(xxreadtoken_chars, c);
  9645. if (p == NULL) {
  9646. READTOKEN1:
  9647. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  9648. }
  9649. if (p - xxreadtoken_chars >= xxreadtoken_singles) {
  9650. if (pgetc() == *p) { /* double occurrence? */
  9651. p += xxreadtoken_doubles + 1;
  9652. } else {
  9653. pungetc();
  9654. }
  9655. }
  9656. }
  9657. return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  9658. }
  9659. }
  9660. } /* for */
  9661. }
  9662. #else
  9663. #define RETURN(token) return lasttoken = token
  9664. static int
  9665. xxreadtoken(void)
  9666. {
  9667. int c;
  9668. if (tokpushback) {
  9669. tokpushback = 0;
  9670. return lasttoken;
  9671. }
  9672. if (needprompt) {
  9673. setprompt(2);
  9674. }
  9675. startlinno = plinno;
  9676. for (;;) { /* until token or start of word found */
  9677. c = pgetc_macro();
  9678. switch (c) {
  9679. case ' ': case '\t':
  9680. #if ENABLE_ASH_ALIAS
  9681. case PEOA:
  9682. #endif
  9683. continue;
  9684. case '#':
  9685. while ((c = pgetc()) != '\n' && c != PEOF);
  9686. pungetc();
  9687. continue;
  9688. case '\\':
  9689. if (pgetc() == '\n') {
  9690. startlinno = ++plinno;
  9691. if (doprompt)
  9692. setprompt(2);
  9693. continue;
  9694. }
  9695. pungetc();
  9696. goto breakloop;
  9697. case '\n':
  9698. plinno++;
  9699. needprompt = doprompt;
  9700. RETURN(TNL);
  9701. case PEOF:
  9702. RETURN(TEOF);
  9703. case '&':
  9704. if (pgetc() == '&')
  9705. RETURN(TAND);
  9706. pungetc();
  9707. RETURN(TBACKGND);
  9708. case '|':
  9709. if (pgetc() == '|')
  9710. RETURN(TOR);
  9711. pungetc();
  9712. RETURN(TPIPE);
  9713. case ';':
  9714. if (pgetc() == ';')
  9715. RETURN(TENDCASE);
  9716. pungetc();
  9717. RETURN(TSEMI);
  9718. case '(':
  9719. RETURN(TLP);
  9720. case ')':
  9721. RETURN(TRP);
  9722. default:
  9723. goto breakloop;
  9724. }
  9725. }
  9726. breakloop:
  9727. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  9728. #undef RETURN
  9729. }
  9730. #endif /* NEW_xxreadtoken */
  9731. static int
  9732. readtoken(void)
  9733. {
  9734. int t;
  9735. #if DEBUG
  9736. smallint alreadyseen = tokpushback;
  9737. #endif
  9738. #if ENABLE_ASH_ALIAS
  9739. top:
  9740. #endif
  9741. t = xxreadtoken();
  9742. /*
  9743. * eat newlines
  9744. */
  9745. if (checkkwd & CHKNL) {
  9746. while (t == TNL) {
  9747. parseheredoc();
  9748. t = xxreadtoken();
  9749. }
  9750. }
  9751. if (t != TWORD || quoteflag) {
  9752. goto out;
  9753. }
  9754. /*
  9755. * check for keywords
  9756. */
  9757. if (checkkwd & CHKKWD) {
  9758. const char *const *pp;
  9759. pp = findkwd(wordtext);
  9760. if (pp) {
  9761. lasttoken = t = pp - tokname_array;
  9762. TRACE(("keyword %s recognized\n", tokname(t)));
  9763. goto out;
  9764. }
  9765. }
  9766. if (checkkwd & CHKALIAS) {
  9767. #if ENABLE_ASH_ALIAS
  9768. struct alias *ap;
  9769. ap = lookupalias(wordtext, 1);
  9770. if (ap != NULL) {
  9771. if (*ap->val) {
  9772. pushstring(ap->val, ap);
  9773. }
  9774. goto top;
  9775. }
  9776. #endif
  9777. }
  9778. out:
  9779. checkkwd = 0;
  9780. #if DEBUG
  9781. if (!alreadyseen)
  9782. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  9783. else
  9784. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  9785. #endif
  9786. return t;
  9787. }
  9788. static char
  9789. peektoken(void)
  9790. {
  9791. int t;
  9792. t = readtoken();
  9793. tokpushback = 1;
  9794. return tokname_array[t][0];
  9795. }
  9796. /*
  9797. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  9798. * valid parse tree indicating a blank line.)
  9799. */
  9800. static union node *
  9801. parsecmd(int interact)
  9802. {
  9803. int t;
  9804. tokpushback = 0;
  9805. doprompt = interact;
  9806. if (doprompt)
  9807. setprompt(doprompt);
  9808. needprompt = 0;
  9809. t = readtoken();
  9810. if (t == TEOF)
  9811. return NEOF;
  9812. if (t == TNL)
  9813. return NULL;
  9814. tokpushback = 1;
  9815. return list(1);
  9816. }
  9817. /*
  9818. * Input any here documents.
  9819. */
  9820. static void
  9821. parseheredoc(void)
  9822. {
  9823. struct heredoc *here;
  9824. union node *n;
  9825. here = heredoclist;
  9826. heredoclist = 0;
  9827. while (here) {
  9828. if (needprompt) {
  9829. setprompt(2);
  9830. }
  9831. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  9832. here->eofmark, here->striptabs);
  9833. n = stalloc(sizeof(struct narg));
  9834. n->narg.type = NARG;
  9835. n->narg.next = NULL;
  9836. n->narg.text = wordtext;
  9837. n->narg.backquote = backquotelist;
  9838. here->here->nhere.doc = n;
  9839. here = here->next;
  9840. }
  9841. }
  9842. /*
  9843. * called by editline -- any expansions to the prompt should be added here.
  9844. */
  9845. #if ENABLE_ASH_EXPAND_PRMT
  9846. static const char *
  9847. expandstr(const char *ps)
  9848. {
  9849. union node n;
  9850. /* XXX Fix (char *) cast. */
  9851. setinputstring((char *)ps);
  9852. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  9853. popfile();
  9854. n.narg.type = NARG;
  9855. n.narg.next = NULL;
  9856. n.narg.text = wordtext;
  9857. n.narg.backquote = backquotelist;
  9858. expandarg(&n, NULL, 0);
  9859. return stackblock();
  9860. }
  9861. #endif
  9862. /*
  9863. * Execute a command or commands contained in a string.
  9864. */
  9865. static int
  9866. evalstring(char *s, int mask)
  9867. {
  9868. union node *n;
  9869. struct stackmark smark;
  9870. int skip;
  9871. setinputstring(s);
  9872. setstackmark(&smark);
  9873. skip = 0;
  9874. while ((n = parsecmd(0)) != NEOF) {
  9875. evaltree(n, 0);
  9876. popstackmark(&smark);
  9877. skip = evalskip;
  9878. if (skip)
  9879. break;
  9880. }
  9881. popfile();
  9882. skip &= mask;
  9883. evalskip = skip;
  9884. return skip;
  9885. }
  9886. /*
  9887. * The eval command.
  9888. */
  9889. static int
  9890. evalcmd(int argc, char **argv)
  9891. {
  9892. char *p;
  9893. char *concat;
  9894. char **ap;
  9895. if (argc > 1) {
  9896. p = argv[1];
  9897. if (argc > 2) {
  9898. STARTSTACKSTR(concat);
  9899. ap = argv + 2;
  9900. for (;;) {
  9901. concat = stack_putstr(p, concat);
  9902. p = *ap++;
  9903. if (p == NULL)
  9904. break;
  9905. STPUTC(' ', concat);
  9906. }
  9907. STPUTC('\0', concat);
  9908. p = grabstackstr(concat);
  9909. }
  9910. evalstring(p, ~SKIPEVAL);
  9911. }
  9912. return exitstatus;
  9913. }
  9914. /*
  9915. * Read and execute commands. "Top" is nonzero for the top level command
  9916. * loop; it turns on prompting if the shell is interactive.
  9917. */
  9918. static int
  9919. cmdloop(int top)
  9920. {
  9921. union node *n;
  9922. struct stackmark smark;
  9923. int inter;
  9924. int numeof = 0;
  9925. TRACE(("cmdloop(%d) called\n", top));
  9926. for (;;) {
  9927. int skip;
  9928. setstackmark(&smark);
  9929. #if JOBS
  9930. if (jobctl)
  9931. showjobs(stderr, SHOW_CHANGED);
  9932. #endif
  9933. inter = 0;
  9934. if (iflag && top) {
  9935. inter++;
  9936. #if ENABLE_ASH_MAIL
  9937. chkmail();
  9938. #endif
  9939. }
  9940. n = parsecmd(inter);
  9941. /* showtree(n); DEBUG */
  9942. if (n == NEOF) {
  9943. if (!top || numeof >= 50)
  9944. break;
  9945. if (!stoppedjobs()) {
  9946. if (!Iflag)
  9947. break;
  9948. out2str("\nUse \"exit\" to leave shell.\n");
  9949. }
  9950. numeof++;
  9951. } else if (nflag == 0) {
  9952. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  9953. job_warning >>= 1;
  9954. numeof = 0;
  9955. evaltree(n, 0);
  9956. }
  9957. popstackmark(&smark);
  9958. skip = evalskip;
  9959. if (skip) {
  9960. evalskip = 0;
  9961. return skip & SKIPEVAL;
  9962. }
  9963. }
  9964. return 0;
  9965. }
  9966. /*
  9967. * Take commands from a file. To be compatible we should do a path
  9968. * search for the file, which is necessary to find sub-commands.
  9969. */
  9970. static char *
  9971. find_dot_file(char *name)
  9972. {
  9973. char *fullname;
  9974. const char *path = pathval();
  9975. struct stat statb;
  9976. /* don't try this for absolute or relative paths */
  9977. if (strchr(name, '/'))
  9978. return name;
  9979. while ((fullname = padvance(&path, name)) != NULL) {
  9980. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  9981. /*
  9982. * Don't bother freeing here, since it will
  9983. * be freed by the caller.
  9984. */
  9985. return fullname;
  9986. }
  9987. stunalloc(fullname);
  9988. }
  9989. /* not found in the PATH */
  9990. ash_msg_and_raise_error("%s: not found", name);
  9991. /* NOTREACHED */
  9992. }
  9993. static int
  9994. dotcmd(int argc, char **argv)
  9995. {
  9996. struct strlist *sp;
  9997. volatile struct shparam saveparam;
  9998. int status = 0;
  9999. for (sp = cmdenviron; sp; sp = sp->next)
  10000. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  10001. if (argc >= 2) { /* That's what SVR2 does */
  10002. char *fullname;
  10003. fullname = find_dot_file(argv[1]);
  10004. if (argc > 2) {
  10005. saveparam = shellparam;
  10006. shellparam.malloc = 0;
  10007. shellparam.nparam = argc - 2;
  10008. shellparam.p = argv + 2;
  10009. };
  10010. setinputfile(fullname, INPUT_PUSH_FILE);
  10011. commandname = fullname;
  10012. cmdloop(0);
  10013. popfile();
  10014. if (argc > 2) {
  10015. freeparam(&shellparam);
  10016. shellparam = saveparam;
  10017. };
  10018. status = exitstatus;
  10019. }
  10020. return status;
  10021. }
  10022. static int
  10023. exitcmd(int argc, char **argv)
  10024. {
  10025. if (stoppedjobs())
  10026. return 0;
  10027. if (argc > 1)
  10028. exitstatus = number(argv[1]);
  10029. raise_exception(EXEXIT);
  10030. /* NOTREACHED */
  10031. }
  10032. #if ENABLE_ASH_BUILTIN_ECHO
  10033. static int
  10034. echocmd(int argc, char **argv)
  10035. {
  10036. return bb_echo(argv);
  10037. }
  10038. #endif
  10039. #if ENABLE_ASH_BUILTIN_TEST
  10040. static int
  10041. testcmd(int argc, char **argv)
  10042. {
  10043. return test_main(argc, argv);
  10044. }
  10045. #endif
  10046. /*
  10047. * Read a file containing shell functions.
  10048. */
  10049. static void
  10050. readcmdfile(char *name)
  10051. {
  10052. setinputfile(name, INPUT_PUSH_FILE);
  10053. cmdloop(0);
  10054. popfile();
  10055. }
  10056. /* ============ find_command inplementation */
  10057. /*
  10058. * Resolve a command name. If you change this routine, you may have to
  10059. * change the shellexec routine as well.
  10060. */
  10061. static void
  10062. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  10063. {
  10064. struct tblentry *cmdp;
  10065. int idx;
  10066. int prev;
  10067. char *fullname;
  10068. struct stat statb;
  10069. int e;
  10070. int updatetbl;
  10071. struct builtincmd *bcmd;
  10072. /* If name contains a slash, don't use PATH or hash table */
  10073. if (strchr(name, '/') != NULL) {
  10074. entry->u.index = -1;
  10075. if (act & DO_ABS) {
  10076. while (stat(name, &statb) < 0) {
  10077. #ifdef SYSV
  10078. if (errno == EINTR)
  10079. continue;
  10080. #endif
  10081. entry->cmdtype = CMDUNKNOWN;
  10082. return;
  10083. }
  10084. }
  10085. entry->cmdtype = CMDNORMAL;
  10086. return;
  10087. }
  10088. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  10089. updatetbl = (path == pathval());
  10090. if (!updatetbl) {
  10091. act |= DO_ALTPATH;
  10092. if (strstr(path, "%builtin") != NULL)
  10093. act |= DO_ALTBLTIN;
  10094. }
  10095. /* If name is in the table, check answer will be ok */
  10096. cmdp = cmdlookup(name, 0);
  10097. if (cmdp != NULL) {
  10098. int bit;
  10099. switch (cmdp->cmdtype) {
  10100. default:
  10101. #if DEBUG
  10102. abort();
  10103. #endif
  10104. case CMDNORMAL:
  10105. bit = DO_ALTPATH;
  10106. break;
  10107. case CMDFUNCTION:
  10108. bit = DO_NOFUNC;
  10109. break;
  10110. case CMDBUILTIN:
  10111. bit = DO_ALTBLTIN;
  10112. break;
  10113. }
  10114. if (act & bit) {
  10115. updatetbl = 0;
  10116. cmdp = NULL;
  10117. } else if (cmdp->rehash == 0)
  10118. /* if not invalidated by cd, we're done */
  10119. goto success;
  10120. }
  10121. /* If %builtin not in path, check for builtin next */
  10122. bcmd = find_builtin(name);
  10123. if (bcmd) {
  10124. if (IS_BUILTIN_REGULAR(bcmd))
  10125. goto builtin_success;
  10126. if (act & DO_ALTPATH) {
  10127. if (!(act & DO_ALTBLTIN))
  10128. goto builtin_success;
  10129. } else if (builtinloc <= 0) {
  10130. goto builtin_success;
  10131. }
  10132. }
  10133. #if ENABLE_FEATURE_SH_STANDALONE
  10134. if (find_applet_by_name(name)) {
  10135. entry->cmdtype = CMDNORMAL;
  10136. entry->u.index = -1;
  10137. return;
  10138. }
  10139. #endif
  10140. /* We have to search path. */
  10141. prev = -1; /* where to start */
  10142. if (cmdp && cmdp->rehash) { /* doing a rehash */
  10143. if (cmdp->cmdtype == CMDBUILTIN)
  10144. prev = builtinloc;
  10145. else
  10146. prev = cmdp->param.index;
  10147. }
  10148. e = ENOENT;
  10149. idx = -1;
  10150. loop:
  10151. while ((fullname = padvance(&path, name)) != NULL) {
  10152. stunalloc(fullname);
  10153. /* NB: code below will still use fullname
  10154. * despite it being "unallocated" */
  10155. idx++;
  10156. if (pathopt) {
  10157. if (prefix(pathopt, "builtin")) {
  10158. if (bcmd)
  10159. goto builtin_success;
  10160. continue;
  10161. } else if (!(act & DO_NOFUNC)
  10162. && prefix(pathopt, "func")) {
  10163. /* handled below */
  10164. } else {
  10165. /* ignore unimplemented options */
  10166. continue;
  10167. }
  10168. }
  10169. /* if rehash, don't redo absolute path names */
  10170. if (fullname[0] == '/' && idx <= prev) {
  10171. if (idx < prev)
  10172. continue;
  10173. TRACE(("searchexec \"%s\": no change\n", name));
  10174. goto success;
  10175. }
  10176. while (stat(fullname, &statb) < 0) {
  10177. #ifdef SYSV
  10178. if (errno == EINTR)
  10179. continue;
  10180. #endif
  10181. if (errno != ENOENT && errno != ENOTDIR)
  10182. e = errno;
  10183. goto loop;
  10184. }
  10185. e = EACCES; /* if we fail, this will be the error */
  10186. if (!S_ISREG(statb.st_mode))
  10187. continue;
  10188. if (pathopt) { /* this is a %func directory */
  10189. stalloc(strlen(fullname) + 1);
  10190. /* NB: stalloc will return space pointed by fullname
  10191. * (because we don't have any intervening allocations
  10192. * between stunalloc above and this stalloc) */
  10193. readcmdfile(fullname);
  10194. cmdp = cmdlookup(name, 0);
  10195. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  10196. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  10197. stunalloc(fullname);
  10198. goto success;
  10199. }
  10200. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  10201. if (!updatetbl) {
  10202. entry->cmdtype = CMDNORMAL;
  10203. entry->u.index = idx;
  10204. return;
  10205. }
  10206. INT_OFF;
  10207. cmdp = cmdlookup(name, 1);
  10208. cmdp->cmdtype = CMDNORMAL;
  10209. cmdp->param.index = idx;
  10210. INT_ON;
  10211. goto success;
  10212. }
  10213. /* We failed. If there was an entry for this command, delete it */
  10214. if (cmdp && updatetbl)
  10215. delete_cmd_entry();
  10216. if (act & DO_ERR)
  10217. ash_msg("%s: %s", name, errmsg(e, "not found"));
  10218. entry->cmdtype = CMDUNKNOWN;
  10219. return;
  10220. builtin_success:
  10221. if (!updatetbl) {
  10222. entry->cmdtype = CMDBUILTIN;
  10223. entry->u.cmd = bcmd;
  10224. return;
  10225. }
  10226. INT_OFF;
  10227. cmdp = cmdlookup(name, 1);
  10228. cmdp->cmdtype = CMDBUILTIN;
  10229. cmdp->param.cmd = bcmd;
  10230. INT_ON;
  10231. success:
  10232. cmdp->rehash = 0;
  10233. entry->cmdtype = cmdp->cmdtype;
  10234. entry->u = cmdp->param;
  10235. }
  10236. /* ============ trap.c */
  10237. /*
  10238. * The trap builtin.
  10239. */
  10240. static int
  10241. trapcmd(int argc, char **argv)
  10242. {
  10243. char *action;
  10244. char **ap;
  10245. int signo;
  10246. nextopt(nullstr);
  10247. ap = argptr;
  10248. if (!*ap) {
  10249. for (signo = 0; signo < NSIG; signo++) {
  10250. if (trap[signo] != NULL) {
  10251. const char *sn;
  10252. sn = get_signame(signo);
  10253. out1fmt("trap -- %s %s\n",
  10254. single_quote(trap[signo]), sn);
  10255. }
  10256. }
  10257. return 0;
  10258. }
  10259. if (!ap[1])
  10260. action = NULL;
  10261. else
  10262. action = *ap++;
  10263. while (*ap) {
  10264. signo = get_signum(*ap);
  10265. if (signo < 0)
  10266. ash_msg_and_raise_error("%s: bad trap", *ap);
  10267. INT_OFF;
  10268. if (action) {
  10269. if (LONE_DASH(action))
  10270. action = NULL;
  10271. else
  10272. action = ckstrdup(action);
  10273. }
  10274. free(trap[signo]);
  10275. trap[signo] = action;
  10276. if (signo != 0)
  10277. setsignal(signo);
  10278. INT_ON;
  10279. ap++;
  10280. }
  10281. return 0;
  10282. }
  10283. /* ============ Builtins */
  10284. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  10285. /*
  10286. * Lists available builtins
  10287. */
  10288. static int
  10289. helpcmd(int argc, char **argv)
  10290. {
  10291. int col, i;
  10292. out1fmt("\nBuilt-in commands:\n-------------------\n");
  10293. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  10294. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  10295. builtintab[i].name + 1);
  10296. if (col > 60) {
  10297. out1fmt("\n");
  10298. col = 0;
  10299. }
  10300. }
  10301. #if ENABLE_FEATURE_SH_STANDALONE
  10302. for (i = 0; i < NUM_APPLETS; i++) {
  10303. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
  10304. if (col > 60) {
  10305. out1fmt("\n");
  10306. col = 0;
  10307. }
  10308. }
  10309. #endif
  10310. out1fmt("\n\n");
  10311. return EXIT_SUCCESS;
  10312. }
  10313. #endif /* FEATURE_SH_EXTRA_QUIET */
  10314. /*
  10315. * The export and readonly commands.
  10316. */
  10317. static int
  10318. exportcmd(int argc, char **argv)
  10319. {
  10320. struct var *vp;
  10321. char *name;
  10322. const char *p;
  10323. char **aptr;
  10324. int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
  10325. if (nextopt("p") != 'p') {
  10326. aptr = argptr;
  10327. name = *aptr;
  10328. if (name) {
  10329. do {
  10330. p = strchr(name, '=');
  10331. if (p != NULL) {
  10332. p++;
  10333. } else {
  10334. vp = *findvar(hashvar(name), name);
  10335. if (vp) {
  10336. vp->flags |= flag;
  10337. continue;
  10338. }
  10339. }
  10340. setvar(name, p, flag);
  10341. } while ((name = *++aptr) != NULL);
  10342. return 0;
  10343. }
  10344. }
  10345. showvars(argv[0], flag, 0);
  10346. return 0;
  10347. }
  10348. /*
  10349. * Delete a function if it exists.
  10350. */
  10351. static void
  10352. unsetfunc(const char *name)
  10353. {
  10354. struct tblentry *cmdp;
  10355. cmdp = cmdlookup(name, 0);
  10356. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  10357. delete_cmd_entry();
  10358. }
  10359. /*
  10360. * The unset builtin command. We unset the function before we unset the
  10361. * variable to allow a function to be unset when there is a readonly variable
  10362. * with the same name.
  10363. */
  10364. static int
  10365. unsetcmd(int argc, char **argv)
  10366. {
  10367. char **ap;
  10368. int i;
  10369. int flag = 0;
  10370. int ret = 0;
  10371. while ((i = nextopt("vf")) != '\0') {
  10372. flag = i;
  10373. }
  10374. for (ap = argptr; *ap; ap++) {
  10375. if (flag != 'f') {
  10376. i = unsetvar(*ap);
  10377. ret |= i;
  10378. if (!(i & 2))
  10379. continue;
  10380. }
  10381. if (flag != 'v')
  10382. unsetfunc(*ap);
  10383. }
  10384. return ret & 1;
  10385. }
  10386. /* setmode.c */
  10387. #include <sys/times.h>
  10388. static const unsigned char timescmd_str[] ALIGN1 = {
  10389. ' ', offsetof(struct tms, tms_utime),
  10390. '\n', offsetof(struct tms, tms_stime),
  10391. ' ', offsetof(struct tms, tms_cutime),
  10392. '\n', offsetof(struct tms, tms_cstime),
  10393. 0
  10394. };
  10395. static int
  10396. timescmd(int ac, char **av)
  10397. {
  10398. long clk_tck, s, t;
  10399. const unsigned char *p;
  10400. struct tms buf;
  10401. clk_tck = sysconf(_SC_CLK_TCK);
  10402. times(&buf);
  10403. p = timescmd_str;
  10404. do {
  10405. t = *(clock_t *)(((char *) &buf) + p[1]);
  10406. s = t / clk_tck;
  10407. out1fmt("%ldm%ld.%.3lds%c",
  10408. s/60, s%60,
  10409. ((t - s * clk_tck) * 1000) / clk_tck,
  10410. p[0]);
  10411. } while (*(p += 2));
  10412. return 0;
  10413. }
  10414. #if ENABLE_ASH_MATH_SUPPORT
  10415. static arith_t
  10416. dash_arith(const char *s)
  10417. {
  10418. arith_t result;
  10419. int errcode = 0;
  10420. INT_OFF;
  10421. result = arith(s, &errcode);
  10422. if (errcode < 0) {
  10423. if (errcode == -3)
  10424. ash_msg_and_raise_error("exponent less than 0");
  10425. if (errcode == -2)
  10426. ash_msg_and_raise_error("divide by zero");
  10427. if (errcode == -5)
  10428. ash_msg_and_raise_error("expression recursion loop detected");
  10429. raise_error_syntax(s);
  10430. }
  10431. INT_ON;
  10432. return result;
  10433. }
  10434. /*
  10435. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  10436. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  10437. *
  10438. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  10439. */
  10440. static int
  10441. letcmd(int argc, char **argv)
  10442. {
  10443. char **ap;
  10444. arith_t i = 0;
  10445. ap = argv + 1;
  10446. if (!*ap)
  10447. ash_msg_and_raise_error("expression expected");
  10448. for (ap = argv + 1; *ap; ap++) {
  10449. i = dash_arith(*ap);
  10450. }
  10451. return !i;
  10452. }
  10453. #endif /* ASH_MATH_SUPPORT */
  10454. /* ============ miscbltin.c
  10455. *
  10456. * Miscellaneous builtins.
  10457. */
  10458. #undef rflag
  10459. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  10460. typedef enum __rlimit_resource rlim_t;
  10461. #endif
  10462. /*
  10463. * The read builtin. The -e option causes backslashes to escape the
  10464. * following character.
  10465. *
  10466. * This uses unbuffered input, which may be avoidable in some cases.
  10467. */
  10468. static int
  10469. readcmd(int argc, char **argv)
  10470. {
  10471. char **ap;
  10472. int backslash;
  10473. char c;
  10474. int rflag;
  10475. char *prompt;
  10476. const char *ifs;
  10477. char *p;
  10478. int startword;
  10479. int status;
  10480. int i;
  10481. #if ENABLE_ASH_READ_NCHARS
  10482. int n_flag = 0;
  10483. int nchars = 0;
  10484. int silent = 0;
  10485. struct termios tty, old_tty;
  10486. #endif
  10487. #if ENABLE_ASH_READ_TIMEOUT
  10488. fd_set set;
  10489. struct timeval ts;
  10490. ts.tv_sec = ts.tv_usec = 0;
  10491. #endif
  10492. rflag = 0;
  10493. prompt = NULL;
  10494. #if ENABLE_ASH_READ_NCHARS && ENABLE_ASH_READ_TIMEOUT
  10495. while ((i = nextopt("p:rt:n:s")) != '\0')
  10496. #elif ENABLE_ASH_READ_NCHARS
  10497. while ((i = nextopt("p:rn:s")) != '\0')
  10498. #elif ENABLE_ASH_READ_TIMEOUT
  10499. while ((i = nextopt("p:rt:")) != '\0')
  10500. #else
  10501. while ((i = nextopt("p:r")) != '\0')
  10502. #endif
  10503. {
  10504. switch (i) {
  10505. case 'p':
  10506. prompt = optionarg;
  10507. break;
  10508. #if ENABLE_ASH_READ_NCHARS
  10509. case 'n':
  10510. nchars = bb_strtou(optionarg, NULL, 10);
  10511. if (nchars < 0 || errno)
  10512. ash_msg_and_raise_error("invalid count");
  10513. n_flag = nchars; /* just a flag "nchars is nonzero" */
  10514. break;
  10515. case 's':
  10516. silent = 1;
  10517. break;
  10518. #endif
  10519. #if ENABLE_ASH_READ_TIMEOUT
  10520. case 't':
  10521. ts.tv_sec = bb_strtou(optionarg, &p, 10);
  10522. ts.tv_usec = 0;
  10523. /* EINVAL means number is ok, but not terminated by NUL */
  10524. if (*p == '.' && errno == EINVAL) {
  10525. char *p2;
  10526. if (*++p) {
  10527. int scale;
  10528. ts.tv_usec = bb_strtou(p, &p2, 10);
  10529. if (errno)
  10530. ash_msg_and_raise_error("invalid timeout");
  10531. scale = p2 - p;
  10532. /* normalize to usec */
  10533. if (scale > 6)
  10534. ash_msg_and_raise_error("invalid timeout");
  10535. while (scale++ < 6)
  10536. ts.tv_usec *= 10;
  10537. }
  10538. } else if (ts.tv_sec < 0 || errno) {
  10539. ash_msg_and_raise_error("invalid timeout");
  10540. }
  10541. if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
  10542. ash_msg_and_raise_error("invalid timeout");
  10543. }
  10544. break;
  10545. #endif
  10546. case 'r':
  10547. rflag = 1;
  10548. break;
  10549. default:
  10550. break;
  10551. }
  10552. }
  10553. if (prompt && isatty(0)) {
  10554. out2str(prompt);
  10555. }
  10556. ap = argptr;
  10557. if (*ap == NULL)
  10558. ash_msg_and_raise_error("arg count");
  10559. ifs = bltinlookup("IFS");
  10560. if (ifs == NULL)
  10561. ifs = defifs;
  10562. #if ENABLE_ASH_READ_NCHARS
  10563. if (n_flag || silent) {
  10564. if (tcgetattr(0, &tty) != 0) {
  10565. /* Not a tty */
  10566. n_flag = 0;
  10567. silent = 0;
  10568. } else {
  10569. old_tty = tty;
  10570. if (n_flag) {
  10571. tty.c_lflag &= ~ICANON;
  10572. tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
  10573. }
  10574. if (silent) {
  10575. tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
  10576. }
  10577. tcsetattr(0, TCSANOW, &tty);
  10578. }
  10579. }
  10580. #endif
  10581. #if ENABLE_ASH_READ_TIMEOUT
  10582. if (ts.tv_sec || ts.tv_usec) {
  10583. FD_ZERO(&set);
  10584. FD_SET(0, &set);
  10585. /* poll-based wait produces bigger code, using select */
  10586. i = select(1, &set, NULL, NULL, &ts);
  10587. if (!i) { /* timed out! */
  10588. #if ENABLE_ASH_READ_NCHARS
  10589. if (n_flag)
  10590. tcsetattr(0, TCSANOW, &old_tty);
  10591. #endif
  10592. return 1;
  10593. }
  10594. }
  10595. #endif
  10596. status = 0;
  10597. startword = 1;
  10598. backslash = 0;
  10599. STARTSTACKSTR(p);
  10600. do {
  10601. if (read(0, &c, 1) != 1) {
  10602. status = 1;
  10603. break;
  10604. }
  10605. if (c == '\0')
  10606. continue;
  10607. if (backslash) {
  10608. backslash = 0;
  10609. if (c != '\n')
  10610. goto put;
  10611. continue;
  10612. }
  10613. if (!rflag && c == '\\') {
  10614. backslash++;
  10615. continue;
  10616. }
  10617. if (c == '\n')
  10618. break;
  10619. if (startword && *ifs == ' ' && strchr(ifs, c)) {
  10620. continue;
  10621. }
  10622. startword = 0;
  10623. if (ap[1] != NULL && strchr(ifs, c) != NULL) {
  10624. STACKSTRNUL(p);
  10625. setvar(*ap, stackblock(), 0);
  10626. ap++;
  10627. startword = 1;
  10628. STARTSTACKSTR(p);
  10629. } else {
  10630. put:
  10631. STPUTC(c, p);
  10632. }
  10633. }
  10634. /* end of do {} while: */
  10635. #if ENABLE_ASH_READ_NCHARS
  10636. while (!n_flag || --nchars);
  10637. #else
  10638. while (1);
  10639. #endif
  10640. #if ENABLE_ASH_READ_NCHARS
  10641. if (n_flag || silent)
  10642. tcsetattr(0, TCSANOW, &old_tty);
  10643. #endif
  10644. STACKSTRNUL(p);
  10645. /* Remove trailing blanks */
  10646. while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
  10647. *p = '\0';
  10648. setvar(*ap, stackblock(), 0);
  10649. while (*++ap != NULL)
  10650. setvar(*ap, nullstr, 0);
  10651. return status;
  10652. }
  10653. static int
  10654. umaskcmd(int argc, char **argv)
  10655. {
  10656. static const char permuser[3] ALIGN1 = "ugo";
  10657. static const char permmode[3] ALIGN1 = "rwx";
  10658. static const short permmask[] ALIGN2 = {
  10659. S_IRUSR, S_IWUSR, S_IXUSR,
  10660. S_IRGRP, S_IWGRP, S_IXGRP,
  10661. S_IROTH, S_IWOTH, S_IXOTH
  10662. };
  10663. char *ap;
  10664. mode_t mask;
  10665. int i;
  10666. int symbolic_mode = 0;
  10667. while (nextopt("S") != '\0') {
  10668. symbolic_mode = 1;
  10669. }
  10670. INT_OFF;
  10671. mask = umask(0);
  10672. umask(mask);
  10673. INT_ON;
  10674. ap = *argptr;
  10675. if (ap == NULL) {
  10676. if (symbolic_mode) {
  10677. char buf[18];
  10678. char *p = buf;
  10679. for (i = 0; i < 3; i++) {
  10680. int j;
  10681. *p++ = permuser[i];
  10682. *p++ = '=';
  10683. for (j = 0; j < 3; j++) {
  10684. if ((mask & permmask[3 * i + j]) == 0) {
  10685. *p++ = permmode[j];
  10686. }
  10687. }
  10688. *p++ = ',';
  10689. }
  10690. *--p = 0;
  10691. puts(buf);
  10692. } else {
  10693. out1fmt("%.4o\n", mask);
  10694. }
  10695. } else {
  10696. if (isdigit((unsigned char) *ap)) {
  10697. mask = 0;
  10698. do {
  10699. if (*ap >= '8' || *ap < '0')
  10700. ash_msg_and_raise_error(illnum, argv[1]);
  10701. mask = (mask << 3) + (*ap - '0');
  10702. } while (*++ap != '\0');
  10703. umask(mask);
  10704. } else {
  10705. mask = ~mask & 0777;
  10706. if (!bb_parse_mode(ap, &mask)) {
  10707. ash_msg_and_raise_error("illegal mode: %s", ap);
  10708. }
  10709. umask(~mask & 0777);
  10710. }
  10711. }
  10712. return 0;
  10713. }
  10714. /*
  10715. * ulimit builtin
  10716. *
  10717. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  10718. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  10719. * ash by J.T. Conklin.
  10720. *
  10721. * Public domain.
  10722. */
  10723. struct limits {
  10724. uint8_t cmd; /* RLIMIT_xxx fit into it */
  10725. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  10726. char option;
  10727. };
  10728. static const struct limits limits_tbl[] = {
  10729. #ifdef RLIMIT_CPU
  10730. { RLIMIT_CPU, 0, 't' },
  10731. #endif
  10732. #ifdef RLIMIT_FSIZE
  10733. { RLIMIT_FSIZE, 9, 'f' },
  10734. #endif
  10735. #ifdef RLIMIT_DATA
  10736. { RLIMIT_DATA, 10, 'd' },
  10737. #endif
  10738. #ifdef RLIMIT_STACK
  10739. { RLIMIT_STACK, 10, 's' },
  10740. #endif
  10741. #ifdef RLIMIT_CORE
  10742. { RLIMIT_CORE, 9, 'c' },
  10743. #endif
  10744. #ifdef RLIMIT_RSS
  10745. { RLIMIT_RSS, 10, 'm' },
  10746. #endif
  10747. #ifdef RLIMIT_MEMLOCK
  10748. { RLIMIT_MEMLOCK, 10, 'l' },
  10749. #endif
  10750. #ifdef RLIMIT_NPROC
  10751. { RLIMIT_NPROC, 0, 'p' },
  10752. #endif
  10753. #ifdef RLIMIT_NOFILE
  10754. { RLIMIT_NOFILE, 0, 'n' },
  10755. #endif
  10756. #ifdef RLIMIT_AS
  10757. { RLIMIT_AS, 10, 'v' },
  10758. #endif
  10759. #ifdef RLIMIT_LOCKS
  10760. { RLIMIT_LOCKS, 0, 'w' },
  10761. #endif
  10762. };
  10763. static const char limits_name[] =
  10764. #ifdef RLIMIT_CPU
  10765. "time(seconds)" "\0"
  10766. #endif
  10767. #ifdef RLIMIT_FSIZE
  10768. "file(blocks)" "\0"
  10769. #endif
  10770. #ifdef RLIMIT_DATA
  10771. "data(kb)" "\0"
  10772. #endif
  10773. #ifdef RLIMIT_STACK
  10774. "stack(kb)" "\0"
  10775. #endif
  10776. #ifdef RLIMIT_CORE
  10777. "coredump(blocks)" "\0"
  10778. #endif
  10779. #ifdef RLIMIT_RSS
  10780. "memory(kb)" "\0"
  10781. #endif
  10782. #ifdef RLIMIT_MEMLOCK
  10783. "locked memory(kb)" "\0"
  10784. #endif
  10785. #ifdef RLIMIT_NPROC
  10786. "process" "\0"
  10787. #endif
  10788. #ifdef RLIMIT_NOFILE
  10789. "nofiles" "\0"
  10790. #endif
  10791. #ifdef RLIMIT_AS
  10792. "vmemory(kb)" "\0"
  10793. #endif
  10794. #ifdef RLIMIT_LOCKS
  10795. "locks" "\0"
  10796. #endif
  10797. ;
  10798. enum limtype { SOFT = 0x1, HARD = 0x2 };
  10799. static void
  10800. printlim(enum limtype how, const struct rlimit *limit,
  10801. const struct limits *l)
  10802. {
  10803. rlim_t val;
  10804. val = limit->rlim_max;
  10805. if (how & SOFT)
  10806. val = limit->rlim_cur;
  10807. if (val == RLIM_INFINITY)
  10808. out1fmt("unlimited\n");
  10809. else {
  10810. val >>= l->factor_shift;
  10811. out1fmt("%lld\n", (long long) val);
  10812. }
  10813. }
  10814. static int
  10815. ulimitcmd(int argc, char **argv)
  10816. {
  10817. int c;
  10818. rlim_t val = 0;
  10819. enum limtype how = SOFT | HARD;
  10820. const struct limits *l;
  10821. int set, all = 0;
  10822. int optc, what;
  10823. struct rlimit limit;
  10824. what = 'f';
  10825. while ((optc = nextopt("HSa"
  10826. #ifdef RLIMIT_CPU
  10827. "t"
  10828. #endif
  10829. #ifdef RLIMIT_FSIZE
  10830. "f"
  10831. #endif
  10832. #ifdef RLIMIT_DATA
  10833. "d"
  10834. #endif
  10835. #ifdef RLIMIT_STACK
  10836. "s"
  10837. #endif
  10838. #ifdef RLIMIT_CORE
  10839. "c"
  10840. #endif
  10841. #ifdef RLIMIT_RSS
  10842. "m"
  10843. #endif
  10844. #ifdef RLIMIT_MEMLOCK
  10845. "l"
  10846. #endif
  10847. #ifdef RLIMIT_NPROC
  10848. "p"
  10849. #endif
  10850. #ifdef RLIMIT_NOFILE
  10851. "n"
  10852. #endif
  10853. #ifdef RLIMIT_AS
  10854. "v"
  10855. #endif
  10856. #ifdef RLIMIT_LOCKS
  10857. "w"
  10858. #endif
  10859. )) != '\0')
  10860. switch (optc) {
  10861. case 'H':
  10862. how = HARD;
  10863. break;
  10864. case 'S':
  10865. how = SOFT;
  10866. break;
  10867. case 'a':
  10868. all = 1;
  10869. break;
  10870. default:
  10871. what = optc;
  10872. }
  10873. for (l = limits_tbl; l->option != what; l++)
  10874. continue;
  10875. set = *argptr ? 1 : 0;
  10876. if (set) {
  10877. char *p = *argptr;
  10878. if (all || argptr[1])
  10879. ash_msg_and_raise_error("too many arguments");
  10880. if (strncmp(p, "unlimited\n", 9) == 0)
  10881. val = RLIM_INFINITY;
  10882. else {
  10883. val = (rlim_t) 0;
  10884. while ((c = *p++) >= '0' && c <= '9') {
  10885. val = (val * 10) + (long)(c - '0');
  10886. if (val < (rlim_t) 0)
  10887. break;
  10888. }
  10889. if (c)
  10890. ash_msg_and_raise_error("bad number");
  10891. val <<= l->factor_shift;
  10892. }
  10893. }
  10894. if (all) {
  10895. const char *lname = limits_name;
  10896. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  10897. getrlimit(l->cmd, &limit);
  10898. out1fmt("%-20s ", lname);
  10899. lname += strlen(lname) + 1;
  10900. printlim(how, &limit, l);
  10901. }
  10902. return 0;
  10903. }
  10904. getrlimit(l->cmd, &limit);
  10905. if (set) {
  10906. if (how & HARD)
  10907. limit.rlim_max = val;
  10908. if (how & SOFT)
  10909. limit.rlim_cur = val;
  10910. if (setrlimit(l->cmd, &limit) < 0)
  10911. ash_msg_and_raise_error("error setting limit (%m)");
  10912. } else {
  10913. printlim(how, &limit, l);
  10914. }
  10915. return 0;
  10916. }
  10917. /* ============ Math support */
  10918. #if ENABLE_ASH_MATH_SUPPORT
  10919. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  10920. Permission is hereby granted, free of charge, to any person obtaining
  10921. a copy of this software and associated documentation files (the
  10922. "Software"), to deal in the Software without restriction, including
  10923. without limitation the rights to use, copy, modify, merge, publish,
  10924. distribute, sublicense, and/or sell copies of the Software, and to
  10925. permit persons to whom the Software is furnished to do so, subject to
  10926. the following conditions:
  10927. The above copyright notice and this permission notice shall be
  10928. included in all copies or substantial portions of the Software.
  10929. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  10930. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10931. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  10932. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  10933. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  10934. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  10935. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  10936. */
  10937. /* This is my infix parser/evaluator. It is optimized for size, intended
  10938. * as a replacement for yacc-based parsers. However, it may well be faster
  10939. * than a comparable parser written in yacc. The supported operators are
  10940. * listed in #defines below. Parens, order of operations, and error handling
  10941. * are supported. This code is thread safe. The exact expression format should
  10942. * be that which POSIX specifies for shells. */
  10943. /* The code uses a simple two-stack algorithm. See
  10944. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  10945. * for a detailed explanation of the infix-to-postfix algorithm on which
  10946. * this is based (this code differs in that it applies operators immediately
  10947. * to the stack instead of adding them to a queue to end up with an
  10948. * expression). */
  10949. /* To use the routine, call it with an expression string and error return
  10950. * pointer */
  10951. /*
  10952. * Aug 24, 2001 Manuel Novoa III
  10953. *
  10954. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  10955. *
  10956. * 1) In arith_apply():
  10957. * a) Cached values of *numptr and &(numptr[-1]).
  10958. * b) Removed redundant test for zero denominator.
  10959. *
  10960. * 2) In arith():
  10961. * a) Eliminated redundant code for processing operator tokens by moving
  10962. * to a table-based implementation. Also folded handling of parens
  10963. * into the table.
  10964. * b) Combined all 3 loops which called arith_apply to reduce generated
  10965. * code size at the cost of speed.
  10966. *
  10967. * 3) The following expressions were treated as valid by the original code:
  10968. * 1() , 0! , 1 ( *3 ) .
  10969. * These bugs have been fixed by internally enclosing the expression in
  10970. * parens and then checking that all binary ops and right parens are
  10971. * preceded by a valid expression (NUM_TOKEN).
  10972. *
  10973. * Note: It may be desirable to replace Aaron's test for whitespace with
  10974. * ctype's isspace() if it is used by another busybox applet or if additional
  10975. * whitespace chars should be considered. Look below the "#include"s for a
  10976. * precompiler test.
  10977. */
  10978. /*
  10979. * Aug 26, 2001 Manuel Novoa III
  10980. *
  10981. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  10982. *
  10983. * Merge in Aaron's comments previously posted to the busybox list,
  10984. * modified slightly to take account of my changes to the code.
  10985. *
  10986. */
  10987. /*
  10988. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  10989. *
  10990. * - allow access to variable,
  10991. * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
  10992. * - realize assign syntax (VAR=expr, +=, *= etc)
  10993. * - realize exponentiation (** operator)
  10994. * - realize comma separated - expr, expr
  10995. * - realise ++expr --expr expr++ expr--
  10996. * - realise expr ? expr : expr (but, second expr calculate always)
  10997. * - allow hexadecimal and octal numbers
  10998. * - was restored loses XOR operator
  10999. * - remove one goto label, added three ;-)
  11000. * - protect $((num num)) as true zero expr (Manuel`s error)
  11001. * - always use special isspace(), see comment from bash ;-)
  11002. */
  11003. #define arith_isspace(arithval) \
  11004. (arithval == ' ' || arithval == '\n' || arithval == '\t')
  11005. typedef unsigned char operator;
  11006. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  11007. * precedence, and 3 high bits are an ID unique across operators of that
  11008. * precedence. The ID portion is so that multiple operators can have the
  11009. * same precedence, ensuring that the leftmost one is evaluated first.
  11010. * Consider * and /. */
  11011. #define tok_decl(prec,id) (((id)<<5)|(prec))
  11012. #define PREC(op) ((op) & 0x1F)
  11013. #define TOK_LPAREN tok_decl(0,0)
  11014. #define TOK_COMMA tok_decl(1,0)
  11015. #define TOK_ASSIGN tok_decl(2,0)
  11016. #define TOK_AND_ASSIGN tok_decl(2,1)
  11017. #define TOK_OR_ASSIGN tok_decl(2,2)
  11018. #define TOK_XOR_ASSIGN tok_decl(2,3)
  11019. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  11020. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  11021. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  11022. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  11023. #define TOK_MUL_ASSIGN tok_decl(3,0)
  11024. #define TOK_DIV_ASSIGN tok_decl(3,1)
  11025. #define TOK_REM_ASSIGN tok_decl(3,2)
  11026. /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
  11027. #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
  11028. /* conditional is right associativity too */
  11029. #define TOK_CONDITIONAL tok_decl(4,0)
  11030. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  11031. #define TOK_OR tok_decl(5,0)
  11032. #define TOK_AND tok_decl(6,0)
  11033. #define TOK_BOR tok_decl(7,0)
  11034. #define TOK_BXOR tok_decl(8,0)
  11035. #define TOK_BAND tok_decl(9,0)
  11036. #define TOK_EQ tok_decl(10,0)
  11037. #define TOK_NE tok_decl(10,1)
  11038. #define TOK_LT tok_decl(11,0)
  11039. #define TOK_GT tok_decl(11,1)
  11040. #define TOK_GE tok_decl(11,2)
  11041. #define TOK_LE tok_decl(11,3)
  11042. #define TOK_LSHIFT tok_decl(12,0)
  11043. #define TOK_RSHIFT tok_decl(12,1)
  11044. #define TOK_ADD tok_decl(13,0)
  11045. #define TOK_SUB tok_decl(13,1)
  11046. #define TOK_MUL tok_decl(14,0)
  11047. #define TOK_DIV tok_decl(14,1)
  11048. #define TOK_REM tok_decl(14,2)
  11049. /* exponent is right associativity */
  11050. #define TOK_EXPONENT tok_decl(15,1)
  11051. /* For now unary operators. */
  11052. #define UNARYPREC 16
  11053. #define TOK_BNOT tok_decl(UNARYPREC,0)
  11054. #define TOK_NOT tok_decl(UNARYPREC,1)
  11055. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  11056. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  11057. #define PREC_PRE (UNARYPREC+2)
  11058. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  11059. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  11060. #define PREC_POST (UNARYPREC+3)
  11061. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  11062. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  11063. #define SPEC_PREC (UNARYPREC+4)
  11064. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  11065. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  11066. #define NUMPTR (*numstackptr)
  11067. static int
  11068. tok_have_assign(operator op)
  11069. {
  11070. operator prec = PREC(op);
  11071. convert_prec_is_assing(prec);
  11072. return (prec == PREC(TOK_ASSIGN) ||
  11073. prec == PREC_PRE || prec == PREC_POST);
  11074. }
  11075. static int
  11076. is_right_associativity(operator prec)
  11077. {
  11078. return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
  11079. || prec == PREC(TOK_CONDITIONAL));
  11080. }
  11081. typedef struct ARITCH_VAR_NUM {
  11082. arith_t val;
  11083. arith_t contidional_second_val;
  11084. char contidional_second_val_initialized;
  11085. char *var; /* if NULL then is regular number,
  11086. else is variable name */
  11087. } v_n_t;
  11088. typedef struct CHK_VAR_RECURSIVE_LOOPED {
  11089. const char *var;
  11090. struct CHK_VAR_RECURSIVE_LOOPED *next;
  11091. } chk_var_recursive_looped_t;
  11092. static chk_var_recursive_looped_t *prev_chk_var_recursive;
  11093. static int
  11094. arith_lookup_val(v_n_t *t)
  11095. {
  11096. if (t->var) {
  11097. const char * p = lookupvar(t->var);
  11098. if (p) {
  11099. int errcode;
  11100. /* recursive try as expression */
  11101. chk_var_recursive_looped_t *cur;
  11102. chk_var_recursive_looped_t cur_save;
  11103. for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
  11104. if (strcmp(cur->var, t->var) == 0) {
  11105. /* expression recursion loop detected */
  11106. return -5;
  11107. }
  11108. }
  11109. /* save current lookuped var name */
  11110. cur = prev_chk_var_recursive;
  11111. cur_save.var = t->var;
  11112. cur_save.next = cur;
  11113. prev_chk_var_recursive = &cur_save;
  11114. t->val = arith (p, &errcode);
  11115. /* restore previous ptr after recursiving */
  11116. prev_chk_var_recursive = cur;
  11117. return errcode;
  11118. }
  11119. /* allow undefined var as 0 */
  11120. t->val = 0;
  11121. }
  11122. return 0;
  11123. }
  11124. /* "applying" a token means performing it on the top elements on the integer
  11125. * stack. For a unary operator it will only change the top element, but a
  11126. * binary operator will pop two arguments and push a result */
  11127. static int
  11128. arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
  11129. {
  11130. v_n_t *numptr_m1;
  11131. arith_t numptr_val, rez;
  11132. int ret_arith_lookup_val;
  11133. /* There is no operator that can work without arguments */
  11134. if (NUMPTR == numstack) goto err;
  11135. numptr_m1 = NUMPTR - 1;
  11136. /* check operand is var with noninteger value */
  11137. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11138. if (ret_arith_lookup_val)
  11139. return ret_arith_lookup_val;
  11140. rez = numptr_m1->val;
  11141. if (op == TOK_UMINUS)
  11142. rez *= -1;
  11143. else if (op == TOK_NOT)
  11144. rez = !rez;
  11145. else if (op == TOK_BNOT)
  11146. rez = ~rez;
  11147. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  11148. rez++;
  11149. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  11150. rez--;
  11151. else if (op != TOK_UPLUS) {
  11152. /* Binary operators */
  11153. /* check and binary operators need two arguments */
  11154. if (numptr_m1 == numstack) goto err;
  11155. /* ... and they pop one */
  11156. --NUMPTR;
  11157. numptr_val = rez;
  11158. if (op == TOK_CONDITIONAL) {
  11159. if (! numptr_m1->contidional_second_val_initialized) {
  11160. /* protect $((expr1 ? expr2)) without ": expr" */
  11161. goto err;
  11162. }
  11163. rez = numptr_m1->contidional_second_val;
  11164. } else if (numptr_m1->contidional_second_val_initialized) {
  11165. /* protect $((expr1 : expr2)) without "expr ? " */
  11166. goto err;
  11167. }
  11168. numptr_m1 = NUMPTR - 1;
  11169. if (op != TOK_ASSIGN) {
  11170. /* check operand is var with noninteger value for not '=' */
  11171. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11172. if (ret_arith_lookup_val)
  11173. return ret_arith_lookup_val;
  11174. }
  11175. if (op == TOK_CONDITIONAL) {
  11176. numptr_m1->contidional_second_val = rez;
  11177. }
  11178. rez = numptr_m1->val;
  11179. if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  11180. rez |= numptr_val;
  11181. else if (op == TOK_OR)
  11182. rez = numptr_val || rez;
  11183. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  11184. rez &= numptr_val;
  11185. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  11186. rez ^= numptr_val;
  11187. else if (op == TOK_AND)
  11188. rez = rez && numptr_val;
  11189. else if (op == TOK_EQ)
  11190. rez = (rez == numptr_val);
  11191. else if (op == TOK_NE)
  11192. rez = (rez != numptr_val);
  11193. else if (op == TOK_GE)
  11194. rez = (rez >= numptr_val);
  11195. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  11196. rez >>= numptr_val;
  11197. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  11198. rez <<= numptr_val;
  11199. else if (op == TOK_GT)
  11200. rez = (rez > numptr_val);
  11201. else if (op == TOK_LT)
  11202. rez = (rez < numptr_val);
  11203. else if (op == TOK_LE)
  11204. rez = (rez <= numptr_val);
  11205. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  11206. rez *= numptr_val;
  11207. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  11208. rez += numptr_val;
  11209. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  11210. rez -= numptr_val;
  11211. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  11212. rez = numptr_val;
  11213. else if (op == TOK_CONDITIONAL_SEP) {
  11214. if (numptr_m1 == numstack) {
  11215. /* protect $((expr : expr)) without "expr ? " */
  11216. goto err;
  11217. }
  11218. numptr_m1->contidional_second_val_initialized = op;
  11219. numptr_m1->contidional_second_val = numptr_val;
  11220. } else if (op == TOK_CONDITIONAL) {
  11221. rez = rez ?
  11222. numptr_val : numptr_m1->contidional_second_val;
  11223. } else if (op == TOK_EXPONENT) {
  11224. if (numptr_val < 0)
  11225. return -3; /* exponent less than 0 */
  11226. else {
  11227. arith_t c = 1;
  11228. if (numptr_val)
  11229. while (numptr_val--)
  11230. c *= rez;
  11231. rez = c;
  11232. }
  11233. } else if (numptr_val==0) /* zero divisor check */
  11234. return -2;
  11235. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  11236. rez /= numptr_val;
  11237. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  11238. rez %= numptr_val;
  11239. }
  11240. if (tok_have_assign(op)) {
  11241. char buf[sizeof(arith_t_type)*3 + 2];
  11242. if (numptr_m1->var == NULL) {
  11243. /* Hmm, 1=2 ? */
  11244. goto err;
  11245. }
  11246. /* save to shell variable */
  11247. #if ENABLE_ASH_MATH_SUPPORT_64
  11248. snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
  11249. #else
  11250. snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
  11251. #endif
  11252. setvar(numptr_m1->var, buf, 0);
  11253. /* after saving, make previous value for v++ or v-- */
  11254. if (op == TOK_POST_INC)
  11255. rez--;
  11256. else if (op == TOK_POST_DEC)
  11257. rez++;
  11258. }
  11259. numptr_m1->val = rez;
  11260. /* protect geting var value, is number now */
  11261. numptr_m1->var = NULL;
  11262. return 0;
  11263. err:
  11264. return -1;
  11265. }
  11266. /* longest must be first */
  11267. static const char op_tokens[] ALIGN1 = {
  11268. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  11269. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  11270. '<','<', 0, TOK_LSHIFT,
  11271. '>','>', 0, TOK_RSHIFT,
  11272. '|','|', 0, TOK_OR,
  11273. '&','&', 0, TOK_AND,
  11274. '!','=', 0, TOK_NE,
  11275. '<','=', 0, TOK_LE,
  11276. '>','=', 0, TOK_GE,
  11277. '=','=', 0, TOK_EQ,
  11278. '|','=', 0, TOK_OR_ASSIGN,
  11279. '&','=', 0, TOK_AND_ASSIGN,
  11280. '*','=', 0, TOK_MUL_ASSIGN,
  11281. '/','=', 0, TOK_DIV_ASSIGN,
  11282. '%','=', 0, TOK_REM_ASSIGN,
  11283. '+','=', 0, TOK_PLUS_ASSIGN,
  11284. '-','=', 0, TOK_MINUS_ASSIGN,
  11285. '-','-', 0, TOK_POST_DEC,
  11286. '^','=', 0, TOK_XOR_ASSIGN,
  11287. '+','+', 0, TOK_POST_INC,
  11288. '*','*', 0, TOK_EXPONENT,
  11289. '!', 0, TOK_NOT,
  11290. '<', 0, TOK_LT,
  11291. '>', 0, TOK_GT,
  11292. '=', 0, TOK_ASSIGN,
  11293. '|', 0, TOK_BOR,
  11294. '&', 0, TOK_BAND,
  11295. '*', 0, TOK_MUL,
  11296. '/', 0, TOK_DIV,
  11297. '%', 0, TOK_REM,
  11298. '+', 0, TOK_ADD,
  11299. '-', 0, TOK_SUB,
  11300. '^', 0, TOK_BXOR,
  11301. /* uniq */
  11302. '~', 0, TOK_BNOT,
  11303. ',', 0, TOK_COMMA,
  11304. '?', 0, TOK_CONDITIONAL,
  11305. ':', 0, TOK_CONDITIONAL_SEP,
  11306. ')', 0, TOK_RPAREN,
  11307. '(', 0, TOK_LPAREN,
  11308. 0
  11309. };
  11310. /* ptr to ")" */
  11311. #define endexpression &op_tokens[sizeof(op_tokens)-7]
  11312. static arith_t
  11313. arith(const char *expr, int *perrcode)
  11314. {
  11315. char arithval; /* Current character under analysis */
  11316. operator lasttok, op;
  11317. operator prec;
  11318. const char *p = endexpression;
  11319. int errcode;
  11320. size_t datasizes = strlen(expr) + 2;
  11321. /* Stack of integers */
  11322. /* The proof that there can be no more than strlen(startbuf)/2+1 integers
  11323. * in any given correct or incorrect expression is left as an exercise to
  11324. * the reader. */
  11325. v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
  11326. *numstackptr = numstack;
  11327. /* Stack of operator tokens */
  11328. operator *stack = alloca((datasizes) * sizeof(operator)),
  11329. *stackptr = stack;
  11330. *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
  11331. *perrcode = errcode = 0;
  11332. while (1) {
  11333. arithval = *expr;
  11334. if (arithval == 0) {
  11335. if (p == endexpression) {
  11336. /* Null expression. */
  11337. return 0;
  11338. }
  11339. /* This is only reached after all tokens have been extracted from the
  11340. * input stream. If there are still tokens on the operator stack, they
  11341. * are to be applied in order. At the end, there should be a final
  11342. * result on the integer stack */
  11343. if (expr != endexpression + 1) {
  11344. /* If we haven't done so already, */
  11345. /* append a closing right paren */
  11346. expr = endexpression;
  11347. /* and let the loop process it. */
  11348. continue;
  11349. }
  11350. /* At this point, we're done with the expression. */
  11351. if (numstackptr != numstack+1) {
  11352. /* ... but if there isn't, it's bad */
  11353. err:
  11354. return (*perrcode = -1);
  11355. }
  11356. if (numstack->var) {
  11357. /* expression is $((var)) only, lookup now */
  11358. errcode = arith_lookup_val(numstack);
  11359. }
  11360. ret:
  11361. *perrcode = errcode;
  11362. return numstack->val;
  11363. }
  11364. /* Continue processing the expression. */
  11365. if (arith_isspace(arithval)) {
  11366. /* Skip whitespace */
  11367. goto prologue;
  11368. }
  11369. p = endofname(expr);
  11370. if (p != expr) {
  11371. size_t var_name_size = (p-expr) + 1; /* trailing zero */
  11372. numstackptr->var = alloca(var_name_size);
  11373. safe_strncpy(numstackptr->var, expr, var_name_size);
  11374. expr = p;
  11375. num:
  11376. numstackptr->contidional_second_val_initialized = 0;
  11377. numstackptr++;
  11378. lasttok = TOK_NUM;
  11379. continue;
  11380. }
  11381. if (isdigit(arithval)) {
  11382. numstackptr->var = NULL;
  11383. #if ENABLE_ASH_MATH_SUPPORT_64
  11384. numstackptr->val = strtoll(expr, (char **) &expr, 0);
  11385. #else
  11386. numstackptr->val = strtol(expr, (char **) &expr, 0);
  11387. #endif
  11388. goto num;
  11389. }
  11390. for (p = op_tokens; ; p++) {
  11391. const char *o;
  11392. if (*p == 0) {
  11393. /* strange operator not found */
  11394. goto err;
  11395. }
  11396. for (o = expr; *p && *o == *p; p++)
  11397. o++;
  11398. if (! *p) {
  11399. /* found */
  11400. expr = o - 1;
  11401. break;
  11402. }
  11403. /* skip tail uncompared token */
  11404. while (*p)
  11405. p++;
  11406. /* skip zero delim */
  11407. p++;
  11408. }
  11409. op = p[1];
  11410. /* post grammar: a++ reduce to num */
  11411. if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  11412. lasttok = TOK_NUM;
  11413. /* Plus and minus are binary (not unary) _only_ if the last
  11414. * token was as number, or a right paren (which pretends to be
  11415. * a number, since it evaluates to one). Think about it.
  11416. * It makes sense. */
  11417. if (lasttok != TOK_NUM) {
  11418. switch (op) {
  11419. case TOK_ADD:
  11420. op = TOK_UPLUS;
  11421. break;
  11422. case TOK_SUB:
  11423. op = TOK_UMINUS;
  11424. break;
  11425. case TOK_POST_INC:
  11426. op = TOK_PRE_INC;
  11427. break;
  11428. case TOK_POST_DEC:
  11429. op = TOK_PRE_DEC;
  11430. break;
  11431. }
  11432. }
  11433. /* We don't want a unary operator to cause recursive descent on the
  11434. * stack, because there can be many in a row and it could cause an
  11435. * operator to be evaluated before its argument is pushed onto the
  11436. * integer stack. */
  11437. /* But for binary operators, "apply" everything on the operator
  11438. * stack until we find an operator with a lesser priority than the
  11439. * one we have just extracted. */
  11440. /* Left paren is given the lowest priority so it will never be
  11441. * "applied" in this way.
  11442. * if associativity is right and priority eq, applied also skip
  11443. */
  11444. prec = PREC(op);
  11445. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  11446. /* not left paren or unary */
  11447. if (lasttok != TOK_NUM) {
  11448. /* binary op must be preceded by a num */
  11449. goto err;
  11450. }
  11451. while (stackptr != stack) {
  11452. if (op == TOK_RPAREN) {
  11453. /* The algorithm employed here is simple: while we don't
  11454. * hit an open paren nor the bottom of the stack, pop
  11455. * tokens and apply them */
  11456. if (stackptr[-1] == TOK_LPAREN) {
  11457. --stackptr;
  11458. /* Any operator directly after a */
  11459. lasttok = TOK_NUM;
  11460. /* close paren should consider itself binary */
  11461. goto prologue;
  11462. }
  11463. } else {
  11464. operator prev_prec = PREC(stackptr[-1]);
  11465. convert_prec_is_assing(prec);
  11466. convert_prec_is_assing(prev_prec);
  11467. if (prev_prec < prec)
  11468. break;
  11469. /* check right assoc */
  11470. if (prev_prec == prec && is_right_associativity(prec))
  11471. break;
  11472. }
  11473. errcode = arith_apply(*--stackptr, numstack, &numstackptr);
  11474. if (errcode) goto ret;
  11475. }
  11476. if (op == TOK_RPAREN) {
  11477. goto err;
  11478. }
  11479. }
  11480. /* Push this operator to the stack and remember it. */
  11481. *stackptr++ = lasttok = op;
  11482. prologue:
  11483. ++expr;
  11484. } /* while */
  11485. }
  11486. #endif /* ASH_MATH_SUPPORT */
  11487. /* ============ main() and helpers */
  11488. /*
  11489. * Called to exit the shell.
  11490. */
  11491. static void exitshell(void) ATTRIBUTE_NORETURN;
  11492. static void
  11493. exitshell(void)
  11494. {
  11495. struct jmploc loc;
  11496. char *p;
  11497. int status;
  11498. status = exitstatus;
  11499. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  11500. if (setjmp(loc.loc)) {
  11501. if (exception == EXEXIT)
  11502. /* dash bug: it just does _exit(exitstatus) here
  11503. * but we have to do setjobctl(0) first!
  11504. * (bug is still not fixed in dash-0.5.3 - if you run dash
  11505. * under Midnight Commander, on exit from dash MC is backgrounded) */
  11506. status = exitstatus;
  11507. goto out;
  11508. }
  11509. exception_handler = &loc;
  11510. p = trap[0];
  11511. if (p) {
  11512. trap[0] = NULL;
  11513. evalstring(p, 0);
  11514. }
  11515. flush_stdout_stderr();
  11516. out:
  11517. setjobctl(0);
  11518. _exit(status);
  11519. /* NOTREACHED */
  11520. }
  11521. static void
  11522. init(void)
  11523. {
  11524. /* from input.c: */
  11525. basepf.nextc = basepf.buf = basebuf;
  11526. /* from trap.c: */
  11527. signal(SIGCHLD, SIG_DFL);
  11528. /* from var.c: */
  11529. {
  11530. char **envp;
  11531. char ppid[sizeof(int)*3 + 1];
  11532. const char *p;
  11533. struct stat st1, st2;
  11534. initvar();
  11535. for (envp = environ; envp && *envp; envp++) {
  11536. if (strchr(*envp, '=')) {
  11537. setvareq(*envp, VEXPORT|VTEXTFIXED);
  11538. }
  11539. }
  11540. snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
  11541. setvar("PPID", ppid, 0);
  11542. p = lookupvar("PWD");
  11543. if (p)
  11544. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  11545. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  11546. p = '\0';
  11547. setpwd(p, 0);
  11548. }
  11549. }
  11550. /*
  11551. * Process the shell command line arguments.
  11552. */
  11553. static void
  11554. procargs(int argc, char **argv)
  11555. {
  11556. int i;
  11557. const char *xminusc;
  11558. char **xargv;
  11559. xargv = argv;
  11560. arg0 = xargv[0];
  11561. if (argc > 0)
  11562. xargv++;
  11563. for (i = 0; i < NOPTS; i++)
  11564. optlist[i] = 2;
  11565. argptr = xargv;
  11566. options(1);
  11567. xargv = argptr;
  11568. xminusc = minusc;
  11569. if (*xargv == NULL) {
  11570. if (xminusc)
  11571. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  11572. sflag = 1;
  11573. }
  11574. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  11575. iflag = 1;
  11576. if (mflag == 2)
  11577. mflag = iflag;
  11578. for (i = 0; i < NOPTS; i++)
  11579. if (optlist[i] == 2)
  11580. optlist[i] = 0;
  11581. #if DEBUG == 2
  11582. debug = 1;
  11583. #endif
  11584. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  11585. if (xminusc) {
  11586. minusc = *xargv++;
  11587. if (*xargv)
  11588. goto setarg0;
  11589. } else if (!sflag) {
  11590. setinputfile(*xargv, 0);
  11591. setarg0:
  11592. arg0 = *xargv++;
  11593. commandname = arg0;
  11594. }
  11595. shellparam.p = xargv;
  11596. #if ENABLE_ASH_GETOPTS
  11597. shellparam.optind = 1;
  11598. shellparam.optoff = -1;
  11599. #endif
  11600. /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
  11601. while (*xargv) {
  11602. shellparam.nparam++;
  11603. xargv++;
  11604. }
  11605. optschanged();
  11606. }
  11607. /*
  11608. * Read /etc/profile or .profile.
  11609. */
  11610. static void
  11611. read_profile(const char *name)
  11612. {
  11613. int skip;
  11614. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  11615. return;
  11616. skip = cmdloop(0);
  11617. popfile();
  11618. if (skip)
  11619. exitshell();
  11620. }
  11621. /*
  11622. * This routine is called when an error or an interrupt occurs in an
  11623. * interactive shell and control is returned to the main command loop.
  11624. */
  11625. static void
  11626. reset(void)
  11627. {
  11628. /* from eval.c: */
  11629. evalskip = 0;
  11630. loopnest = 0;
  11631. /* from input.c: */
  11632. parselleft = parsenleft = 0; /* clear input buffer */
  11633. popallfiles();
  11634. /* from parser.c: */
  11635. tokpushback = 0;
  11636. checkkwd = 0;
  11637. /* from redir.c: */
  11638. clearredir(0);
  11639. }
  11640. #if PROFILE
  11641. static short profile_buf[16384];
  11642. extern int etext();
  11643. #endif
  11644. /*
  11645. * Main routine. We initialize things, parse the arguments, execute
  11646. * profiles if we're a login shell, and then call cmdloop to execute
  11647. * commands. The setjmp call sets up the location to jump to when an
  11648. * exception occurs. When an exception occurs the variable "state"
  11649. * is used to figure out how far we had gotten.
  11650. */
  11651. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  11652. int ash_main(int argc, char **argv)
  11653. {
  11654. char *shinit;
  11655. volatile int state;
  11656. struct jmploc jmploc;
  11657. struct stackmark smark;
  11658. #if PROFILE
  11659. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  11660. #endif
  11661. #if ENABLE_FEATURE_EDITING
  11662. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  11663. #endif
  11664. state = 0;
  11665. if (setjmp(jmploc.loc)) {
  11666. int e;
  11667. int s;
  11668. reset();
  11669. e = exception;
  11670. if (e == EXERROR)
  11671. exitstatus = 2;
  11672. s = state;
  11673. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  11674. exitshell();
  11675. if (e == EXINT) {
  11676. outcslow('\n', stderr);
  11677. }
  11678. popstackmark(&smark);
  11679. FORCE_INT_ON; /* enable interrupts */
  11680. if (s == 1)
  11681. goto state1;
  11682. if (s == 2)
  11683. goto state2;
  11684. if (s == 3)
  11685. goto state3;
  11686. goto state4;
  11687. }
  11688. exception_handler = &jmploc;
  11689. #if DEBUG
  11690. opentrace();
  11691. trace_puts("Shell args: ");
  11692. trace_puts_args(argv);
  11693. #endif
  11694. rootpid = getpid();
  11695. #if ENABLE_ASH_RANDOM_SUPPORT
  11696. rseed = rootpid + time(NULL);
  11697. #endif
  11698. init();
  11699. setstackmark(&smark);
  11700. procargs(argc, argv);
  11701. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  11702. if (iflag) {
  11703. const char *hp = lookupvar("HISTFILE");
  11704. if (hp == NULL) {
  11705. hp = lookupvar("HOME");
  11706. if (hp != NULL) {
  11707. char *defhp = concat_path_file(hp, ".ash_history");
  11708. setvar("HISTFILE", defhp, 0);
  11709. free(defhp);
  11710. }
  11711. }
  11712. }
  11713. #endif
  11714. if (argv[0] && argv[0][0] == '-')
  11715. isloginsh = 1;
  11716. if (isloginsh) {
  11717. state = 1;
  11718. read_profile("/etc/profile");
  11719. state1:
  11720. state = 2;
  11721. read_profile(".profile");
  11722. }
  11723. state2:
  11724. state = 3;
  11725. if (
  11726. #ifndef linux
  11727. getuid() == geteuid() && getgid() == getegid() &&
  11728. #endif
  11729. iflag
  11730. ) {
  11731. shinit = lookupvar("ENV");
  11732. if (shinit != NULL && *shinit != '\0') {
  11733. read_profile(shinit);
  11734. }
  11735. }
  11736. state3:
  11737. state = 4;
  11738. if (minusc)
  11739. evalstring(minusc, 0);
  11740. if (sflag || minusc == NULL) {
  11741. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  11742. if ( iflag ) {
  11743. const char *hp = lookupvar("HISTFILE");
  11744. if (hp != NULL)
  11745. line_input_state->hist_file = hp;
  11746. }
  11747. #endif
  11748. state4: /* XXX ??? - why isn't this before the "if" statement */
  11749. cmdloop(1);
  11750. }
  11751. #if PROFILE
  11752. monitor(0);
  11753. #endif
  11754. #ifdef GPROF
  11755. {
  11756. extern void _mcleanup(void);
  11757. _mcleanup();
  11758. }
  11759. #endif
  11760. exitshell();
  11761. /* NOTREACHED */
  11762. }
  11763. #if DEBUG
  11764. const char *applet_name = "debug stuff usage";
  11765. int main(int argc, char **argv)
  11766. {
  11767. return ash_main(argc, argv);
  11768. }
  11769. #endif
  11770. /*-
  11771. * Copyright (c) 1989, 1991, 1993, 1994
  11772. * The Regents of the University of California. All rights reserved.
  11773. *
  11774. * This code is derived from software contributed to Berkeley by
  11775. * Kenneth Almquist.
  11776. *
  11777. * Redistribution and use in source and binary forms, with or without
  11778. * modification, are permitted provided that the following conditions
  11779. * are met:
  11780. * 1. Redistributions of source code must retain the above copyright
  11781. * notice, this list of conditions and the following disclaimer.
  11782. * 2. Redistributions in binary form must reproduce the above copyright
  11783. * notice, this list of conditions and the following disclaimer in the
  11784. * documentation and/or other materials provided with the distribution.
  11785. * 3. Neither the name of the University nor the names of its contributors
  11786. * may be used to endorse or promote products derived from this software
  11787. * without specific prior written permission.
  11788. *
  11789. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  11790. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11791. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  11792. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  11793. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  11794. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  11795. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  11796. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  11797. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  11798. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11799. * SUCH DAMAGE.
  11800. */