ash.c 320 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config ASH
  19. //config: bool "ash (77 kb)"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: The most complete and most pedantically correct shell included with
  24. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  25. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  26. //config: (written by Kenneth Almquist) from NetBSD.
  27. //config:
  28. //config:# ash options
  29. //config:# note: Don't remove !NOMMU part in the next line; it would break
  30. //config:# menuconfig's indenting.
  31. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  32. //config:
  33. //config:config ASH_OPTIMIZE_FOR_SIZE
  34. //config: bool "Optimize for size instead of speed"
  35. //config: default y
  36. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  37. //config:
  38. //config:config ASH_INTERNAL_GLOB
  39. //config: bool "Use internal glob() implementation"
  40. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  41. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  42. //config: help
  43. //config: Do not use glob() function from libc, use internal implementation.
  44. //config: Use this if you are getting "glob.h: No such file or directory"
  45. //config: or similar build errors.
  46. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  47. //config: which would break ash if you select N here.
  48. //config:
  49. //config:config ASH_BASH_COMPAT
  50. //config: bool "bash-compatible extensions"
  51. //config: default y
  52. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  53. //config:
  54. //config:config ASH_BASH_SOURCE_CURDIR
  55. //config: bool "'source' and '.' builtins search current directory after $PATH"
  56. //config: default n # do not encourage non-standard behavior
  57. //config: depends on ASH_BASH_COMPAT
  58. //config: help
  59. //config: This is not compliant with standards. Avoid if possible.
  60. //config:
  61. //config:config ASH_BASH_NOT_FOUND_HOOK
  62. //config: bool "command_not_found_handle hook support"
  63. //config: default y
  64. //config: depends on ASH_BASH_COMPAT
  65. //config: help
  66. //config: Enable support for the 'command_not_found_handle' hook function,
  67. //config: from GNU bash, which allows for alternative command not found
  68. //config: handling.
  69. //config:
  70. //config:config ASH_JOB_CONTROL
  71. //config: bool "Job control"
  72. //config: default y
  73. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  74. //config:
  75. //config:config ASH_ALIAS
  76. //config: bool "Alias support"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config:
  80. //config:config ASH_RANDOM_SUPPORT
  81. //config: bool "Pseudorandom generator and $RANDOM variable"
  82. //config: default y
  83. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  84. //config: help
  85. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  86. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  87. //config: You can reset the generator by using a specified start value.
  88. //config: After "unset RANDOM" the generator will switch off and this
  89. //config: variable will no longer have special treatment.
  90. //config:
  91. //config:config ASH_EXPAND_PRMT
  92. //config: bool "Expand prompt string"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: $PS# may contain volatile content, such as backquote commands.
  97. //config: This option recreates the prompt string from the environment
  98. //config: variable each time it is displayed.
  99. //config:
  100. //config:config ASH_IDLE_TIMEOUT
  101. //config: bool "Idle timeout variable $TMOUT"
  102. //config: default y
  103. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  104. //config: help
  105. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  106. //config:
  107. //config:config ASH_MAIL
  108. //config: bool "Check for new mail in interactive shell"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config: help
  112. //config: Enable "check for new mail" function:
  113. //config: if set, $MAIL file and $MAILPATH list of files
  114. //config: are checked for mtime changes, and "you have mail"
  115. //config: message is printed if change is detected.
  116. //config:
  117. //config:config ASH_ECHO
  118. //config: bool "echo builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_PRINTF
  123. //config: bool "printf builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_TEST
  128. //config: bool "test builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config:
  132. //config:config ASH_HELP
  133. //config: bool "help builtin"
  134. //config: default y
  135. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  136. //config:
  137. //config:config ASH_GETOPTS
  138. //config: bool "getopts builtin"
  139. //config: default y
  140. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "command builtin"
  144. //config: default y
  145. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  146. //config: help
  147. //config: Enable support for the 'command' builtin, which allows
  148. //config: you to run the specified command or builtin,
  149. //config: even when there is a function with the same name.
  150. //config:
  151. //config:endif # ash options
  152. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  153. // APPLET_ODDNAME:name main location suid_type help
  154. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  155. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  156. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  157. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  158. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  159. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  160. /*
  161. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  162. * DEBUG=2 to compile in and turn on debugging.
  163. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  164. * debugging info is written to ./trace, quit signal generates core dump.
  165. */
  166. #define DEBUG 0
  167. /* Tweak debug output verbosity here */
  168. #define DEBUG_TIME 0
  169. #define DEBUG_PID 1
  170. #define DEBUG_SIG 1
  171. #define DEBUG_INTONOFF 0
  172. #define PROFILE 0
  173. #define JOBS ENABLE_ASH_JOB_CONTROL
  174. #include <fnmatch.h>
  175. #include <sys/times.h>
  176. #include <sys/utsname.h> /* for setting $HOSTNAME */
  177. #include "busybox.h" /* for applet_names */
  178. /* So far, all bash compat is controlled by one config option */
  179. /* Separate defines document which part of code implements what */
  180. /* function keyword */
  181. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  182. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  183. /* &>file */
  184. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  185. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  186. /* $'...' */
  187. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  188. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  189. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  191. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  192. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  193. /* BASH_TEST2: [[ EXPR ]]
  194. * Status of [[ support:
  195. * We replace && and || with -a and -o
  196. * TODO:
  197. * singleword+noglob expansion:
  198. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  199. * [[ /bin/n* ]]; echo 0:$?
  200. * -a/-o are not AND/OR ops! (they are just strings)
  201. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  202. * = is glob match operator, not equality operator: STR = GLOB
  203. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  204. * == same as =
  205. * add =~ regex match operator: STR =~ REGEX
  206. */
  207. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  208. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  209. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  210. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  211. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  212. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  213. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  214. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  215. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  216. /* Bionic at least up to version 24 has no glob() */
  217. # undef ENABLE_ASH_INTERNAL_GLOB
  218. # define ENABLE_ASH_INTERNAL_GLOB 1
  219. #endif
  220. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  221. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  222. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  223. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  224. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  225. # error fails to match dirname, subsequently not expanding <pattern> in it.
  226. // Testcase:
  227. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  228. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  229. #endif
  230. #if !ENABLE_ASH_INTERNAL_GLOB
  231. # include <glob.h>
  232. #endif
  233. #include "unicode.h"
  234. #include "shell_common.h"
  235. #if ENABLE_FEATURE_SH_MATH
  236. # include "math.h"
  237. #else
  238. typedef long arith_t;
  239. # define ARITH_FMT "%ld"
  240. #endif
  241. #if ENABLE_ASH_RANDOM_SUPPORT
  242. # include "random.h"
  243. #else
  244. # define CLEAR_RANDOM_T(rnd) ((void)0)
  245. #endif
  246. #include "NUM_APPLETS.h"
  247. #if NUM_APPLETS == 1
  248. /* STANDALONE does not make sense, and won't compile */
  249. # undef CONFIG_FEATURE_SH_STANDALONE
  250. # undef ENABLE_FEATURE_SH_STANDALONE
  251. # undef IF_FEATURE_SH_STANDALONE
  252. # undef IF_NOT_FEATURE_SH_STANDALONE
  253. # define ENABLE_FEATURE_SH_STANDALONE 0
  254. # define IF_FEATURE_SH_STANDALONE(...)
  255. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  256. #endif
  257. #ifndef F_DUPFD_CLOEXEC
  258. # define F_DUPFD_CLOEXEC F_DUPFD
  259. #endif
  260. #ifndef O_CLOEXEC
  261. # define O_CLOEXEC 0
  262. #endif
  263. #ifndef PIPE_BUF
  264. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  265. #endif
  266. #if !BB_MMU
  267. # error "Do not even bother, ash will not run on NOMMU machine"
  268. #endif
  269. /* We use a trick to have more optimized code (fewer pointer reloads):
  270. * ash.c: extern struct globals *const ash_ptr_to_globals;
  271. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  272. * This way, compiler in ash.c knows the pointer can not change.
  273. *
  274. * However, this may break on weird arches or toolchains. In this case,
  275. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  276. * this optimization.
  277. */
  278. #ifndef BB_GLOBAL_CONST
  279. # define BB_GLOBAL_CONST const
  280. #endif
  281. /* ============ Hash table sizes. Configurable. */
  282. #define VTABSIZE 39
  283. #define ATABSIZE 39
  284. #define CMDTABLESIZE 31 /* should be prime */
  285. /* ============ Shell options */
  286. static const char *const optletters_optnames[] = {
  287. "e" "errexit",
  288. "f" "noglob",
  289. "I" "ignoreeof",
  290. "i" "interactive",
  291. "m" "monitor",
  292. "n" "noexec",
  293. "s" "stdin",
  294. "x" "xtrace",
  295. "v" "verbose",
  296. "C" "noclobber",
  297. "a" "allexport",
  298. "b" "notify",
  299. "u" "nounset",
  300. "\0" "vi"
  301. #if BASH_PIPEFAIL
  302. ,"\0" "pipefail"
  303. #endif
  304. #if DEBUG
  305. ,"\0" "nolog"
  306. ,"\0" "debug"
  307. #endif
  308. };
  309. #define optletters(n) optletters_optnames[n][0]
  310. #define optnames(n) (optletters_optnames[n] + 1)
  311. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  312. /* ============ Misc data */
  313. #define msg_illnum "Illegal number: %s"
  314. /*
  315. * We enclose jmp_buf in a structure so that we can declare pointers to
  316. * jump locations. The global variable handler contains the location to
  317. * jump to when an exception occurs, and the global variable exception_type
  318. * contains a code identifying the exception. To implement nested
  319. * exception handlers, the user should save the value of handler on entry
  320. * to an inner scope, set handler to point to a jmploc structure for the
  321. * inner scope, and restore handler on exit from the scope.
  322. */
  323. struct jmploc {
  324. jmp_buf loc;
  325. };
  326. struct globals_misc {
  327. uint8_t exitstatus; /* exit status of last command */
  328. uint8_t back_exitstatus;/* exit status of backquoted command */
  329. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  330. int rootpid; /* pid of main shell */
  331. /* shell level: 0 for the main shell, 1 for its children, and so on */
  332. int shlvl;
  333. #define rootshell (!shlvl)
  334. int errlinno;
  335. char *minusc; /* argument to -c option */
  336. char *curdir; // = nullstr; /* current working directory */
  337. char *physdir; // = nullstr; /* physical working directory */
  338. char *arg0; /* value of $0 */
  339. struct jmploc *exception_handler;
  340. volatile int suppress_int; /* counter */
  341. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  342. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  343. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  344. smallint exception_type; /* kind of exception (0..5) */
  345. /* exceptions */
  346. #define EXINT 0 /* SIGINT received */
  347. #define EXERROR 1 /* a generic error */
  348. #define EXEXIT 4 /* exit the shell */
  349. char nullstr[1]; /* zero length string */
  350. char optlist[NOPTS];
  351. #define eflag optlist[0]
  352. #define fflag optlist[1]
  353. #define Iflag optlist[2]
  354. #define iflag optlist[3]
  355. #define mflag optlist[4]
  356. #define nflag optlist[5]
  357. #define sflag optlist[6]
  358. #define xflag optlist[7]
  359. #define vflag optlist[8]
  360. #define Cflag optlist[9]
  361. #define aflag optlist[10]
  362. #define bflag optlist[11]
  363. #define uflag optlist[12]
  364. #define viflag optlist[13]
  365. #if BASH_PIPEFAIL
  366. # define pipefail optlist[14]
  367. #else
  368. # define pipefail 0
  369. #endif
  370. #if DEBUG
  371. # define nolog optlist[14 + BASH_PIPEFAIL]
  372. # define debug optlist[15 + BASH_PIPEFAIL]
  373. #endif
  374. /* trap handler commands */
  375. /*
  376. * Sigmode records the current value of the signal handlers for the various
  377. * modes. A value of zero means that the current handler is not known.
  378. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  379. */
  380. char sigmode[NSIG - 1];
  381. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  382. #define S_CATCH 2 /* signal is caught */
  383. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  384. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  385. /* indicates specified signal received */
  386. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  387. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  388. char *trap[NSIG];
  389. char **trap_ptr; /* used only by "trap hack" */
  390. /* Rarely referenced stuff */
  391. #if ENABLE_ASH_RANDOM_SUPPORT
  392. random_t random_gen;
  393. #endif
  394. pid_t backgndpid; /* pid of last background process */
  395. };
  396. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  397. #define G_misc (*ash_ptr_to_globals_misc)
  398. #define exitstatus (G_misc.exitstatus )
  399. #define back_exitstatus (G_misc.back_exitstatus )
  400. #define job_warning (G_misc.job_warning)
  401. #define rootpid (G_misc.rootpid )
  402. #define shlvl (G_misc.shlvl )
  403. #define errlinno (G_misc.errlinno )
  404. #define minusc (G_misc.minusc )
  405. #define curdir (G_misc.curdir )
  406. #define physdir (G_misc.physdir )
  407. #define arg0 (G_misc.arg0 )
  408. #define exception_handler (G_misc.exception_handler)
  409. #define exception_type (G_misc.exception_type )
  410. #define suppress_int (G_misc.suppress_int )
  411. #define pending_int (G_misc.pending_int )
  412. #define got_sigchld (G_misc.got_sigchld )
  413. #define pending_sig (G_misc.pending_sig )
  414. #define nullstr (G_misc.nullstr )
  415. #define optlist (G_misc.optlist )
  416. #define sigmode (G_misc.sigmode )
  417. #define gotsig (G_misc.gotsig )
  418. #define may_have_traps (G_misc.may_have_traps )
  419. #define trap (G_misc.trap )
  420. #define trap_ptr (G_misc.trap_ptr )
  421. #define random_gen (G_misc.random_gen )
  422. #define backgndpid (G_misc.backgndpid )
  423. #define INIT_G_misc() do { \
  424. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  425. barrier(); \
  426. curdir = nullstr; \
  427. physdir = nullstr; \
  428. trap_ptr = trap; \
  429. } while (0)
  430. /* ============ DEBUG */
  431. #if DEBUG
  432. static void trace_printf(const char *fmt, ...);
  433. static void trace_vprintf(const char *fmt, va_list va);
  434. # define TRACE(param) trace_printf param
  435. # define TRACEV(param) trace_vprintf param
  436. # define close(fd) do { \
  437. int dfd = (fd); \
  438. if (close(dfd) < 0) \
  439. bb_error_msg("bug on %d: closing %d(0x%x)", \
  440. __LINE__, dfd, dfd); \
  441. } while (0)
  442. #else
  443. # define TRACE(param)
  444. # define TRACEV(param)
  445. #endif
  446. /* ============ Utility functions */
  447. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  448. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  449. static int
  450. isdigit_str9(const char *str)
  451. {
  452. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  453. while (--maxlen && isdigit(*str))
  454. str++;
  455. return (*str == '\0');
  456. }
  457. static const char *
  458. var_end(const char *var)
  459. {
  460. while (*var)
  461. if (*var++ == '=')
  462. break;
  463. return var;
  464. }
  465. /* ============ Interrupts / exceptions */
  466. static void exitshell(void) NORETURN;
  467. /*
  468. * These macros allow the user to suspend the handling of interrupt signals
  469. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  470. * much more efficient and portable. (But hacking the kernel is so much
  471. * more fun than worrying about efficiency and portability. :-))
  472. */
  473. #if DEBUG_INTONOFF
  474. # define INT_OFF do { \
  475. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  476. suppress_int++; \
  477. barrier(); \
  478. } while (0)
  479. #else
  480. # define INT_OFF do { \
  481. suppress_int++; \
  482. barrier(); \
  483. } while (0)
  484. #endif
  485. /*
  486. * Called to raise an exception. Since C doesn't include exceptions, we
  487. * just do a longjmp to the exception handler. The type of exception is
  488. * stored in the global variable "exception_type".
  489. */
  490. static void raise_exception(int) NORETURN;
  491. static void
  492. raise_exception(int e)
  493. {
  494. #if DEBUG
  495. if (exception_handler == NULL)
  496. abort();
  497. #endif
  498. INT_OFF;
  499. exception_type = e;
  500. longjmp(exception_handler->loc, 1);
  501. }
  502. #if DEBUG
  503. #define raise_exception(e) do { \
  504. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  505. raise_exception(e); \
  506. } while (0)
  507. #endif
  508. /*
  509. * Called when a SIGINT is received. (If the user specifies
  510. * that SIGINT is to be trapped or ignored using the trap builtin, then
  511. * this routine is not called.) Suppressint is nonzero when interrupts
  512. * are held using the INT_OFF macro. (The test for iflag is just
  513. * defensive programming.)
  514. */
  515. static void raise_interrupt(void) NORETURN;
  516. static void
  517. raise_interrupt(void)
  518. {
  519. pending_int = 0;
  520. /* Signal is not automatically unmasked after it is raised,
  521. * do it ourself - unmask all signals */
  522. sigprocmask_allsigs(SIG_UNBLOCK);
  523. /* pending_sig = 0; - now done in signal_handler() */
  524. if (!(rootshell && iflag)) {
  525. /* Kill ourself with SIGINT */
  526. signal(SIGINT, SIG_DFL);
  527. raise(SIGINT);
  528. }
  529. /* bash: ^C even on empty command line sets $? */
  530. exitstatus = SIGINT + 128;
  531. raise_exception(EXINT);
  532. /* NOTREACHED */
  533. }
  534. #if DEBUG
  535. #define raise_interrupt() do { \
  536. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  537. raise_interrupt(); \
  538. } while (0)
  539. #endif
  540. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  541. int_on(void)
  542. {
  543. barrier();
  544. if (--suppress_int == 0 && pending_int) {
  545. raise_interrupt();
  546. }
  547. }
  548. #if DEBUG_INTONOFF
  549. # define INT_ON do { \
  550. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  551. int_on(); \
  552. } while (0)
  553. #else
  554. # define INT_ON int_on()
  555. #endif
  556. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  557. force_int_on(void)
  558. {
  559. barrier();
  560. suppress_int = 0;
  561. if (pending_int)
  562. raise_interrupt();
  563. }
  564. #define FORCE_INT_ON force_int_on()
  565. #define SAVE_INT(v) ((v) = suppress_int)
  566. #define RESTORE_INT(v) do { \
  567. barrier(); \
  568. suppress_int = (v); \
  569. if (suppress_int == 0 && pending_int) \
  570. raise_interrupt(); \
  571. } while (0)
  572. /* ============ Stdout/stderr output */
  573. static void
  574. outstr(const char *p, FILE *file)
  575. {
  576. INT_OFF;
  577. fputs(p, file);
  578. INT_ON;
  579. }
  580. static void
  581. flush_stdout_stderr(void)
  582. {
  583. INT_OFF;
  584. fflush_all();
  585. INT_ON;
  586. }
  587. /* Was called outcslow(c,FILE*), but c was always '\n' */
  588. static void
  589. newline_and_flush(FILE *dest)
  590. {
  591. INT_OFF;
  592. putc('\n', dest);
  593. fflush(dest);
  594. INT_ON;
  595. }
  596. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  597. static int
  598. out1fmt(const char *fmt, ...)
  599. {
  600. va_list ap;
  601. int r;
  602. INT_OFF;
  603. va_start(ap, fmt);
  604. r = vprintf(fmt, ap);
  605. va_end(ap);
  606. INT_ON;
  607. return r;
  608. }
  609. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  610. static int
  611. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  612. {
  613. va_list ap;
  614. int ret;
  615. INT_OFF;
  616. va_start(ap, fmt);
  617. ret = vsnprintf(outbuf, length, fmt, ap);
  618. va_end(ap);
  619. INT_ON;
  620. return ret;
  621. }
  622. static void
  623. out1str(const char *p)
  624. {
  625. outstr(p, stdout);
  626. }
  627. static void
  628. out2str(const char *p)
  629. {
  630. outstr(p, stderr);
  631. flush_stdout_stderr();
  632. }
  633. /* ============ Parser structures */
  634. /* control characters in argument strings */
  635. #define CTL_FIRST CTLESC
  636. #define CTLESC ((unsigned char)'\201') /* escape next character */
  637. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  638. #define CTLENDVAR ((unsigned char)'\203')
  639. #define CTLBACKQ ((unsigned char)'\204')
  640. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  641. #define CTLENDARI ((unsigned char)'\207')
  642. #define CTLQUOTEMARK ((unsigned char)'\210')
  643. #define CTL_LAST CTLQUOTEMARK
  644. /* variable substitution byte (follows CTLVAR) */
  645. #define VSTYPE 0x0f /* type of variable substitution */
  646. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  647. /* values of VSTYPE field */
  648. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  649. #define VSMINUS 0x2 /* ${var-text} */
  650. #define VSPLUS 0x3 /* ${var+text} */
  651. #define VSQUESTION 0x4 /* ${var?message} */
  652. #define VSASSIGN 0x5 /* ${var=text} */
  653. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  654. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  655. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  656. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  657. #define VSLENGTH 0xa /* ${#var} */
  658. #if BASH_SUBSTR
  659. #define VSSUBSTR 0xc /* ${var:position:length} */
  660. #endif
  661. #if BASH_PATTERN_SUBST
  662. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  663. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  664. #endif
  665. static const char dolatstr[] ALIGN1 = {
  666. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  667. };
  668. #define DOLATSTRLEN 6
  669. #define NCMD 0
  670. #define NPIPE 1
  671. #define NREDIR 2
  672. #define NBACKGND 3
  673. #define NSUBSHELL 4
  674. #define NAND 5
  675. #define NOR 6
  676. #define NSEMI 7
  677. #define NIF 8
  678. #define NWHILE 9
  679. #define NUNTIL 10
  680. #define NFOR 11
  681. #define NCASE 12
  682. #define NCLIST 13
  683. #define NDEFUN 14
  684. #define NARG 15
  685. #define NTO 16
  686. #if BASH_REDIR_OUTPUT
  687. #define NTO2 17
  688. #endif
  689. #define NCLOBBER 18
  690. #define NFROM 19
  691. #define NFROMTO 20
  692. #define NAPPEND 21
  693. #define NTOFD 22
  694. #define NFROMFD 23
  695. #define NHERE 24
  696. #define NXHERE 25
  697. #define NNOT 26
  698. #define N_NUMBER 27
  699. union node;
  700. struct ncmd {
  701. smallint type; /* Nxxxx */
  702. int linno;
  703. union node *assign;
  704. union node *args;
  705. union node *redirect;
  706. };
  707. struct npipe {
  708. smallint type;
  709. smallint pipe_backgnd;
  710. struct nodelist *cmdlist;
  711. };
  712. struct nredir {
  713. smallint type;
  714. int linno;
  715. union node *n;
  716. union node *redirect;
  717. };
  718. struct nbinary {
  719. smallint type;
  720. union node *ch1;
  721. union node *ch2;
  722. };
  723. struct nif {
  724. smallint type;
  725. union node *test;
  726. union node *ifpart;
  727. union node *elsepart;
  728. };
  729. struct nfor {
  730. smallint type;
  731. int linno;
  732. union node *args;
  733. union node *body;
  734. char *var;
  735. };
  736. struct ncase {
  737. smallint type;
  738. int linno;
  739. union node *expr;
  740. union node *cases;
  741. };
  742. struct nclist {
  743. smallint type;
  744. union node *next;
  745. union node *pattern;
  746. union node *body;
  747. };
  748. struct ndefun {
  749. smallint type;
  750. int linno;
  751. char *text;
  752. union node *body;
  753. };
  754. struct narg {
  755. smallint type;
  756. union node *next;
  757. char *text;
  758. struct nodelist *backquote;
  759. };
  760. /* nfile and ndup layout must match!
  761. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  762. * that it is actually NTO2 (>&file), and change its type.
  763. */
  764. struct nfile {
  765. smallint type;
  766. union node *next;
  767. int fd;
  768. int _unused_dupfd;
  769. union node *fname;
  770. char *expfname;
  771. };
  772. struct ndup {
  773. smallint type;
  774. union node *next;
  775. int fd;
  776. int dupfd;
  777. union node *vname;
  778. char *_unused_expfname;
  779. };
  780. struct nhere {
  781. smallint type;
  782. union node *next;
  783. int fd;
  784. union node *doc;
  785. };
  786. struct nnot {
  787. smallint type;
  788. union node *com;
  789. };
  790. union node {
  791. smallint type;
  792. struct ncmd ncmd;
  793. struct npipe npipe;
  794. struct nredir nredir;
  795. struct nbinary nbinary;
  796. struct nif nif;
  797. struct nfor nfor;
  798. struct ncase ncase;
  799. struct nclist nclist;
  800. struct ndefun ndefun;
  801. struct narg narg;
  802. struct nfile nfile;
  803. struct ndup ndup;
  804. struct nhere nhere;
  805. struct nnot nnot;
  806. };
  807. /*
  808. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  809. * It must be distinct from NULL.
  810. */
  811. #define NODE_EOF ((union node *) -1L)
  812. struct nodelist {
  813. struct nodelist *next;
  814. union node *n;
  815. };
  816. struct funcnode {
  817. int count;
  818. union node n;
  819. };
  820. /*
  821. * Free a parse tree.
  822. */
  823. static void
  824. freefunc(struct funcnode *f)
  825. {
  826. if (f && --f->count < 0)
  827. free(f);
  828. }
  829. /* ============ Debugging output */
  830. #if DEBUG
  831. static FILE *tracefile;
  832. static void
  833. trace_printf(const char *fmt, ...)
  834. {
  835. va_list va;
  836. if (debug != 1)
  837. return;
  838. if (DEBUG_TIME)
  839. fprintf(tracefile, "%u ", (int) time(NULL));
  840. if (DEBUG_PID)
  841. fprintf(tracefile, "[%u] ", (int) getpid());
  842. if (DEBUG_SIG)
  843. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  844. va_start(va, fmt);
  845. vfprintf(tracefile, fmt, va);
  846. va_end(va);
  847. }
  848. static void
  849. trace_vprintf(const char *fmt, va_list va)
  850. {
  851. if (debug != 1)
  852. return;
  853. vfprintf(tracefile, fmt, va);
  854. fprintf(tracefile, "\n");
  855. }
  856. static void
  857. trace_puts(const char *s)
  858. {
  859. if (debug != 1)
  860. return;
  861. fputs(s, tracefile);
  862. }
  863. static void
  864. trace_puts_quoted(char *s)
  865. {
  866. char *p;
  867. char c;
  868. if (debug != 1)
  869. return;
  870. putc('"', tracefile);
  871. for (p = s; *p; p++) {
  872. switch ((unsigned char)*p) {
  873. case '\n': c = 'n'; goto backslash;
  874. case '\t': c = 't'; goto backslash;
  875. case '\r': c = 'r'; goto backslash;
  876. case '\"': c = '\"'; goto backslash;
  877. case '\\': c = '\\'; goto backslash;
  878. case CTLESC: c = 'e'; goto backslash;
  879. case CTLVAR: c = 'v'; goto backslash;
  880. case CTLBACKQ: c = 'q'; goto backslash;
  881. backslash:
  882. putc('\\', tracefile);
  883. putc(c, tracefile);
  884. break;
  885. default:
  886. if (*p >= ' ' && *p <= '~')
  887. putc(*p, tracefile);
  888. else {
  889. putc('\\', tracefile);
  890. putc((*p >> 6) & 03, tracefile);
  891. putc((*p >> 3) & 07, tracefile);
  892. putc(*p & 07, tracefile);
  893. }
  894. break;
  895. }
  896. }
  897. putc('"', tracefile);
  898. }
  899. static void
  900. trace_puts_args(char **ap)
  901. {
  902. if (debug != 1)
  903. return;
  904. if (!*ap)
  905. return;
  906. while (1) {
  907. trace_puts_quoted(*ap);
  908. if (!*++ap) {
  909. putc('\n', tracefile);
  910. break;
  911. }
  912. putc(' ', tracefile);
  913. }
  914. }
  915. static void
  916. opentrace(void)
  917. {
  918. char s[100];
  919. #ifdef O_APPEND
  920. int flags;
  921. #endif
  922. if (debug != 1) {
  923. if (tracefile)
  924. fflush(tracefile);
  925. /* leave open because libedit might be using it */
  926. return;
  927. }
  928. strcpy(s, "./trace");
  929. if (tracefile) {
  930. if (!freopen(s, "a", tracefile)) {
  931. fprintf(stderr, "Can't re-open %s\n", s);
  932. debug = 0;
  933. return;
  934. }
  935. } else {
  936. tracefile = fopen(s, "a");
  937. if (tracefile == NULL) {
  938. fprintf(stderr, "Can't open %s\n", s);
  939. debug = 0;
  940. return;
  941. }
  942. }
  943. #ifdef O_APPEND
  944. flags = fcntl(fileno(tracefile), F_GETFL);
  945. if (flags >= 0)
  946. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  947. #endif
  948. setlinebuf(tracefile);
  949. fputs("\nTracing started.\n", tracefile);
  950. }
  951. static void
  952. indent(int amount, char *pfx, FILE *fp)
  953. {
  954. int i;
  955. for (i = 0; i < amount; i++) {
  956. if (pfx && i == amount - 1)
  957. fputs(pfx, fp);
  958. putc('\t', fp);
  959. }
  960. }
  961. /* little circular references here... */
  962. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  963. static void
  964. sharg(union node *arg, FILE *fp)
  965. {
  966. char *p;
  967. struct nodelist *bqlist;
  968. unsigned char subtype;
  969. if (arg->type != NARG) {
  970. out1fmt("<node type %d>\n", arg->type);
  971. abort();
  972. }
  973. bqlist = arg->narg.backquote;
  974. for (p = arg->narg.text; *p; p++) {
  975. switch ((unsigned char)*p) {
  976. case CTLESC:
  977. p++;
  978. putc(*p, fp);
  979. break;
  980. case CTLVAR:
  981. putc('$', fp);
  982. putc('{', fp);
  983. subtype = *++p;
  984. if (subtype == VSLENGTH)
  985. putc('#', fp);
  986. while (*p != '=') {
  987. putc(*p, fp);
  988. p++;
  989. }
  990. if (subtype & VSNUL)
  991. putc(':', fp);
  992. switch (subtype & VSTYPE) {
  993. case VSNORMAL:
  994. putc('}', fp);
  995. break;
  996. case VSMINUS:
  997. putc('-', fp);
  998. break;
  999. case VSPLUS:
  1000. putc('+', fp);
  1001. break;
  1002. case VSQUESTION:
  1003. putc('?', fp);
  1004. break;
  1005. case VSASSIGN:
  1006. putc('=', fp);
  1007. break;
  1008. case VSTRIMLEFT:
  1009. putc('#', fp);
  1010. break;
  1011. case VSTRIMLEFTMAX:
  1012. putc('#', fp);
  1013. putc('#', fp);
  1014. break;
  1015. case VSTRIMRIGHT:
  1016. putc('%', fp);
  1017. break;
  1018. case VSTRIMRIGHTMAX:
  1019. putc('%', fp);
  1020. putc('%', fp);
  1021. break;
  1022. case VSLENGTH:
  1023. break;
  1024. default:
  1025. out1fmt("<subtype %d>", subtype);
  1026. }
  1027. break;
  1028. case CTLENDVAR:
  1029. putc('}', fp);
  1030. break;
  1031. case CTLBACKQ:
  1032. putc('$', fp);
  1033. putc('(', fp);
  1034. shtree(bqlist->n, -1, NULL, fp);
  1035. putc(')', fp);
  1036. break;
  1037. default:
  1038. putc(*p, fp);
  1039. break;
  1040. }
  1041. }
  1042. }
  1043. static void
  1044. shcmd(union node *cmd, FILE *fp)
  1045. {
  1046. union node *np;
  1047. int first;
  1048. const char *s;
  1049. int dftfd;
  1050. first = 1;
  1051. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1052. if (!first)
  1053. putc(' ', fp);
  1054. sharg(np, fp);
  1055. first = 0;
  1056. }
  1057. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1058. if (!first)
  1059. putc(' ', fp);
  1060. dftfd = 0;
  1061. switch (np->nfile.type) {
  1062. case NTO: s = ">>"+1; dftfd = 1; break;
  1063. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1064. case NAPPEND: s = ">>"; dftfd = 1; break;
  1065. #if BASH_REDIR_OUTPUT
  1066. case NTO2:
  1067. #endif
  1068. case NTOFD: s = ">&"; dftfd = 1; break;
  1069. case NFROM: s = "<"; break;
  1070. case NFROMFD: s = "<&"; break;
  1071. case NFROMTO: s = "<>"; break;
  1072. default: s = "*error*"; break;
  1073. }
  1074. if (np->nfile.fd != dftfd)
  1075. fprintf(fp, "%d", np->nfile.fd);
  1076. fputs(s, fp);
  1077. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1078. fprintf(fp, "%d", np->ndup.dupfd);
  1079. } else {
  1080. sharg(np->nfile.fname, fp);
  1081. }
  1082. first = 0;
  1083. }
  1084. }
  1085. static void
  1086. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1087. {
  1088. struct nodelist *lp;
  1089. const char *s;
  1090. if (n == NULL)
  1091. return;
  1092. indent(ind, pfx, fp);
  1093. if (n == NODE_EOF) {
  1094. fputs("<EOF>", fp);
  1095. return;
  1096. }
  1097. switch (n->type) {
  1098. case NSEMI:
  1099. s = "; ";
  1100. goto binop;
  1101. case NAND:
  1102. s = " && ";
  1103. goto binop;
  1104. case NOR:
  1105. s = " || ";
  1106. binop:
  1107. shtree(n->nbinary.ch1, ind, NULL, fp);
  1108. /* if (ind < 0) */
  1109. fputs(s, fp);
  1110. shtree(n->nbinary.ch2, ind, NULL, fp);
  1111. break;
  1112. case NCMD:
  1113. shcmd(n, fp);
  1114. if (ind >= 0)
  1115. putc('\n', fp);
  1116. break;
  1117. case NPIPE:
  1118. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1119. shtree(lp->n, 0, NULL, fp);
  1120. if (lp->next)
  1121. fputs(" | ", fp);
  1122. }
  1123. if (n->npipe.pipe_backgnd)
  1124. fputs(" &", fp);
  1125. if (ind >= 0)
  1126. putc('\n', fp);
  1127. break;
  1128. default:
  1129. fprintf(fp, "<node type %d>", n->type);
  1130. if (ind >= 0)
  1131. putc('\n', fp);
  1132. break;
  1133. }
  1134. }
  1135. static void
  1136. showtree(union node *n)
  1137. {
  1138. trace_puts("showtree called\n");
  1139. shtree(n, 1, NULL, stderr);
  1140. }
  1141. #endif /* DEBUG */
  1142. /* ============ Parser data */
  1143. /*
  1144. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1145. */
  1146. struct strlist {
  1147. struct strlist *next;
  1148. char *text;
  1149. };
  1150. struct alias;
  1151. struct strpush {
  1152. struct strpush *prev; /* preceding string on stack */
  1153. char *prev_string;
  1154. int prev_left_in_line;
  1155. #if ENABLE_ASH_ALIAS
  1156. struct alias *ap; /* if push was associated with an alias */
  1157. #endif
  1158. char *string; /* remember the string since it may change */
  1159. /* Remember last two characters for pungetc. */
  1160. int lastc[2];
  1161. /* Number of outstanding calls to pungetc. */
  1162. int unget;
  1163. };
  1164. /*
  1165. * The parsefile structure pointed to by the global variable parsefile
  1166. * contains information about the current file being read.
  1167. */
  1168. struct parsefile {
  1169. struct parsefile *prev; /* preceding file on stack */
  1170. int linno; /* current line */
  1171. int pf_fd; /* file descriptor (or -1 if string) */
  1172. int left_in_line; /* number of chars left in this line */
  1173. int left_in_buffer; /* number of chars left in this buffer past the line */
  1174. char *next_to_pgetc; /* next char in buffer */
  1175. char *buf; /* input buffer */
  1176. struct strpush *strpush; /* for pushing strings at this level */
  1177. struct strpush basestrpush; /* so pushing one is fast */
  1178. /* Remember last two characters for pungetc. */
  1179. int lastc[2];
  1180. /* Number of outstanding calls to pungetc. */
  1181. int unget;
  1182. };
  1183. static struct parsefile basepf; /* top level input file */
  1184. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1185. static char *commandname; /* currently executing command */
  1186. /* ============ Message printing */
  1187. static void
  1188. ash_vmsg(const char *msg, va_list ap)
  1189. {
  1190. fprintf(stderr, "%s: ", arg0);
  1191. if (commandname) {
  1192. if (strcmp(arg0, commandname))
  1193. fprintf(stderr, "%s: ", commandname);
  1194. if (!iflag || g_parsefile->pf_fd > 0)
  1195. fprintf(stderr, "line %d: ", errlinno);
  1196. }
  1197. vfprintf(stderr, msg, ap);
  1198. newline_and_flush(stderr);
  1199. }
  1200. /*
  1201. * Exverror is called to raise the error exception. If the second argument
  1202. * is not NULL then error prints an error message using printf style
  1203. * formatting. It then raises the error exception.
  1204. */
  1205. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1206. static void
  1207. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1208. {
  1209. #if DEBUG
  1210. if (msg) {
  1211. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1212. TRACEV((msg, ap));
  1213. } else
  1214. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1215. if (msg)
  1216. #endif
  1217. ash_vmsg(msg, ap);
  1218. flush_stdout_stderr();
  1219. raise_exception(cond);
  1220. /* NOTREACHED */
  1221. }
  1222. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1223. static void
  1224. ash_msg_and_raise_error(const char *msg, ...)
  1225. {
  1226. va_list ap;
  1227. exitstatus = 2;
  1228. va_start(ap, msg);
  1229. ash_vmsg_and_raise(EXERROR, msg, ap);
  1230. /* NOTREACHED */
  1231. va_end(ap);
  1232. }
  1233. /*
  1234. * 'fmt' must be a string literal.
  1235. */
  1236. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1237. static void raise_error_syntax(const char *) NORETURN;
  1238. static void
  1239. raise_error_syntax(const char *msg)
  1240. {
  1241. errlinno = g_parsefile->linno;
  1242. ash_msg_and_raise_error("syntax error: %s", msg);
  1243. /* NOTREACHED */
  1244. }
  1245. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1246. static void
  1247. ash_msg_and_raise(int cond, const char *msg, ...)
  1248. {
  1249. va_list ap;
  1250. va_start(ap, msg);
  1251. ash_vmsg_and_raise(cond, msg, ap);
  1252. /* NOTREACHED */
  1253. va_end(ap);
  1254. }
  1255. /*
  1256. * error/warning routines for external builtins
  1257. */
  1258. static void
  1259. ash_msg(const char *fmt, ...)
  1260. {
  1261. va_list ap;
  1262. va_start(ap, fmt);
  1263. ash_vmsg(fmt, ap);
  1264. va_end(ap);
  1265. }
  1266. /*
  1267. * Return a string describing an error. The returned string may be a
  1268. * pointer to a static buffer that will be overwritten on the next call.
  1269. * Action describes the operation that got the error.
  1270. */
  1271. static const char *
  1272. errmsg(int e, const char *em)
  1273. {
  1274. if (e == ENOENT || e == ENOTDIR) {
  1275. return em;
  1276. }
  1277. return strerror(e);
  1278. }
  1279. /* ============ Memory allocation */
  1280. #if 0
  1281. /* I consider these wrappers nearly useless:
  1282. * ok, they return you to nearest exception handler, but
  1283. * how much memory do you leak in the process, making
  1284. * memory starvation worse?
  1285. */
  1286. static void *
  1287. ckrealloc(void * p, size_t nbytes)
  1288. {
  1289. p = realloc(p, nbytes);
  1290. if (!p)
  1291. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1292. return p;
  1293. }
  1294. static void *
  1295. ckmalloc(size_t nbytes)
  1296. {
  1297. return ckrealloc(NULL, nbytes);
  1298. }
  1299. static void *
  1300. ckzalloc(size_t nbytes)
  1301. {
  1302. return memset(ckmalloc(nbytes), 0, nbytes);
  1303. }
  1304. static char *
  1305. ckstrdup(const char *s)
  1306. {
  1307. char *p = strdup(s);
  1308. if (!p)
  1309. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1310. return p;
  1311. }
  1312. #else
  1313. /* Using bbox equivalents. They exit if out of memory */
  1314. # define ckrealloc xrealloc
  1315. # define ckmalloc xmalloc
  1316. # define ckzalloc xzalloc
  1317. # define ckstrdup xstrdup
  1318. #endif
  1319. /*
  1320. * It appears that grabstackstr() will barf with such alignments
  1321. * because stalloc() will return a string allocated in a new stackblock.
  1322. */
  1323. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1324. enum {
  1325. /* Most machines require the value returned from malloc to be aligned
  1326. * in some way. The following macro will get this right
  1327. * on many machines. */
  1328. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1329. /* Minimum size of a block */
  1330. MINSIZE = SHELL_ALIGN(504),
  1331. };
  1332. struct stack_block {
  1333. struct stack_block *prev;
  1334. char space[MINSIZE];
  1335. };
  1336. struct stackmark {
  1337. struct stack_block *stackp;
  1338. char *stacknxt;
  1339. size_t stacknleft;
  1340. };
  1341. struct globals_memstack {
  1342. struct stack_block *g_stackp; // = &stackbase;
  1343. char *g_stacknxt; // = stackbase.space;
  1344. char *sstrend; // = stackbase.space + MINSIZE;
  1345. size_t g_stacknleft; // = MINSIZE;
  1346. struct stack_block stackbase;
  1347. };
  1348. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1349. #define G_memstack (*ash_ptr_to_globals_memstack)
  1350. #define g_stackp (G_memstack.g_stackp )
  1351. #define g_stacknxt (G_memstack.g_stacknxt )
  1352. #define sstrend (G_memstack.sstrend )
  1353. #define g_stacknleft (G_memstack.g_stacknleft)
  1354. #define stackbase (G_memstack.stackbase )
  1355. #define INIT_G_memstack() do { \
  1356. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1357. barrier(); \
  1358. g_stackp = &stackbase; \
  1359. g_stacknxt = stackbase.space; \
  1360. g_stacknleft = MINSIZE; \
  1361. sstrend = stackbase.space + MINSIZE; \
  1362. } while (0)
  1363. #define stackblock() ((void *)g_stacknxt)
  1364. #define stackblocksize() g_stacknleft
  1365. /*
  1366. * Parse trees for commands are allocated in lifo order, so we use a stack
  1367. * to make this more efficient, and also to avoid all sorts of exception
  1368. * handling code to handle interrupts in the middle of a parse.
  1369. *
  1370. * The size 504 was chosen because the Ultrix malloc handles that size
  1371. * well.
  1372. */
  1373. static void *
  1374. stalloc(size_t nbytes)
  1375. {
  1376. char *p;
  1377. size_t aligned;
  1378. aligned = SHELL_ALIGN(nbytes);
  1379. if (aligned > g_stacknleft) {
  1380. size_t len;
  1381. size_t blocksize;
  1382. struct stack_block *sp;
  1383. blocksize = aligned;
  1384. if (blocksize < MINSIZE)
  1385. blocksize = MINSIZE;
  1386. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1387. if (len < blocksize)
  1388. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1389. INT_OFF;
  1390. sp = ckmalloc(len);
  1391. sp->prev = g_stackp;
  1392. g_stacknxt = sp->space;
  1393. g_stacknleft = blocksize;
  1394. sstrend = g_stacknxt + blocksize;
  1395. g_stackp = sp;
  1396. INT_ON;
  1397. }
  1398. p = g_stacknxt;
  1399. g_stacknxt += aligned;
  1400. g_stacknleft -= aligned;
  1401. return p;
  1402. }
  1403. static void *
  1404. stzalloc(size_t nbytes)
  1405. {
  1406. return memset(stalloc(nbytes), 0, nbytes);
  1407. }
  1408. static void
  1409. stunalloc(void *p)
  1410. {
  1411. #if DEBUG
  1412. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1413. write(STDERR_FILENO, "stunalloc\n", 10);
  1414. abort();
  1415. }
  1416. #endif
  1417. g_stacknleft += g_stacknxt - (char *)p;
  1418. g_stacknxt = p;
  1419. }
  1420. /*
  1421. * Like strdup but works with the ash stack.
  1422. */
  1423. static char *
  1424. sstrdup(const char *p)
  1425. {
  1426. size_t len = strlen(p) + 1;
  1427. return memcpy(stalloc(len), p, len);
  1428. }
  1429. static ALWAYS_INLINE void
  1430. grabstackblock(size_t len)
  1431. {
  1432. stalloc(len);
  1433. }
  1434. static void
  1435. pushstackmark(struct stackmark *mark, size_t len)
  1436. {
  1437. mark->stackp = g_stackp;
  1438. mark->stacknxt = g_stacknxt;
  1439. mark->stacknleft = g_stacknleft;
  1440. grabstackblock(len);
  1441. }
  1442. static void
  1443. setstackmark(struct stackmark *mark)
  1444. {
  1445. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1446. }
  1447. static void
  1448. popstackmark(struct stackmark *mark)
  1449. {
  1450. struct stack_block *sp;
  1451. if (!mark->stackp)
  1452. return;
  1453. INT_OFF;
  1454. while (g_stackp != mark->stackp) {
  1455. sp = g_stackp;
  1456. g_stackp = sp->prev;
  1457. free(sp);
  1458. }
  1459. g_stacknxt = mark->stacknxt;
  1460. g_stacknleft = mark->stacknleft;
  1461. sstrend = mark->stacknxt + mark->stacknleft;
  1462. INT_ON;
  1463. }
  1464. /*
  1465. * When the parser reads in a string, it wants to stick the string on the
  1466. * stack and only adjust the stack pointer when it knows how big the
  1467. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1468. * of space on top of the stack and stackblocklen returns the length of
  1469. * this block. Growstackblock will grow this space by at least one byte,
  1470. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1471. * part of the block that has been used.
  1472. */
  1473. static void
  1474. growstackblock(void)
  1475. {
  1476. size_t newlen;
  1477. newlen = g_stacknleft * 2;
  1478. if (newlen < g_stacknleft)
  1479. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1480. if (newlen < 128)
  1481. newlen += 128;
  1482. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1483. struct stack_block *sp;
  1484. struct stack_block *prevstackp;
  1485. size_t grosslen;
  1486. INT_OFF;
  1487. sp = g_stackp;
  1488. prevstackp = sp->prev;
  1489. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1490. sp = ckrealloc(sp, grosslen);
  1491. sp->prev = prevstackp;
  1492. g_stackp = sp;
  1493. g_stacknxt = sp->space;
  1494. g_stacknleft = newlen;
  1495. sstrend = sp->space + newlen;
  1496. INT_ON;
  1497. } else {
  1498. char *oldspace = g_stacknxt;
  1499. size_t oldlen = g_stacknleft;
  1500. char *p = stalloc(newlen);
  1501. /* free the space we just allocated */
  1502. g_stacknxt = memcpy(p, oldspace, oldlen);
  1503. g_stacknleft += newlen;
  1504. }
  1505. }
  1506. /*
  1507. * The following routines are somewhat easier to use than the above.
  1508. * The user declares a variable of type STACKSTR, which may be declared
  1509. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1510. * the user uses the macro STPUTC to add characters to the string. In
  1511. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1512. * grown as necessary. When the user is done, she can just leave the
  1513. * string there and refer to it using stackblock(). Or she can allocate
  1514. * the space for it using grabstackstr(). If it is necessary to allow
  1515. * someone else to use the stack temporarily and then continue to grow
  1516. * the string, the user should use grabstack to allocate the space, and
  1517. * then call ungrabstr(p) to return to the previous mode of operation.
  1518. *
  1519. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1520. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1521. * is space for at least one character.
  1522. */
  1523. static void *
  1524. growstackstr(void)
  1525. {
  1526. size_t len = stackblocksize();
  1527. growstackblock();
  1528. return (char *)stackblock() + len;
  1529. }
  1530. /*
  1531. * Called from CHECKSTRSPACE.
  1532. */
  1533. static char *
  1534. makestrspace(size_t newlen, char *p)
  1535. {
  1536. size_t len = p - g_stacknxt;
  1537. size_t size;
  1538. for (;;) {
  1539. size_t nleft;
  1540. size = stackblocksize();
  1541. nleft = size - len;
  1542. if (nleft >= newlen)
  1543. break;
  1544. growstackblock();
  1545. }
  1546. return (char *)stackblock() + len;
  1547. }
  1548. static char *
  1549. stack_nputstr(const char *s, size_t n, char *p)
  1550. {
  1551. p = makestrspace(n, p);
  1552. p = (char *)mempcpy(p, s, n);
  1553. return p;
  1554. }
  1555. static char *
  1556. stack_putstr(const char *s, char *p)
  1557. {
  1558. return stack_nputstr(s, strlen(s), p);
  1559. }
  1560. static char *
  1561. _STPUTC(int c, char *p)
  1562. {
  1563. if (p == sstrend)
  1564. p = growstackstr();
  1565. *p++ = c;
  1566. return p;
  1567. }
  1568. #define STARTSTACKSTR(p) ((p) = stackblock())
  1569. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1570. #define CHECKSTRSPACE(n, p) do { \
  1571. char *q = (p); \
  1572. size_t l = (n); \
  1573. size_t m = sstrend - q; \
  1574. if (l > m) \
  1575. (p) = makestrspace(l, q); \
  1576. } while (0)
  1577. #define USTPUTC(c, p) (*(p)++ = (c))
  1578. #define STACKSTRNUL(p) do { \
  1579. if ((p) == sstrend) \
  1580. (p) = growstackstr(); \
  1581. *(p) = '\0'; \
  1582. } while (0)
  1583. #define STUNPUTC(p) (--(p))
  1584. #define STTOPC(p) ((p)[-1])
  1585. #define STADJUST(amount, p) ((p) += (amount))
  1586. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1587. #define ungrabstackstr(s, p) stunalloc(s)
  1588. #define stackstrend() ((void *)sstrend)
  1589. /* ============ String helpers */
  1590. /*
  1591. * prefix -- see if pfx is a prefix of string.
  1592. */
  1593. static char *
  1594. prefix(const char *string, const char *pfx)
  1595. {
  1596. while (*pfx) {
  1597. if (*pfx++ != *string++)
  1598. return NULL;
  1599. }
  1600. return (char *) string;
  1601. }
  1602. /*
  1603. * Check for a valid number. This should be elsewhere.
  1604. */
  1605. static int
  1606. is_number(const char *p)
  1607. {
  1608. do {
  1609. if (!isdigit(*p))
  1610. return 0;
  1611. } while (*++p != '\0');
  1612. return 1;
  1613. }
  1614. /*
  1615. * Convert a string of digits to an integer, printing an error message on
  1616. * failure.
  1617. */
  1618. static int
  1619. number(const char *s)
  1620. {
  1621. if (!is_number(s))
  1622. ash_msg_and_raise_error(msg_illnum, s);
  1623. return atoi(s);
  1624. }
  1625. /*
  1626. * Produce a single quoted string suitable as input to the shell.
  1627. * The return string is allocated on the stack.
  1628. */
  1629. static char *
  1630. single_quote(const char *s)
  1631. {
  1632. char *p;
  1633. STARTSTACKSTR(p);
  1634. do {
  1635. char *q;
  1636. size_t len;
  1637. len = strchrnul(s, '\'') - s;
  1638. q = p = makestrspace(len + 3, p);
  1639. *q++ = '\'';
  1640. q = (char *)mempcpy(q, s, len);
  1641. *q++ = '\'';
  1642. s += len;
  1643. STADJUST(q - p, p);
  1644. if (*s != '\'')
  1645. break;
  1646. len = 0;
  1647. do len++; while (*++s == '\'');
  1648. q = p = makestrspace(len + 3, p);
  1649. *q++ = '"';
  1650. q = (char *)mempcpy(q, s - len, len);
  1651. *q++ = '"';
  1652. STADJUST(q - p, p);
  1653. } while (*s);
  1654. USTPUTC('\0', p);
  1655. return stackblock();
  1656. }
  1657. /*
  1658. * Produce a possibly single quoted string suitable as input to the shell.
  1659. * If quoting was done, the return string is allocated on the stack,
  1660. * otherwise a pointer to the original string is returned.
  1661. */
  1662. static const char *
  1663. maybe_single_quote(const char *s)
  1664. {
  1665. const char *p = s;
  1666. while (*p) {
  1667. /* Assuming ACSII */
  1668. /* quote ctrl_chars space !"#$%&'()* */
  1669. if (*p < '+')
  1670. goto need_quoting;
  1671. /* quote ;<=>? */
  1672. if (*p >= ';' && *p <= '?')
  1673. goto need_quoting;
  1674. /* quote `[\ */
  1675. if (*p == '`')
  1676. goto need_quoting;
  1677. if (*p == '[')
  1678. goto need_quoting;
  1679. if (*p == '\\')
  1680. goto need_quoting;
  1681. /* quote {|}~ DEL and high bytes */
  1682. if (*p > 'z')
  1683. goto need_quoting;
  1684. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1685. /* TODO: maybe avoid quoting % */
  1686. p++;
  1687. }
  1688. return s;
  1689. need_quoting:
  1690. return single_quote(s);
  1691. }
  1692. /* ============ nextopt */
  1693. static char **argptr; /* argument list for builtin commands */
  1694. static char *optionarg; /* set by nextopt (like getopt) */
  1695. static char *optptr; /* used by nextopt */
  1696. /*
  1697. * XXX - should get rid of. Have all builtins use getopt(3).
  1698. * The library getopt must have the BSD extension static variable
  1699. * "optreset", otherwise it can't be used within the shell safely.
  1700. *
  1701. * Standard option processing (a la getopt) for builtin routines.
  1702. * The only argument that is passed to nextopt is the option string;
  1703. * the other arguments are unnecessary. It returns the character,
  1704. * or '\0' on end of input.
  1705. */
  1706. static int
  1707. nextopt(const char *optstring)
  1708. {
  1709. char *p;
  1710. const char *q;
  1711. char c;
  1712. p = optptr;
  1713. if (p == NULL || *p == '\0') {
  1714. /* We ate entire "-param", take next one */
  1715. p = *argptr;
  1716. if (p == NULL)
  1717. return '\0';
  1718. if (*p != '-')
  1719. return '\0';
  1720. if (*++p == '\0') /* just "-" ? */
  1721. return '\0';
  1722. argptr++;
  1723. if (LONE_DASH(p)) /* "--" ? */
  1724. return '\0';
  1725. /* p => next "-param" */
  1726. }
  1727. /* p => some option char in the middle of a "-param" */
  1728. c = *p++;
  1729. for (q = optstring; *q != c;) {
  1730. if (*q == '\0')
  1731. ash_msg_and_raise_error("illegal option -%c", c);
  1732. if (*++q == ':')
  1733. q++;
  1734. }
  1735. if (*++q == ':') {
  1736. if (*p == '\0') {
  1737. p = *argptr++;
  1738. if (p == NULL)
  1739. ash_msg_and_raise_error("no arg for -%c option", c);
  1740. }
  1741. optionarg = p;
  1742. p = NULL;
  1743. }
  1744. optptr = p;
  1745. return c;
  1746. }
  1747. /* ============ Shell variables */
  1748. struct shparam {
  1749. int nparam; /* # of positional parameters (without $0) */
  1750. #if ENABLE_ASH_GETOPTS
  1751. int optind; /* next parameter to be processed by getopts */
  1752. int optoff; /* used by getopts */
  1753. #endif
  1754. unsigned char malloced; /* if parameter list dynamically allocated */
  1755. char **p; /* parameter list */
  1756. };
  1757. /*
  1758. * Free the list of positional parameters.
  1759. */
  1760. static void
  1761. freeparam(volatile struct shparam *param)
  1762. {
  1763. if (param->malloced) {
  1764. char **ap, **ap1;
  1765. ap = ap1 = param->p;
  1766. while (*ap)
  1767. free(*ap++);
  1768. free(ap1);
  1769. }
  1770. }
  1771. #if ENABLE_ASH_GETOPTS
  1772. static void FAST_FUNC getoptsreset(const char *value);
  1773. #endif
  1774. struct var {
  1775. struct var *next; /* next entry in hash list */
  1776. int flags; /* flags are defined above */
  1777. const char *var_text; /* name=value */
  1778. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1779. /* the variable gets set/unset */
  1780. };
  1781. struct localvar {
  1782. struct localvar *next; /* next local variable in list */
  1783. struct var *vp; /* the variable that was made local */
  1784. int flags; /* saved flags */
  1785. const char *text; /* saved text */
  1786. };
  1787. /* flags */
  1788. #define VEXPORT 0x01 /* variable is exported */
  1789. #define VREADONLY 0x02 /* variable cannot be modified */
  1790. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1791. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1792. #define VSTACK 0x10 /* text is allocated on the stack */
  1793. #define VUNSET 0x20 /* the variable is not set */
  1794. #define VNOFUNC 0x40 /* don't call the callback function */
  1795. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1796. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1797. #if ENABLE_ASH_RANDOM_SUPPORT
  1798. # define VDYNAMIC 0x200 /* dynamic variable */
  1799. #else
  1800. # define VDYNAMIC 0
  1801. #endif
  1802. /* Need to be before varinit_data[] */
  1803. #if ENABLE_LOCALE_SUPPORT
  1804. static void FAST_FUNC
  1805. change_lc_all(const char *value)
  1806. {
  1807. if (value && *value != '\0')
  1808. setlocale(LC_ALL, value);
  1809. }
  1810. static void FAST_FUNC
  1811. change_lc_ctype(const char *value)
  1812. {
  1813. if (value && *value != '\0')
  1814. setlocale(LC_CTYPE, value);
  1815. }
  1816. #endif
  1817. #if ENABLE_ASH_MAIL
  1818. static void chkmail(void);
  1819. static void changemail(const char *var_value) FAST_FUNC;
  1820. #else
  1821. # define chkmail() ((void)0)
  1822. #endif
  1823. static void changepath(const char *) FAST_FUNC;
  1824. #if ENABLE_ASH_RANDOM_SUPPORT
  1825. static void change_random(const char *) FAST_FUNC;
  1826. #endif
  1827. static const struct {
  1828. int flags;
  1829. const char *var_text;
  1830. void (*var_func)(const char *) FAST_FUNC;
  1831. } varinit_data[] = {
  1832. /*
  1833. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1834. * some environment strings may be constant.
  1835. */
  1836. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1837. #if ENABLE_ASH_MAIL
  1838. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1839. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1840. #endif
  1841. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1842. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1843. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1844. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1845. #if ENABLE_ASH_GETOPTS
  1846. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1847. #endif
  1848. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1849. #if ENABLE_ASH_RANDOM_SUPPORT
  1850. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1851. #endif
  1852. #if ENABLE_LOCALE_SUPPORT
  1853. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1854. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1855. #endif
  1856. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1857. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1858. #endif
  1859. };
  1860. struct redirtab;
  1861. struct globals_var {
  1862. struct shparam shellparam; /* $@ current positional parameters */
  1863. struct redirtab *redirlist;
  1864. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1865. struct var *vartab[VTABSIZE];
  1866. struct var varinit[ARRAY_SIZE(varinit_data)];
  1867. int lineno;
  1868. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1869. };
  1870. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1871. #define G_var (*ash_ptr_to_globals_var)
  1872. #define shellparam (G_var.shellparam )
  1873. //#define redirlist (G_var.redirlist )
  1874. #define preverrout_fd (G_var.preverrout_fd)
  1875. #define vartab (G_var.vartab )
  1876. #define varinit (G_var.varinit )
  1877. #define lineno (G_var.lineno )
  1878. #define linenovar (G_var.linenovar )
  1879. #define vifs varinit[0]
  1880. #if ENABLE_ASH_MAIL
  1881. # define vmail (&vifs)[1]
  1882. # define vmpath (&vmail)[1]
  1883. # define vpath (&vmpath)[1]
  1884. #else
  1885. # define vpath (&vifs)[1]
  1886. #endif
  1887. #define vps1 (&vpath)[1]
  1888. #define vps2 (&vps1)[1]
  1889. #define vps4 (&vps2)[1]
  1890. #if ENABLE_ASH_GETOPTS
  1891. # define voptind (&vps4)[1]
  1892. # define vlineno (&voptind)[1]
  1893. # if ENABLE_ASH_RANDOM_SUPPORT
  1894. # define vrandom (&vlineno)[1]
  1895. # endif
  1896. #else
  1897. # define vlineno (&vps4)[1]
  1898. # if ENABLE_ASH_RANDOM_SUPPORT
  1899. # define vrandom (&vlineno)[1]
  1900. # endif
  1901. #endif
  1902. #define INIT_G_var() do { \
  1903. unsigned i; \
  1904. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1905. barrier(); \
  1906. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1907. varinit[i].flags = varinit_data[i].flags; \
  1908. varinit[i].var_text = varinit_data[i].var_text; \
  1909. varinit[i].var_func = varinit_data[i].var_func; \
  1910. } \
  1911. strcpy(linenovar, "LINENO="); \
  1912. vlineno.var_text = linenovar; \
  1913. } while (0)
  1914. /*
  1915. * The following macros access the values of the above variables.
  1916. * They have to skip over the name. They return the null string
  1917. * for unset variables.
  1918. */
  1919. #define ifsval() (vifs.var_text + 4)
  1920. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1921. #if ENABLE_ASH_MAIL
  1922. # define mailval() (vmail.var_text + 5)
  1923. # define mpathval() (vmpath.var_text + 9)
  1924. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1925. #endif
  1926. #define pathval() (vpath.var_text + 5)
  1927. #define ps1val() (vps1.var_text + 4)
  1928. #define ps2val() (vps2.var_text + 4)
  1929. #define ps4val() (vps4.var_text + 4)
  1930. #if ENABLE_ASH_GETOPTS
  1931. # define optindval() (voptind.var_text + 7)
  1932. #endif
  1933. #if ENABLE_ASH_GETOPTS
  1934. static void FAST_FUNC
  1935. getoptsreset(const char *value)
  1936. {
  1937. shellparam.optind = 1;
  1938. if (is_number(value))
  1939. shellparam.optind = number(value) ?: 1;
  1940. shellparam.optoff = -1;
  1941. }
  1942. #endif
  1943. /*
  1944. * Compares two strings up to the first = or '\0'. The first
  1945. * string must be terminated by '='; the second may be terminated by
  1946. * either '=' or '\0'.
  1947. */
  1948. static int
  1949. varcmp(const char *p, const char *q)
  1950. {
  1951. int c, d;
  1952. while ((c = *p) == (d = *q)) {
  1953. if (c == '\0' || c == '=')
  1954. goto out;
  1955. p++;
  1956. q++;
  1957. }
  1958. if (c == '=')
  1959. c = '\0';
  1960. if (d == '=')
  1961. d = '\0';
  1962. out:
  1963. return c - d;
  1964. }
  1965. /*
  1966. * Find the appropriate entry in the hash table from the name.
  1967. */
  1968. static struct var **
  1969. hashvar(const char *p)
  1970. {
  1971. unsigned hashval;
  1972. hashval = ((unsigned char) *p) << 4;
  1973. while (*p && *p != '=')
  1974. hashval += (unsigned char) *p++;
  1975. return &vartab[hashval % VTABSIZE];
  1976. }
  1977. static int
  1978. vpcmp(const void *a, const void *b)
  1979. {
  1980. return varcmp(*(const char **)a, *(const char **)b);
  1981. }
  1982. /*
  1983. * This routine initializes the builtin variables.
  1984. */
  1985. static void
  1986. initvar(void)
  1987. {
  1988. struct var *vp;
  1989. struct var *end;
  1990. struct var **vpp;
  1991. /*
  1992. * PS1 depends on uid
  1993. */
  1994. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1995. vps1.var_text = "PS1=\\w \\$ ";
  1996. #else
  1997. if (!geteuid())
  1998. vps1.var_text = "PS1=# ";
  1999. #endif
  2000. vp = varinit;
  2001. end = vp + ARRAY_SIZE(varinit);
  2002. do {
  2003. vpp = hashvar(vp->var_text);
  2004. vp->next = *vpp;
  2005. *vpp = vp;
  2006. } while (++vp < end);
  2007. }
  2008. static struct var **
  2009. findvar(struct var **vpp, const char *name)
  2010. {
  2011. for (; *vpp; vpp = &(*vpp)->next) {
  2012. if (varcmp((*vpp)->var_text, name) == 0) {
  2013. break;
  2014. }
  2015. }
  2016. return vpp;
  2017. }
  2018. /*
  2019. * Find the value of a variable. Returns NULL if not set.
  2020. */
  2021. static const char* FAST_FUNC
  2022. lookupvar(const char *name)
  2023. {
  2024. struct var *v;
  2025. v = *findvar(hashvar(name), name);
  2026. if (v) {
  2027. #if ENABLE_ASH_RANDOM_SUPPORT
  2028. /*
  2029. * Dynamic variables are implemented roughly the same way they are
  2030. * in bash. Namely, they're "special" so long as they aren't unset.
  2031. * As soon as they're unset, they're no longer dynamic, and dynamic
  2032. * lookup will no longer happen at that point. -- PFM.
  2033. */
  2034. if (v->flags & VDYNAMIC)
  2035. v->var_func(NULL);
  2036. #endif
  2037. if (!(v->flags & VUNSET)) {
  2038. if (v == &vlineno && v->var_text == linenovar) {
  2039. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2040. }
  2041. return var_end(v->var_text);
  2042. }
  2043. }
  2044. return NULL;
  2045. }
  2046. #if ENABLE_UNICODE_SUPPORT
  2047. static void
  2048. reinit_unicode_for_ash(void)
  2049. {
  2050. /* Unicode support should be activated even if LANG is set
  2051. * _during_ shell execution, not only if it was set when
  2052. * shell was started. Therefore, re-check LANG every time:
  2053. */
  2054. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2055. || ENABLE_UNICODE_USING_LOCALE
  2056. ) {
  2057. const char *s = lookupvar("LC_ALL");
  2058. if (!s) s = lookupvar("LC_CTYPE");
  2059. if (!s) s = lookupvar("LANG");
  2060. reinit_unicode(s);
  2061. }
  2062. }
  2063. #else
  2064. # define reinit_unicode_for_ash() ((void)0)
  2065. #endif
  2066. /*
  2067. * Search the environment of a builtin command.
  2068. */
  2069. static ALWAYS_INLINE const char *
  2070. bltinlookup(const char *name)
  2071. {
  2072. return lookupvar(name);
  2073. }
  2074. /*
  2075. * Same as setvar except that the variable and value are passed in
  2076. * the first argument as name=value. Since the first argument will
  2077. * be actually stored in the table, it should not be a string that
  2078. * will go away.
  2079. * Called with interrupts off.
  2080. */
  2081. static struct var *
  2082. setvareq(char *s, int flags)
  2083. {
  2084. struct var *vp, **vpp;
  2085. vpp = hashvar(s);
  2086. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2087. vpp = findvar(vpp, s);
  2088. vp = *vpp;
  2089. if (vp) {
  2090. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2091. const char *n;
  2092. if (flags & VNOSAVE)
  2093. free(s);
  2094. n = vp->var_text;
  2095. exitstatus = 1;
  2096. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2097. }
  2098. if (flags & VNOSET)
  2099. goto out;
  2100. if (vp->var_func && !(flags & VNOFUNC))
  2101. vp->var_func(var_end(s));
  2102. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2103. free((char*)vp->var_text);
  2104. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2105. *vpp = vp->next;
  2106. free(vp);
  2107. out_free:
  2108. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2109. free(s);
  2110. goto out;
  2111. }
  2112. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2113. } else {
  2114. /* variable s is not found */
  2115. if (flags & VNOSET)
  2116. goto out;
  2117. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2118. goto out_free;
  2119. vp = ckzalloc(sizeof(*vp));
  2120. vp->next = *vpp;
  2121. /*vp->func = NULL; - ckzalloc did it */
  2122. *vpp = vp;
  2123. }
  2124. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2125. s = ckstrdup(s);
  2126. vp->var_text = s;
  2127. vp->flags = flags;
  2128. out:
  2129. return vp;
  2130. }
  2131. /*
  2132. * Set the value of a variable. The flags argument is ored with the
  2133. * flags of the variable. If val is NULL, the variable is unset.
  2134. */
  2135. static struct var *
  2136. setvar(const char *name, const char *val, int flags)
  2137. {
  2138. const char *q;
  2139. char *p;
  2140. char *nameeq;
  2141. size_t namelen;
  2142. size_t vallen;
  2143. struct var *vp;
  2144. q = endofname(name);
  2145. p = strchrnul(q, '=');
  2146. namelen = p - name;
  2147. if (!namelen || p != q)
  2148. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2149. vallen = 0;
  2150. if (val == NULL) {
  2151. flags |= VUNSET;
  2152. } else {
  2153. vallen = strlen(val);
  2154. }
  2155. INT_OFF;
  2156. nameeq = ckmalloc(namelen + vallen + 2);
  2157. p = mempcpy(nameeq, name, namelen);
  2158. if (val) {
  2159. *p++ = '=';
  2160. p = mempcpy(p, val, vallen);
  2161. }
  2162. *p = '\0';
  2163. vp = setvareq(nameeq, flags | VNOSAVE);
  2164. INT_ON;
  2165. return vp;
  2166. }
  2167. static void FAST_FUNC
  2168. setvar0(const char *name, const char *val)
  2169. {
  2170. setvar(name, val, 0);
  2171. }
  2172. /*
  2173. * Unset the specified variable.
  2174. */
  2175. static void
  2176. unsetvar(const char *s)
  2177. {
  2178. setvar(s, NULL, 0);
  2179. }
  2180. /*
  2181. * Process a linked list of variable assignments.
  2182. */
  2183. static void
  2184. listsetvar(struct strlist *list_set_var, int flags)
  2185. {
  2186. struct strlist *lp = list_set_var;
  2187. if (!lp)
  2188. return;
  2189. INT_OFF;
  2190. do {
  2191. setvareq(lp->text, flags);
  2192. lp = lp->next;
  2193. } while (lp);
  2194. INT_ON;
  2195. }
  2196. /*
  2197. * Generate a list of variables satisfying the given conditions.
  2198. */
  2199. #if !ENABLE_FEATURE_SH_NOFORK
  2200. # define listvars(on, off, lp, end) listvars(on, off, end)
  2201. #endif
  2202. static char **
  2203. listvars(int on, int off, struct strlist *lp, char ***end)
  2204. {
  2205. struct var **vpp;
  2206. struct var *vp;
  2207. char **ep;
  2208. int mask;
  2209. STARTSTACKSTR(ep);
  2210. vpp = vartab;
  2211. mask = on | off;
  2212. do {
  2213. for (vp = *vpp; vp; vp = vp->next) {
  2214. if ((vp->flags & mask) == on) {
  2215. #if ENABLE_FEATURE_SH_NOFORK
  2216. /* If variable with the same name is both
  2217. * exported and temporarily set for a command:
  2218. * export ZVAR=5
  2219. * ZVAR=6 printenv
  2220. * then "ZVAR=6" will be both in vartab and
  2221. * lp lists. Do not pass it twice to printenv.
  2222. */
  2223. struct strlist *lp1 = lp;
  2224. while (lp1) {
  2225. if (strcmp(lp1->text, vp->var_text) == 0)
  2226. goto skip;
  2227. lp1 = lp1->next;
  2228. }
  2229. #endif
  2230. if (ep == stackstrend())
  2231. ep = growstackstr();
  2232. *ep++ = (char*)vp->var_text;
  2233. #if ENABLE_FEATURE_SH_NOFORK
  2234. skip: ;
  2235. #endif
  2236. }
  2237. }
  2238. } while (++vpp < vartab + VTABSIZE);
  2239. #if ENABLE_FEATURE_SH_NOFORK
  2240. while (lp) {
  2241. if (ep == stackstrend())
  2242. ep = growstackstr();
  2243. *ep++ = lp->text;
  2244. lp = lp->next;
  2245. }
  2246. #endif
  2247. if (ep == stackstrend())
  2248. ep = growstackstr();
  2249. if (end)
  2250. *end = ep;
  2251. *ep++ = NULL;
  2252. return grabstackstr(ep);
  2253. }
  2254. /* ============ Path search helper
  2255. *
  2256. * The variable path (passed by reference) should be set to the start
  2257. * of the path before the first call; path_advance will update
  2258. * this value as it proceeds. Successive calls to path_advance will return
  2259. * the possible path expansions in sequence. If an option (indicated by
  2260. * a percent sign) appears in the path entry then the global variable
  2261. * pathopt will be set to point to it; otherwise pathopt will be set to
  2262. * NULL.
  2263. */
  2264. static const char *pathopt; /* set by path_advance */
  2265. static char *
  2266. path_advance(const char **path, const char *name)
  2267. {
  2268. const char *p;
  2269. char *q;
  2270. const char *start;
  2271. size_t len;
  2272. if (*path == NULL)
  2273. return NULL;
  2274. start = *path;
  2275. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2276. continue;
  2277. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2278. while (stackblocksize() < len)
  2279. growstackblock();
  2280. q = stackblock();
  2281. if (p != start) {
  2282. q = mempcpy(q, start, p - start);
  2283. *q++ = '/';
  2284. }
  2285. strcpy(q, name);
  2286. pathopt = NULL;
  2287. if (*p == '%') {
  2288. pathopt = ++p;
  2289. while (*p && *p != ':')
  2290. p++;
  2291. }
  2292. if (*p == ':')
  2293. *path = p + 1;
  2294. else
  2295. *path = NULL;
  2296. return stalloc(len);
  2297. }
  2298. /* ============ Prompt */
  2299. static smallint doprompt; /* if set, prompt the user */
  2300. static smallint needprompt; /* true if interactive and at start of line */
  2301. #if ENABLE_FEATURE_EDITING
  2302. static line_input_t *line_input_state;
  2303. static const char *cmdedit_prompt;
  2304. static void
  2305. putprompt(const char *s)
  2306. {
  2307. if (ENABLE_ASH_EXPAND_PRMT) {
  2308. free((char*)cmdedit_prompt);
  2309. cmdedit_prompt = ckstrdup(s);
  2310. return;
  2311. }
  2312. cmdedit_prompt = s;
  2313. }
  2314. #else
  2315. static void
  2316. putprompt(const char *s)
  2317. {
  2318. out2str(s);
  2319. }
  2320. #endif
  2321. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2322. static const char *expandstr(const char *ps, int syntax_type);
  2323. /* Values for syntax param */
  2324. #define BASESYNTAX 0 /* not in quotes */
  2325. #define DQSYNTAX 1 /* in double quotes */
  2326. #define SQSYNTAX 2 /* in single quotes */
  2327. #define ARISYNTAX 3 /* in arithmetic */
  2328. #if ENABLE_ASH_EXPAND_PRMT
  2329. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2330. #endif
  2331. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2332. /*
  2333. * called by editline -- any expansions to the prompt should be added here.
  2334. */
  2335. static void
  2336. setprompt_if(smallint do_set, int whichprompt)
  2337. {
  2338. const char *prompt;
  2339. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2340. if (!do_set)
  2341. return;
  2342. needprompt = 0;
  2343. switch (whichprompt) {
  2344. case 1:
  2345. prompt = ps1val();
  2346. break;
  2347. case 2:
  2348. prompt = ps2val();
  2349. break;
  2350. default: /* 0 */
  2351. prompt = nullstr;
  2352. }
  2353. #if ENABLE_ASH_EXPAND_PRMT
  2354. pushstackmark(&smark, stackblocksize());
  2355. putprompt(expandstr(prompt, PSSYNTAX));
  2356. popstackmark(&smark);
  2357. #else
  2358. putprompt(prompt);
  2359. #endif
  2360. }
  2361. /* ============ The cd and pwd commands */
  2362. #define CD_PHYSICAL 1
  2363. #define CD_PRINT 2
  2364. static int
  2365. cdopt(void)
  2366. {
  2367. int flags = 0;
  2368. int i, j;
  2369. j = 'L';
  2370. while ((i = nextopt("LP")) != '\0') {
  2371. if (i != j) {
  2372. flags ^= CD_PHYSICAL;
  2373. j = i;
  2374. }
  2375. }
  2376. return flags;
  2377. }
  2378. /*
  2379. * Update curdir (the name of the current directory) in response to a
  2380. * cd command.
  2381. */
  2382. static const char *
  2383. updatepwd(const char *dir)
  2384. {
  2385. char *new;
  2386. char *p;
  2387. char *cdcomppath;
  2388. const char *lim;
  2389. cdcomppath = sstrdup(dir);
  2390. STARTSTACKSTR(new);
  2391. if (*dir != '/') {
  2392. if (curdir == nullstr)
  2393. return 0;
  2394. new = stack_putstr(curdir, new);
  2395. }
  2396. new = makestrspace(strlen(dir) + 2, new);
  2397. lim = (char *)stackblock() + 1;
  2398. if (*dir != '/') {
  2399. if (new[-1] != '/')
  2400. USTPUTC('/', new);
  2401. if (new > lim && *lim == '/')
  2402. lim++;
  2403. } else {
  2404. USTPUTC('/', new);
  2405. cdcomppath++;
  2406. if (dir[1] == '/' && dir[2] != '/') {
  2407. USTPUTC('/', new);
  2408. cdcomppath++;
  2409. lim++;
  2410. }
  2411. }
  2412. p = strtok(cdcomppath, "/");
  2413. while (p) {
  2414. switch (*p) {
  2415. case '.':
  2416. if (p[1] == '.' && p[2] == '\0') {
  2417. while (new > lim) {
  2418. STUNPUTC(new);
  2419. if (new[-1] == '/')
  2420. break;
  2421. }
  2422. break;
  2423. }
  2424. if (p[1] == '\0')
  2425. break;
  2426. /* fall through */
  2427. default:
  2428. new = stack_putstr(p, new);
  2429. USTPUTC('/', new);
  2430. }
  2431. p = strtok(NULL, "/");
  2432. }
  2433. if (new > lim)
  2434. STUNPUTC(new);
  2435. *new = 0;
  2436. return stackblock();
  2437. }
  2438. /*
  2439. * Find out what the current directory is. If we already know the current
  2440. * directory, this routine returns immediately.
  2441. */
  2442. static char *
  2443. getpwd(void)
  2444. {
  2445. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2446. return dir ? dir : nullstr;
  2447. }
  2448. static void
  2449. setpwd(const char *val, int setold)
  2450. {
  2451. char *oldcur, *dir;
  2452. oldcur = dir = curdir;
  2453. if (setold) {
  2454. setvar("OLDPWD", oldcur, VEXPORT);
  2455. }
  2456. INT_OFF;
  2457. if (physdir != nullstr) {
  2458. if (physdir != oldcur)
  2459. free(physdir);
  2460. physdir = nullstr;
  2461. }
  2462. if (oldcur == val || !val) {
  2463. char *s = getpwd();
  2464. physdir = s;
  2465. if (!val)
  2466. dir = s;
  2467. } else
  2468. dir = ckstrdup(val);
  2469. if (oldcur != dir && oldcur != nullstr) {
  2470. free(oldcur);
  2471. }
  2472. curdir = dir;
  2473. INT_ON;
  2474. setvar("PWD", dir, VEXPORT);
  2475. }
  2476. static void hashcd(void);
  2477. /*
  2478. * Actually do the chdir. We also call hashcd to let other routines
  2479. * know that the current directory has changed.
  2480. */
  2481. static int
  2482. docd(const char *dest, int flags)
  2483. {
  2484. const char *dir = NULL;
  2485. int err;
  2486. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2487. INT_OFF;
  2488. if (!(flags & CD_PHYSICAL)) {
  2489. dir = updatepwd(dest);
  2490. if (dir)
  2491. dest = dir;
  2492. }
  2493. err = chdir(dest);
  2494. if (err)
  2495. goto out;
  2496. setpwd(dir, 1);
  2497. hashcd();
  2498. out:
  2499. INT_ON;
  2500. return err;
  2501. }
  2502. static int FAST_FUNC
  2503. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2504. {
  2505. const char *dest;
  2506. const char *path;
  2507. const char *p;
  2508. char c;
  2509. struct stat statb;
  2510. int flags;
  2511. flags = cdopt();
  2512. dest = *argptr;
  2513. if (!dest)
  2514. dest = bltinlookup("HOME");
  2515. else if (LONE_DASH(dest)) {
  2516. dest = bltinlookup("OLDPWD");
  2517. flags |= CD_PRINT;
  2518. }
  2519. if (!dest)
  2520. dest = nullstr;
  2521. if (*dest == '/')
  2522. goto step6;
  2523. if (*dest == '.') {
  2524. c = dest[1];
  2525. dotdot:
  2526. switch (c) {
  2527. case '\0':
  2528. case '/':
  2529. goto step6;
  2530. case '.':
  2531. c = dest[2];
  2532. if (c != '.')
  2533. goto dotdot;
  2534. }
  2535. }
  2536. if (!*dest)
  2537. dest = ".";
  2538. path = bltinlookup("CDPATH");
  2539. while (path) {
  2540. c = *path;
  2541. p = path_advance(&path, dest);
  2542. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2543. if (c && c != ':')
  2544. flags |= CD_PRINT;
  2545. docd:
  2546. if (!docd(p, flags))
  2547. goto out;
  2548. goto err;
  2549. }
  2550. }
  2551. step6:
  2552. p = dest;
  2553. goto docd;
  2554. err:
  2555. ash_msg_and_raise_perror("can't cd to %s", dest);
  2556. /* NOTREACHED */
  2557. out:
  2558. if (flags & CD_PRINT)
  2559. out1fmt("%s\n", curdir);
  2560. return 0;
  2561. }
  2562. static int FAST_FUNC
  2563. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2564. {
  2565. int flags;
  2566. const char *dir = curdir;
  2567. flags = cdopt();
  2568. if (flags) {
  2569. if (physdir == nullstr)
  2570. setpwd(dir, 0);
  2571. dir = physdir;
  2572. }
  2573. out1fmt("%s\n", dir);
  2574. return 0;
  2575. }
  2576. /* ============ ... */
  2577. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2578. /* Syntax classes */
  2579. #define CWORD 0 /* character is nothing special */
  2580. #define CNL 1 /* newline character */
  2581. #define CBACK 2 /* a backslash character */
  2582. #define CSQUOTE 3 /* single quote */
  2583. #define CDQUOTE 4 /* double quote */
  2584. #define CENDQUOTE 5 /* a terminating quote */
  2585. #define CBQUOTE 6 /* backwards single quote */
  2586. #define CVAR 7 /* a dollar sign */
  2587. #define CENDVAR 8 /* a '}' character */
  2588. #define CLP 9 /* a left paren in arithmetic */
  2589. #define CRP 10 /* a right paren in arithmetic */
  2590. #define CENDFILE 11 /* end of file */
  2591. #define CCTL 12 /* like CWORD, except it must be escaped */
  2592. #define CSPCL 13 /* these terminate a word */
  2593. #define CIGN 14 /* character should be ignored */
  2594. #define PEOF 256
  2595. #if ENABLE_ASH_ALIAS
  2596. # define PEOA 257
  2597. #endif
  2598. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2599. #if ENABLE_FEATURE_SH_MATH
  2600. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2601. #else
  2602. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2603. #endif
  2604. static const uint16_t S_I_T[] ALIGN2 = {
  2605. #if ENABLE_ASH_ALIAS
  2606. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2607. #endif
  2608. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2609. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2610. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2611. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2612. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2613. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2614. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2615. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2616. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2617. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2618. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2619. #if !USE_SIT_FUNCTION
  2620. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2621. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2622. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2623. #endif
  2624. #undef SIT_ITEM
  2625. };
  2626. /* Constants below must match table above */
  2627. enum {
  2628. #if ENABLE_ASH_ALIAS
  2629. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2630. #endif
  2631. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2632. CNL_CNL_CNL_CNL , /* 2 */
  2633. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2634. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2635. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2636. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2637. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2638. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2639. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2640. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2641. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2642. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2643. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2644. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2645. };
  2646. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2647. * caller must ensure proper cast on it if c is *char_ptr!
  2648. */
  2649. #if USE_SIT_FUNCTION
  2650. static int
  2651. SIT(int c, int syntax)
  2652. {
  2653. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2654. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2655. /*
  2656. * This causes '/' to be prepended with CTLESC in dquoted string,
  2657. * making "./file"* treated incorrectly because we feed
  2658. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2659. * The "homegrown" glob implementation is okay with that,
  2660. * but glibc one isn't. With '/' always treated as CWORD,
  2661. * both work fine.
  2662. */
  2663. # if ENABLE_ASH_ALIAS
  2664. static const uint8_t syntax_index_table[] ALIGN1 = {
  2665. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2666. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2667. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2668. 11, 3 /* "}~" */
  2669. };
  2670. # else
  2671. static const uint8_t syntax_index_table[] ALIGN1 = {
  2672. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2673. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2674. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2675. 10, 2 /* "}~" */
  2676. };
  2677. # endif
  2678. const char *s;
  2679. int indx;
  2680. if (c == PEOF)
  2681. return CENDFILE;
  2682. # if ENABLE_ASH_ALIAS
  2683. if (c == PEOA)
  2684. indx = 0;
  2685. else
  2686. # endif
  2687. {
  2688. /* Cast is purely for paranoia here,
  2689. * just in case someone passed signed char to us */
  2690. if ((unsigned char)c >= CTL_FIRST
  2691. && (unsigned char)c <= CTL_LAST
  2692. ) {
  2693. return CCTL;
  2694. }
  2695. s = strchrnul(spec_symbls, c);
  2696. if (*s == '\0')
  2697. return CWORD;
  2698. indx = syntax_index_table[s - spec_symbls];
  2699. }
  2700. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2701. }
  2702. #else /* !USE_SIT_FUNCTION */
  2703. static const uint8_t syntax_index_table[] ALIGN1 = {
  2704. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2705. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2715. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2716. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2731. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2738. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2739. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2740. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2742. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2744. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2745. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2746. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2747. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2748. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2751. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2752. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2753. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2765. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2766. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2767. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2768. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2769. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2770. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2798. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2799. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2800. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2803. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2831. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2832. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2833. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2836. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2837. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2838. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2839. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2840. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2841. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2842. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2843. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2963. # if ENABLE_ASH_ALIAS
  2964. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2965. # endif
  2966. };
  2967. #if 1
  2968. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2969. #else /* debug version, caught one signed char bug */
  2970. # define SIT(c, syntax) \
  2971. ({ \
  2972. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2973. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2974. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2975. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2976. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2977. })
  2978. #endif
  2979. #endif /* !USE_SIT_FUNCTION */
  2980. /* ============ Alias handling */
  2981. #if ENABLE_ASH_ALIAS
  2982. #define ALIASINUSE 1
  2983. #define ALIASDEAD 2
  2984. struct alias {
  2985. struct alias *next;
  2986. char *name;
  2987. char *val;
  2988. int flag;
  2989. };
  2990. static struct alias **atab; // [ATABSIZE];
  2991. #define INIT_G_alias() do { \
  2992. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2993. } while (0)
  2994. static struct alias **
  2995. __lookupalias(const char *name)
  2996. {
  2997. unsigned int hashval;
  2998. struct alias **app;
  2999. const char *p;
  3000. unsigned int ch;
  3001. p = name;
  3002. ch = (unsigned char)*p;
  3003. hashval = ch << 4;
  3004. while (ch) {
  3005. hashval += ch;
  3006. ch = (unsigned char)*++p;
  3007. }
  3008. app = &atab[hashval % ATABSIZE];
  3009. for (; *app; app = &(*app)->next) {
  3010. if (strcmp(name, (*app)->name) == 0) {
  3011. break;
  3012. }
  3013. }
  3014. return app;
  3015. }
  3016. static struct alias *
  3017. lookupalias(const char *name, int check)
  3018. {
  3019. struct alias *ap = *__lookupalias(name);
  3020. if (check && ap && (ap->flag & ALIASINUSE))
  3021. return NULL;
  3022. return ap;
  3023. }
  3024. static struct alias *
  3025. freealias(struct alias *ap)
  3026. {
  3027. struct alias *next;
  3028. if (ap->flag & ALIASINUSE) {
  3029. ap->flag |= ALIASDEAD;
  3030. return ap;
  3031. }
  3032. next = ap->next;
  3033. free(ap->name);
  3034. free(ap->val);
  3035. free(ap);
  3036. return next;
  3037. }
  3038. static void
  3039. setalias(const char *name, const char *val)
  3040. {
  3041. struct alias *ap, **app;
  3042. app = __lookupalias(name);
  3043. ap = *app;
  3044. INT_OFF;
  3045. if (ap) {
  3046. if (!(ap->flag & ALIASINUSE)) {
  3047. free(ap->val);
  3048. }
  3049. ap->val = ckstrdup(val);
  3050. ap->flag &= ~ALIASDEAD;
  3051. } else {
  3052. /* not found */
  3053. ap = ckzalloc(sizeof(struct alias));
  3054. ap->name = ckstrdup(name);
  3055. ap->val = ckstrdup(val);
  3056. /*ap->flag = 0; - ckzalloc did it */
  3057. /*ap->next = NULL;*/
  3058. *app = ap;
  3059. }
  3060. INT_ON;
  3061. }
  3062. static int
  3063. unalias(const char *name)
  3064. {
  3065. struct alias **app;
  3066. app = __lookupalias(name);
  3067. if (*app) {
  3068. INT_OFF;
  3069. *app = freealias(*app);
  3070. INT_ON;
  3071. return 0;
  3072. }
  3073. return 1;
  3074. }
  3075. static void
  3076. rmaliases(void)
  3077. {
  3078. struct alias *ap, **app;
  3079. int i;
  3080. INT_OFF;
  3081. for (i = 0; i < ATABSIZE; i++) {
  3082. app = &atab[i];
  3083. for (ap = *app; ap; ap = *app) {
  3084. *app = freealias(*app);
  3085. if (ap == *app) {
  3086. app = &ap->next;
  3087. }
  3088. }
  3089. }
  3090. INT_ON;
  3091. }
  3092. static void
  3093. printalias(const struct alias *ap)
  3094. {
  3095. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3096. }
  3097. /*
  3098. * TODO - sort output
  3099. */
  3100. static int FAST_FUNC
  3101. aliascmd(int argc UNUSED_PARAM, char **argv)
  3102. {
  3103. char *n, *v;
  3104. int ret = 0;
  3105. struct alias *ap;
  3106. if (!argv[1]) {
  3107. int i;
  3108. for (i = 0; i < ATABSIZE; i++) {
  3109. for (ap = atab[i]; ap; ap = ap->next) {
  3110. printalias(ap);
  3111. }
  3112. }
  3113. return 0;
  3114. }
  3115. while ((n = *++argv) != NULL) {
  3116. v = strchr(n+1, '=');
  3117. if (v == NULL) { /* n+1: funny ksh stuff */
  3118. ap = *__lookupalias(n);
  3119. if (ap == NULL) {
  3120. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3121. ret = 1;
  3122. } else
  3123. printalias(ap);
  3124. } else {
  3125. *v++ = '\0';
  3126. setalias(n, v);
  3127. }
  3128. }
  3129. return ret;
  3130. }
  3131. static int FAST_FUNC
  3132. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3133. {
  3134. int i;
  3135. while (nextopt("a") != '\0') {
  3136. rmaliases();
  3137. return 0;
  3138. }
  3139. for (i = 0; *argptr; argptr++) {
  3140. if (unalias(*argptr)) {
  3141. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3142. i = 1;
  3143. }
  3144. }
  3145. return i;
  3146. }
  3147. #endif /* ASH_ALIAS */
  3148. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3149. #define FORK_FG 0
  3150. #define FORK_BG 1
  3151. #define FORK_NOJOB 2
  3152. /* mode flags for showjob(s) */
  3153. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3154. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3155. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3156. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3157. /*
  3158. * A job structure contains information about a job. A job is either a
  3159. * single process or a set of processes contained in a pipeline. In the
  3160. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3161. * array of pids.
  3162. */
  3163. struct procstat {
  3164. pid_t ps_pid; /* process id */
  3165. int ps_status; /* last process status from wait() */
  3166. char *ps_cmd; /* text of command being run */
  3167. };
  3168. struct job {
  3169. struct procstat ps0; /* status of process */
  3170. struct procstat *ps; /* status or processes when more than one */
  3171. #if JOBS
  3172. int stopstatus; /* status of a stopped job */
  3173. #endif
  3174. unsigned nprocs; /* number of processes */
  3175. #define JOBRUNNING 0 /* at least one proc running */
  3176. #define JOBSTOPPED 1 /* all procs are stopped */
  3177. #define JOBDONE 2 /* all procs are completed */
  3178. unsigned
  3179. state: 8,
  3180. #if JOBS
  3181. sigint: 1, /* job was killed by SIGINT */
  3182. jobctl: 1, /* job running under job control */
  3183. #endif
  3184. waited: 1, /* true if this entry has been waited for */
  3185. used: 1, /* true if this entry is in used */
  3186. changed: 1; /* true if status has changed */
  3187. struct job *prev_job; /* previous job */
  3188. };
  3189. static struct job *makejob(/*union node *,*/ int);
  3190. static int forkshell(struct job *, union node *, int);
  3191. static int waitforjob(struct job *);
  3192. #if !JOBS
  3193. enum { doing_jobctl = 0 };
  3194. #define setjobctl(on) do {} while (0)
  3195. #else
  3196. static smallint doing_jobctl; //references:8
  3197. static void setjobctl(int);
  3198. #endif
  3199. /*
  3200. * Ignore a signal.
  3201. */
  3202. static void
  3203. ignoresig(int signo)
  3204. {
  3205. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3206. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3207. /* No, need to do it */
  3208. signal(signo, SIG_IGN);
  3209. }
  3210. sigmode[signo - 1] = S_HARD_IGN;
  3211. }
  3212. /*
  3213. * Only one usage site - in setsignal()
  3214. */
  3215. static void
  3216. signal_handler(int signo)
  3217. {
  3218. if (signo == SIGCHLD) {
  3219. got_sigchld = 1;
  3220. if (!trap[SIGCHLD])
  3221. return;
  3222. }
  3223. gotsig[signo - 1] = 1;
  3224. pending_sig = signo;
  3225. if (signo == SIGINT && !trap[SIGINT]) {
  3226. if (!suppress_int) {
  3227. pending_sig = 0;
  3228. raise_interrupt(); /* does not return */
  3229. }
  3230. pending_int = 1;
  3231. }
  3232. }
  3233. /*
  3234. * Set the signal handler for the specified signal. The routine figures
  3235. * out what it should be set to.
  3236. */
  3237. static void
  3238. setsignal(int signo)
  3239. {
  3240. char *t;
  3241. char cur_act, new_act;
  3242. struct sigaction act;
  3243. t = trap[signo];
  3244. new_act = S_DFL;
  3245. if (t != NULL) { /* trap for this sig is set */
  3246. new_act = S_CATCH;
  3247. if (t[0] == '\0') /* trap is "": ignore this sig */
  3248. new_act = S_IGN;
  3249. }
  3250. if (rootshell && new_act == S_DFL) {
  3251. switch (signo) {
  3252. case SIGINT:
  3253. if (iflag || minusc || sflag == 0)
  3254. new_act = S_CATCH;
  3255. break;
  3256. case SIGQUIT:
  3257. #if DEBUG
  3258. if (debug)
  3259. break;
  3260. #endif
  3261. /* man bash:
  3262. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3263. * commands run by bash have signal handlers
  3264. * set to the values inherited by the shell
  3265. * from its parent". */
  3266. new_act = S_IGN;
  3267. break;
  3268. case SIGTERM:
  3269. if (iflag)
  3270. new_act = S_IGN;
  3271. break;
  3272. #if JOBS
  3273. case SIGTSTP:
  3274. case SIGTTOU:
  3275. if (mflag)
  3276. new_act = S_IGN;
  3277. break;
  3278. #endif
  3279. }
  3280. }
  3281. /* if !rootshell, we reset SIGQUIT to DFL,
  3282. * whereas we have to restore it to what shell got on entry.
  3283. * This is handled by the fact that if signal was IGNored on entry,
  3284. * then cur_act is S_HARD_IGN and we never change its sigaction
  3285. * (see code below).
  3286. */
  3287. if (signo == SIGCHLD)
  3288. new_act = S_CATCH;
  3289. t = &sigmode[signo - 1];
  3290. cur_act = *t;
  3291. if (cur_act == 0) {
  3292. /* current setting is not yet known */
  3293. if (sigaction(signo, NULL, &act)) {
  3294. /* pretend it worked; maybe we should give a warning,
  3295. * but other shells don't. We don't alter sigmode,
  3296. * so we retry every time.
  3297. * btw, in Linux it never fails. --vda */
  3298. return;
  3299. }
  3300. if (act.sa_handler == SIG_IGN) {
  3301. cur_act = S_HARD_IGN;
  3302. if (mflag
  3303. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3304. ) {
  3305. cur_act = S_IGN; /* don't hard ignore these */
  3306. }
  3307. }
  3308. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3309. /* installing SIG_DFL over SIG_DFL is a no-op */
  3310. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3311. *t = S_DFL;
  3312. return;
  3313. }
  3314. }
  3315. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3316. return;
  3317. *t = new_act;
  3318. act.sa_handler = SIG_DFL;
  3319. switch (new_act) {
  3320. case S_CATCH:
  3321. act.sa_handler = signal_handler;
  3322. break;
  3323. case S_IGN:
  3324. act.sa_handler = SIG_IGN;
  3325. break;
  3326. }
  3327. /* flags and mask matter only if !DFL and !IGN, but we do it
  3328. * for all cases for more deterministic behavior:
  3329. */
  3330. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3331. sigfillset(&act.sa_mask);
  3332. sigaction_set(signo, &act);
  3333. }
  3334. /* mode flags for set_curjob */
  3335. #define CUR_DELETE 2
  3336. #define CUR_RUNNING 1
  3337. #define CUR_STOPPED 0
  3338. #if JOBS
  3339. /* pgrp of shell on invocation */
  3340. static int initialpgrp; //references:2
  3341. static int ttyfd = -1; //5
  3342. #endif
  3343. /* array of jobs */
  3344. static struct job *jobtab; //5
  3345. /* size of array */
  3346. static unsigned njobs; //4
  3347. /* current job */
  3348. static struct job *curjob; //lots
  3349. /* number of presumed living untracked jobs */
  3350. static int jobless; //4
  3351. #if 0
  3352. /* Bash has a feature: it restores termios after a successful wait for
  3353. * a foreground job which had at least one stopped or sigkilled member.
  3354. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3355. * properly restoring tty state. Should we do this too?
  3356. * A reproducer: ^Z an interactive python:
  3357. *
  3358. * # python
  3359. * Python 2.7.12 (...)
  3360. * >>> ^Z
  3361. * { python leaves tty in -icanon -echo state. We do survive that... }
  3362. * [1]+ Stopped python
  3363. * { ...however, next program (python #2) does not survive it well: }
  3364. * # python
  3365. * Python 2.7.12 (...)
  3366. * >>> Traceback (most recent call last):
  3367. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3368. * File "<stdin>", line 1, in <module>
  3369. * NameError: name 'qwerty' is not defined
  3370. *
  3371. * The implementation below is modeled on bash code and seems to work.
  3372. * However, I'm not sure we should do this. For one: what if I'd fg
  3373. * the stopped python instead? It'll be confused by "restored" tty state.
  3374. */
  3375. static struct termios shell_tty_info;
  3376. static void
  3377. get_tty_state(void)
  3378. {
  3379. if (rootshell && ttyfd >= 0)
  3380. tcgetattr(ttyfd, &shell_tty_info);
  3381. }
  3382. static void
  3383. set_tty_state(void)
  3384. {
  3385. /* if (rootshell) - caller ensures this */
  3386. if (ttyfd >= 0)
  3387. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3388. }
  3389. static int
  3390. job_signal_status(struct job *jp)
  3391. {
  3392. int status;
  3393. unsigned i;
  3394. struct procstat *ps = jp->ps;
  3395. for (i = 0; i < jp->nprocs; i++) {
  3396. status = ps[i].ps_status;
  3397. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3398. return status;
  3399. }
  3400. return 0;
  3401. }
  3402. static void
  3403. restore_tty_if_stopped_or_signaled(struct job *jp)
  3404. {
  3405. //TODO: check what happens if we come from waitforjob() in expbackq()
  3406. if (rootshell) {
  3407. int s = job_signal_status(jp);
  3408. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3409. set_tty_state();
  3410. }
  3411. }
  3412. #else
  3413. # define get_tty_state() ((void)0)
  3414. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3415. #endif
  3416. static void
  3417. set_curjob(struct job *jp, unsigned mode)
  3418. {
  3419. struct job *jp1;
  3420. struct job **jpp, **curp;
  3421. /* first remove from list */
  3422. jpp = curp = &curjob;
  3423. while (1) {
  3424. jp1 = *jpp;
  3425. if (jp1 == jp)
  3426. break;
  3427. jpp = &jp1->prev_job;
  3428. }
  3429. *jpp = jp1->prev_job;
  3430. /* Then re-insert in correct position */
  3431. jpp = curp;
  3432. switch (mode) {
  3433. default:
  3434. #if DEBUG
  3435. abort();
  3436. #endif
  3437. case CUR_DELETE:
  3438. /* job being deleted */
  3439. break;
  3440. case CUR_RUNNING:
  3441. /* newly created job or backgrounded job,
  3442. * put after all stopped jobs.
  3443. */
  3444. while (1) {
  3445. jp1 = *jpp;
  3446. #if JOBS
  3447. if (!jp1 || jp1->state != JOBSTOPPED)
  3448. #endif
  3449. break;
  3450. jpp = &jp1->prev_job;
  3451. }
  3452. /* FALLTHROUGH */
  3453. #if JOBS
  3454. case CUR_STOPPED:
  3455. #endif
  3456. /* newly stopped job - becomes curjob */
  3457. jp->prev_job = *jpp;
  3458. *jpp = jp;
  3459. break;
  3460. }
  3461. }
  3462. #if JOBS || DEBUG
  3463. static int
  3464. jobno(const struct job *jp)
  3465. {
  3466. return jp - jobtab + 1;
  3467. }
  3468. #endif
  3469. /*
  3470. * Convert a job name to a job structure.
  3471. */
  3472. #if !JOBS
  3473. #define getjob(name, getctl) getjob(name)
  3474. #endif
  3475. static struct job *
  3476. getjob(const char *name, int getctl)
  3477. {
  3478. struct job *jp;
  3479. struct job *found;
  3480. const char *err_msg = "%s: no such job";
  3481. unsigned num;
  3482. int c;
  3483. const char *p;
  3484. char *(*match)(const char *, const char *);
  3485. jp = curjob;
  3486. p = name;
  3487. if (!p)
  3488. goto currentjob;
  3489. if (*p != '%')
  3490. goto err;
  3491. c = *++p;
  3492. if (!c)
  3493. goto currentjob;
  3494. if (!p[1]) {
  3495. if (c == '+' || c == '%') {
  3496. currentjob:
  3497. err_msg = "No current job";
  3498. goto check;
  3499. }
  3500. if (c == '-') {
  3501. if (jp)
  3502. jp = jp->prev_job;
  3503. err_msg = "No previous job";
  3504. check:
  3505. if (!jp)
  3506. goto err;
  3507. goto gotit;
  3508. }
  3509. }
  3510. if (is_number(p)) {
  3511. num = atoi(p);
  3512. if (num > 0 && num <= njobs) {
  3513. jp = jobtab + num - 1;
  3514. if (jp->used)
  3515. goto gotit;
  3516. goto err;
  3517. }
  3518. }
  3519. match = prefix;
  3520. if (*p == '?') {
  3521. match = strstr;
  3522. p++;
  3523. }
  3524. found = NULL;
  3525. while (jp) {
  3526. if (match(jp->ps[0].ps_cmd, p)) {
  3527. if (found)
  3528. goto err;
  3529. found = jp;
  3530. err_msg = "%s: ambiguous";
  3531. }
  3532. jp = jp->prev_job;
  3533. }
  3534. if (!found)
  3535. goto err;
  3536. jp = found;
  3537. gotit:
  3538. #if JOBS
  3539. err_msg = "job %s not created under job control";
  3540. if (getctl && jp->jobctl == 0)
  3541. goto err;
  3542. #endif
  3543. return jp;
  3544. err:
  3545. ash_msg_and_raise_error(err_msg, name);
  3546. }
  3547. /*
  3548. * Mark a job structure as unused.
  3549. */
  3550. static void
  3551. freejob(struct job *jp)
  3552. {
  3553. struct procstat *ps;
  3554. int i;
  3555. INT_OFF;
  3556. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3557. if (ps->ps_cmd != nullstr)
  3558. free(ps->ps_cmd);
  3559. }
  3560. if (jp->ps != &jp->ps0)
  3561. free(jp->ps);
  3562. jp->used = 0;
  3563. set_curjob(jp, CUR_DELETE);
  3564. INT_ON;
  3565. }
  3566. #if JOBS
  3567. static void
  3568. xtcsetpgrp(int fd, pid_t pgrp)
  3569. {
  3570. if (tcsetpgrp(fd, pgrp))
  3571. ash_msg_and_raise_perror("can't set tty process group");
  3572. }
  3573. /*
  3574. * Turn job control on and off.
  3575. *
  3576. * Note: This code assumes that the third arg to ioctl is a character
  3577. * pointer, which is true on Berkeley systems but not System V. Since
  3578. * System V doesn't have job control yet, this isn't a problem now.
  3579. *
  3580. * Called with interrupts off.
  3581. */
  3582. static void
  3583. setjobctl(int on)
  3584. {
  3585. int fd;
  3586. int pgrp;
  3587. if (on == doing_jobctl || rootshell == 0)
  3588. return;
  3589. if (on) {
  3590. int ofd;
  3591. ofd = fd = open(_PATH_TTY, O_RDWR);
  3592. if (fd < 0) {
  3593. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3594. * That sometimes helps to acquire controlling tty.
  3595. * Obviously, a workaround for bugs when someone
  3596. * failed to provide a controlling tty to bash! :) */
  3597. fd = 2;
  3598. while (!isatty(fd))
  3599. if (--fd < 0)
  3600. goto out;
  3601. }
  3602. /* fd is a tty at this point */
  3603. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3604. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3605. close(ofd);
  3606. if (fd < 0)
  3607. goto out; /* F_DUPFD failed */
  3608. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3609. close_on_exec_on(fd);
  3610. while (1) { /* while we are in the background */
  3611. pgrp = tcgetpgrp(fd);
  3612. if (pgrp < 0) {
  3613. out:
  3614. ash_msg("can't access tty; job control turned off");
  3615. mflag = on = 0;
  3616. goto close;
  3617. }
  3618. if (pgrp == getpgrp())
  3619. break;
  3620. killpg(0, SIGTTIN);
  3621. }
  3622. initialpgrp = pgrp;
  3623. setsignal(SIGTSTP);
  3624. setsignal(SIGTTOU);
  3625. setsignal(SIGTTIN);
  3626. pgrp = rootpid;
  3627. setpgid(0, pgrp);
  3628. xtcsetpgrp(fd, pgrp);
  3629. } else {
  3630. /* turning job control off */
  3631. fd = ttyfd;
  3632. pgrp = initialpgrp;
  3633. /* was xtcsetpgrp, but this can make exiting ash
  3634. * loop forever if pty is already deleted */
  3635. tcsetpgrp(fd, pgrp);
  3636. setpgid(0, pgrp);
  3637. setsignal(SIGTSTP);
  3638. setsignal(SIGTTOU);
  3639. setsignal(SIGTTIN);
  3640. close:
  3641. if (fd >= 0)
  3642. close(fd);
  3643. fd = -1;
  3644. }
  3645. ttyfd = fd;
  3646. doing_jobctl = on;
  3647. }
  3648. static int FAST_FUNC
  3649. killcmd(int argc, char **argv)
  3650. {
  3651. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3652. int i = 1;
  3653. do {
  3654. if (argv[i][0] == '%') {
  3655. /*
  3656. * "kill %N" - job kill
  3657. * Converting to pgrp / pid kill
  3658. */
  3659. struct job *jp;
  3660. char *dst;
  3661. int j, n;
  3662. jp = getjob(argv[i], 0);
  3663. /*
  3664. * In jobs started under job control, we signal
  3665. * entire process group by kill -PGRP_ID.
  3666. * This happens, f.e., in interactive shell.
  3667. *
  3668. * Otherwise, we signal each child via
  3669. * kill PID1 PID2 PID3.
  3670. * Testcases:
  3671. * sh -c 'sleep 1|sleep 1 & kill %1'
  3672. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3673. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3674. */
  3675. n = jp->nprocs; /* can't be 0 (I hope) */
  3676. if (jp->jobctl)
  3677. n = 1;
  3678. dst = alloca(n * sizeof(int)*4);
  3679. argv[i] = dst;
  3680. for (j = 0; j < n; j++) {
  3681. struct procstat *ps = &jp->ps[j];
  3682. /* Skip non-running and not-stopped members
  3683. * (i.e. dead members) of the job
  3684. */
  3685. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3686. continue;
  3687. /*
  3688. * kill_main has matching code to expect
  3689. * leading space. Needed to not confuse
  3690. * negative pids with "kill -SIGNAL_NO" syntax
  3691. */
  3692. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3693. }
  3694. *dst = '\0';
  3695. }
  3696. } while (argv[++i]);
  3697. }
  3698. return kill_main(argc, argv);
  3699. }
  3700. static void
  3701. showpipe(struct job *jp /*, FILE *out*/)
  3702. {
  3703. struct procstat *ps;
  3704. struct procstat *psend;
  3705. psend = jp->ps + jp->nprocs;
  3706. for (ps = jp->ps + 1; ps < psend; ps++)
  3707. printf(" | %s", ps->ps_cmd);
  3708. newline_and_flush(stdout);
  3709. flush_stdout_stderr();
  3710. }
  3711. static int
  3712. restartjob(struct job *jp, int mode)
  3713. {
  3714. struct procstat *ps;
  3715. int i;
  3716. int status;
  3717. pid_t pgid;
  3718. INT_OFF;
  3719. if (jp->state == JOBDONE)
  3720. goto out;
  3721. jp->state = JOBRUNNING;
  3722. pgid = jp->ps[0].ps_pid;
  3723. if (mode == FORK_FG) {
  3724. get_tty_state();
  3725. xtcsetpgrp(ttyfd, pgid);
  3726. }
  3727. killpg(pgid, SIGCONT);
  3728. ps = jp->ps;
  3729. i = jp->nprocs;
  3730. do {
  3731. if (WIFSTOPPED(ps->ps_status)) {
  3732. ps->ps_status = -1;
  3733. }
  3734. ps++;
  3735. } while (--i);
  3736. out:
  3737. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3738. INT_ON;
  3739. return status;
  3740. }
  3741. static int FAST_FUNC
  3742. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3743. {
  3744. struct job *jp;
  3745. int mode;
  3746. int retval;
  3747. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3748. nextopt(nullstr);
  3749. argv = argptr;
  3750. do {
  3751. jp = getjob(*argv, 1);
  3752. if (mode == FORK_BG) {
  3753. set_curjob(jp, CUR_RUNNING);
  3754. printf("[%d] ", jobno(jp));
  3755. }
  3756. out1str(jp->ps[0].ps_cmd);
  3757. showpipe(jp /*, stdout*/);
  3758. retval = restartjob(jp, mode);
  3759. } while (*argv && *++argv);
  3760. return retval;
  3761. }
  3762. #endif
  3763. static int
  3764. sprint_status48(char *s, int status, int sigonly)
  3765. {
  3766. int col;
  3767. int st;
  3768. col = 0;
  3769. if (!WIFEXITED(status)) {
  3770. #if JOBS
  3771. if (WIFSTOPPED(status))
  3772. st = WSTOPSIG(status);
  3773. else
  3774. #endif
  3775. st = WTERMSIG(status);
  3776. if (sigonly) {
  3777. if (st == SIGINT || st == SIGPIPE)
  3778. goto out;
  3779. #if JOBS
  3780. if (WIFSTOPPED(status))
  3781. goto out;
  3782. #endif
  3783. }
  3784. st &= 0x7f;
  3785. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3786. col = fmtstr(s, 32, strsignal(st));
  3787. if (WCOREDUMP(status)) {
  3788. strcpy(s + col, " (core dumped)");
  3789. col += sizeof(" (core dumped)")-1;
  3790. }
  3791. } else if (!sigonly) {
  3792. st = WEXITSTATUS(status);
  3793. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3794. }
  3795. out:
  3796. return col;
  3797. }
  3798. static int
  3799. wait_block_or_sig(int *status)
  3800. {
  3801. int pid;
  3802. do {
  3803. sigset_t mask;
  3804. /* Poll all children for changes in their state */
  3805. got_sigchld = 0;
  3806. /* if job control is active, accept stopped processes too */
  3807. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3808. if (pid != 0)
  3809. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3810. /* Children exist, but none are ready. Sleep until interesting signal */
  3811. #if 1
  3812. sigfillset(&mask);
  3813. sigprocmask(SIG_SETMASK, &mask, &mask);
  3814. while (!got_sigchld && !pending_sig)
  3815. sigsuspend(&mask);
  3816. sigprocmask(SIG_SETMASK, &mask, NULL);
  3817. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3818. while (!got_sigchld && !pending_sig)
  3819. pause();
  3820. #endif
  3821. /* If it was SIGCHLD, poll children again */
  3822. } while (got_sigchld);
  3823. return pid;
  3824. }
  3825. #define DOWAIT_NONBLOCK 0
  3826. #define DOWAIT_BLOCK 1
  3827. #define DOWAIT_BLOCK_OR_SIG 2
  3828. static int
  3829. dowait(int block, struct job *job)
  3830. {
  3831. int pid;
  3832. int status;
  3833. struct job *jp;
  3834. struct job *thisjob = NULL;
  3835. TRACE(("dowait(0x%x) called\n", block));
  3836. /* It's wrong to call waitpid() outside of INT_OFF region:
  3837. * signal can arrive just after syscall return and handler can
  3838. * longjmp away, losing stop/exit notification processing.
  3839. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3840. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3841. *
  3842. * However, for "wait" builtin it is wrong to simply call waitpid()
  3843. * in INT_OFF region: "wait" needs to wait for any running job
  3844. * to change state, but should exit on any trap too.
  3845. * In INT_OFF region, a signal just before syscall entry can set
  3846. * pending_sig variables, but we can't check them, and we would
  3847. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3848. *
  3849. * Because of this, we run inside INT_OFF, but use a special routine
  3850. * which combines waitpid() and sigsuspend().
  3851. * This is the reason why we need to have a handler for SIGCHLD:
  3852. * SIG_DFL handler does not wake sigsuspend().
  3853. */
  3854. INT_OFF;
  3855. if (block == DOWAIT_BLOCK_OR_SIG) {
  3856. pid = wait_block_or_sig(&status);
  3857. } else {
  3858. int wait_flags = 0;
  3859. if (block == DOWAIT_NONBLOCK)
  3860. wait_flags = WNOHANG;
  3861. /* if job control is active, accept stopped processes too */
  3862. if (doing_jobctl)
  3863. wait_flags |= WUNTRACED;
  3864. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3865. pid = waitpid(-1, &status, wait_flags);
  3866. }
  3867. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3868. pid, status, errno, strerror(errno)));
  3869. if (pid <= 0)
  3870. goto out;
  3871. thisjob = NULL;
  3872. for (jp = curjob; jp; jp = jp->prev_job) {
  3873. int jobstate;
  3874. struct procstat *ps;
  3875. struct procstat *psend;
  3876. if (jp->state == JOBDONE)
  3877. continue;
  3878. jobstate = JOBDONE;
  3879. ps = jp->ps;
  3880. psend = ps + jp->nprocs;
  3881. do {
  3882. if (ps->ps_pid == pid) {
  3883. TRACE(("Job %d: changing status of proc %d "
  3884. "from 0x%x to 0x%x\n",
  3885. jobno(jp), pid, ps->ps_status, status));
  3886. ps->ps_status = status;
  3887. thisjob = jp;
  3888. }
  3889. if (ps->ps_status == -1)
  3890. jobstate = JOBRUNNING;
  3891. #if JOBS
  3892. if (jobstate == JOBRUNNING)
  3893. continue;
  3894. if (WIFSTOPPED(ps->ps_status)) {
  3895. jp->stopstatus = ps->ps_status;
  3896. jobstate = JOBSTOPPED;
  3897. }
  3898. #endif
  3899. } while (++ps < psend);
  3900. if (!thisjob)
  3901. continue;
  3902. /* Found the job where one of its processes changed its state.
  3903. * Is there at least one live and running process in this job? */
  3904. if (jobstate != JOBRUNNING) {
  3905. /* No. All live processes in the job are stopped
  3906. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3907. */
  3908. thisjob->changed = 1;
  3909. if (thisjob->state != jobstate) {
  3910. TRACE(("Job %d: changing state from %d to %d\n",
  3911. jobno(thisjob), thisjob->state, jobstate));
  3912. thisjob->state = jobstate;
  3913. #if JOBS
  3914. if (jobstate == JOBSTOPPED)
  3915. set_curjob(thisjob, CUR_STOPPED);
  3916. #endif
  3917. }
  3918. }
  3919. goto out;
  3920. }
  3921. /* The process wasn't found in job list */
  3922. #if JOBS
  3923. if (!WIFSTOPPED(status))
  3924. jobless--;
  3925. #endif
  3926. out:
  3927. INT_ON;
  3928. if (thisjob && thisjob == job) {
  3929. char s[48 + 1];
  3930. int len;
  3931. len = sprint_status48(s, status, 1);
  3932. if (len) {
  3933. s[len] = '\n';
  3934. s[len + 1] = '\0';
  3935. out2str(s);
  3936. }
  3937. }
  3938. return pid;
  3939. }
  3940. #if JOBS
  3941. static void
  3942. showjob(struct job *jp, int mode)
  3943. {
  3944. struct procstat *ps;
  3945. struct procstat *psend;
  3946. int col;
  3947. int indent_col;
  3948. char s[16 + 16 + 48];
  3949. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3950. ps = jp->ps;
  3951. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3952. /* just output process (group) id of pipeline */
  3953. fprintf(out, "%d\n", ps->ps_pid);
  3954. return;
  3955. }
  3956. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3957. indent_col = col;
  3958. if (jp == curjob)
  3959. s[col - 3] = '+';
  3960. else if (curjob && jp == curjob->prev_job)
  3961. s[col - 3] = '-';
  3962. if (mode & SHOW_PIDS)
  3963. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3964. psend = ps + jp->nprocs;
  3965. if (jp->state == JOBRUNNING) {
  3966. strcpy(s + col, "Running");
  3967. col += sizeof("Running") - 1;
  3968. } else {
  3969. int status = psend[-1].ps_status;
  3970. if (jp->state == JOBSTOPPED)
  3971. status = jp->stopstatus;
  3972. col += sprint_status48(s + col, status, 0);
  3973. }
  3974. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3975. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3976. * or prints several "PID | <cmdN>" lines,
  3977. * depending on SHOW_PIDS bit.
  3978. * We do not print status of individual processes
  3979. * between PID and <cmdN>. bash does it, but not very well:
  3980. * first line shows overall job status, not process status,
  3981. * making it impossible to know 1st process status.
  3982. */
  3983. goto start;
  3984. do {
  3985. /* for each process */
  3986. s[0] = '\0';
  3987. col = 33;
  3988. if (mode & SHOW_PIDS)
  3989. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3990. start:
  3991. fprintf(out, "%s%*c%s%s",
  3992. s,
  3993. 33 - col >= 0 ? 33 - col : 0, ' ',
  3994. ps == jp->ps ? "" : "| ",
  3995. ps->ps_cmd
  3996. );
  3997. } while (++ps != psend);
  3998. newline_and_flush(out);
  3999. jp->changed = 0;
  4000. if (jp->state == JOBDONE) {
  4001. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4002. freejob(jp);
  4003. }
  4004. }
  4005. /*
  4006. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4007. * statuses have changed since the last call to showjobs.
  4008. */
  4009. static void
  4010. showjobs(int mode)
  4011. {
  4012. struct job *jp;
  4013. TRACE(("showjobs(0x%x) called\n", mode));
  4014. /* Handle all finished jobs */
  4015. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4016. continue;
  4017. for (jp = curjob; jp; jp = jp->prev_job) {
  4018. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4019. showjob(jp, mode);
  4020. }
  4021. }
  4022. }
  4023. static int FAST_FUNC
  4024. jobscmd(int argc UNUSED_PARAM, char **argv)
  4025. {
  4026. int mode, m;
  4027. mode = 0;
  4028. while ((m = nextopt("lp")) != '\0') {
  4029. if (m == 'l')
  4030. mode |= SHOW_PIDS;
  4031. else
  4032. mode |= SHOW_ONLY_PGID;
  4033. }
  4034. argv = argptr;
  4035. if (*argv) {
  4036. do
  4037. showjob(getjob(*argv, 0), mode);
  4038. while (*++argv);
  4039. } else {
  4040. showjobs(mode);
  4041. }
  4042. return 0;
  4043. }
  4044. #endif /* JOBS */
  4045. /* Called only on finished or stopped jobs (no members are running) */
  4046. static int
  4047. getstatus(struct job *job)
  4048. {
  4049. int status;
  4050. int retval;
  4051. struct procstat *ps;
  4052. /* Fetch last member's status */
  4053. ps = job->ps + job->nprocs - 1;
  4054. status = ps->ps_status;
  4055. if (pipefail) {
  4056. /* "set -o pipefail" mode: use last _nonzero_ status */
  4057. while (status == 0 && --ps >= job->ps)
  4058. status = ps->ps_status;
  4059. }
  4060. retval = WEXITSTATUS(status);
  4061. if (!WIFEXITED(status)) {
  4062. #if JOBS
  4063. retval = WSTOPSIG(status);
  4064. if (!WIFSTOPPED(status))
  4065. #endif
  4066. {
  4067. /* XXX: limits number of signals */
  4068. retval = WTERMSIG(status);
  4069. #if JOBS
  4070. if (retval == SIGINT)
  4071. job->sigint = 1;
  4072. #endif
  4073. }
  4074. retval += 128;
  4075. }
  4076. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4077. jobno(job), job->nprocs, status, retval));
  4078. return retval;
  4079. }
  4080. static int FAST_FUNC
  4081. waitcmd(int argc UNUSED_PARAM, char **argv)
  4082. {
  4083. struct job *job;
  4084. int retval;
  4085. struct job *jp;
  4086. nextopt(nullstr);
  4087. retval = 0;
  4088. argv = argptr;
  4089. if (!*argv) {
  4090. /* wait for all jobs */
  4091. for (;;) {
  4092. jp = curjob;
  4093. while (1) {
  4094. if (!jp) /* no running procs */
  4095. goto ret;
  4096. if (jp->state == JOBRUNNING)
  4097. break;
  4098. jp->waited = 1;
  4099. jp = jp->prev_job;
  4100. }
  4101. /* man bash:
  4102. * "When bash is waiting for an asynchronous command via
  4103. * the wait builtin, the reception of a signal for which a trap
  4104. * has been set will cause the wait builtin to return immediately
  4105. * with an exit status greater than 128, immediately after which
  4106. * the trap is executed."
  4107. */
  4108. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4109. /* if child sends us a signal *and immediately exits*,
  4110. * dowait() returns pid > 0. Check this case,
  4111. * not "if (dowait() < 0)"!
  4112. */
  4113. if (pending_sig)
  4114. goto sigout;
  4115. }
  4116. }
  4117. retval = 127;
  4118. do {
  4119. if (**argv != '%') {
  4120. pid_t pid = number(*argv);
  4121. job = curjob;
  4122. while (1) {
  4123. if (!job)
  4124. goto repeat;
  4125. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4126. break;
  4127. job = job->prev_job;
  4128. }
  4129. } else {
  4130. job = getjob(*argv, 0);
  4131. }
  4132. /* loop until process terminated or stopped */
  4133. while (job->state == JOBRUNNING) {
  4134. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4135. if (pending_sig)
  4136. goto sigout;
  4137. }
  4138. job->waited = 1;
  4139. retval = getstatus(job);
  4140. repeat: ;
  4141. } while (*++argv);
  4142. ret:
  4143. return retval;
  4144. sigout:
  4145. retval = 128 + pending_sig;
  4146. return retval;
  4147. }
  4148. static struct job *
  4149. growjobtab(void)
  4150. {
  4151. size_t len;
  4152. ptrdiff_t offset;
  4153. struct job *jp, *jq;
  4154. len = njobs * sizeof(*jp);
  4155. jq = jobtab;
  4156. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4157. offset = (char *)jp - (char *)jq;
  4158. if (offset) {
  4159. /* Relocate pointers */
  4160. size_t l = len;
  4161. jq = (struct job *)((char *)jq + l);
  4162. while (l) {
  4163. l -= sizeof(*jp);
  4164. jq--;
  4165. #define joff(p) ((struct job *)((char *)(p) + l))
  4166. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4167. if (joff(jp)->ps == &jq->ps0)
  4168. jmove(joff(jp)->ps);
  4169. if (joff(jp)->prev_job)
  4170. jmove(joff(jp)->prev_job);
  4171. }
  4172. if (curjob)
  4173. jmove(curjob);
  4174. #undef joff
  4175. #undef jmove
  4176. }
  4177. njobs += 4;
  4178. jobtab = jp;
  4179. jp = (struct job *)((char *)jp + len);
  4180. jq = jp + 3;
  4181. do {
  4182. jq->used = 0;
  4183. } while (--jq >= jp);
  4184. return jp;
  4185. }
  4186. /*
  4187. * Return a new job structure.
  4188. * Called with interrupts off.
  4189. */
  4190. static struct job *
  4191. makejob(/*union node *node,*/ int nprocs)
  4192. {
  4193. int i;
  4194. struct job *jp;
  4195. for (i = njobs, jp = jobtab; ; jp++) {
  4196. if (--i < 0) {
  4197. jp = growjobtab();
  4198. break;
  4199. }
  4200. if (jp->used == 0)
  4201. break;
  4202. if (jp->state != JOBDONE || !jp->waited)
  4203. continue;
  4204. #if JOBS
  4205. if (doing_jobctl)
  4206. continue;
  4207. #endif
  4208. freejob(jp);
  4209. break;
  4210. }
  4211. memset(jp, 0, sizeof(*jp));
  4212. #if JOBS
  4213. /* jp->jobctl is a bitfield.
  4214. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4215. if (doing_jobctl)
  4216. jp->jobctl = 1;
  4217. #endif
  4218. jp->prev_job = curjob;
  4219. curjob = jp;
  4220. jp->used = 1;
  4221. jp->ps = &jp->ps0;
  4222. if (nprocs > 1) {
  4223. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4224. }
  4225. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4226. jobno(jp)));
  4227. return jp;
  4228. }
  4229. #if JOBS
  4230. /*
  4231. * Return a string identifying a command (to be printed by the
  4232. * jobs command).
  4233. */
  4234. static char *cmdnextc;
  4235. static void
  4236. cmdputs(const char *s)
  4237. {
  4238. static const char vstype[VSTYPE + 1][3] = {
  4239. "", "}", "-", "+", "?", "=",
  4240. "%", "%%", "#", "##"
  4241. IF_BASH_SUBSTR(, ":")
  4242. IF_BASH_PATTERN_SUBST(, "/", "//")
  4243. };
  4244. const char *p, *str;
  4245. char cc[2];
  4246. char *nextc;
  4247. unsigned char c;
  4248. unsigned char subtype = 0;
  4249. int quoted = 0;
  4250. cc[1] = '\0';
  4251. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4252. p = s;
  4253. while ((c = *p++) != '\0') {
  4254. str = NULL;
  4255. switch (c) {
  4256. case CTLESC:
  4257. c = *p++;
  4258. break;
  4259. case CTLVAR:
  4260. subtype = *p++;
  4261. if ((subtype & VSTYPE) == VSLENGTH)
  4262. str = "${#";
  4263. else
  4264. str = "${";
  4265. goto dostr;
  4266. case CTLENDVAR:
  4267. str = "\"}" + !(quoted & 1);
  4268. quoted >>= 1;
  4269. subtype = 0;
  4270. goto dostr;
  4271. case CTLBACKQ:
  4272. str = "$(...)";
  4273. goto dostr;
  4274. #if ENABLE_FEATURE_SH_MATH
  4275. case CTLARI:
  4276. str = "$((";
  4277. goto dostr;
  4278. case CTLENDARI:
  4279. str = "))";
  4280. goto dostr;
  4281. #endif
  4282. case CTLQUOTEMARK:
  4283. quoted ^= 1;
  4284. c = '"';
  4285. break;
  4286. case '=':
  4287. if (subtype == 0)
  4288. break;
  4289. if ((subtype & VSTYPE) != VSNORMAL)
  4290. quoted <<= 1;
  4291. str = vstype[subtype & VSTYPE];
  4292. if (subtype & VSNUL)
  4293. c = ':';
  4294. else
  4295. goto checkstr;
  4296. break;
  4297. case '\'':
  4298. case '\\':
  4299. case '"':
  4300. case '$':
  4301. /* These can only happen inside quotes */
  4302. cc[0] = c;
  4303. str = cc;
  4304. //FIXME:
  4305. // $ true $$ &
  4306. // $ <cr>
  4307. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4308. c = '\\';
  4309. break;
  4310. default:
  4311. break;
  4312. }
  4313. USTPUTC(c, nextc);
  4314. checkstr:
  4315. if (!str)
  4316. continue;
  4317. dostr:
  4318. while ((c = *str++) != '\0') {
  4319. USTPUTC(c, nextc);
  4320. }
  4321. } /* while *p++ not NUL */
  4322. if (quoted & 1) {
  4323. USTPUTC('"', nextc);
  4324. }
  4325. *nextc = 0;
  4326. cmdnextc = nextc;
  4327. }
  4328. /* cmdtxt() and cmdlist() call each other */
  4329. static void cmdtxt(union node *n);
  4330. static void
  4331. cmdlist(union node *np, int sep)
  4332. {
  4333. for (; np; np = np->narg.next) {
  4334. if (!sep)
  4335. cmdputs(" ");
  4336. cmdtxt(np);
  4337. if (sep && np->narg.next)
  4338. cmdputs(" ");
  4339. }
  4340. }
  4341. static void
  4342. cmdtxt(union node *n)
  4343. {
  4344. union node *np;
  4345. struct nodelist *lp;
  4346. const char *p;
  4347. if (!n)
  4348. return;
  4349. switch (n->type) {
  4350. default:
  4351. #if DEBUG
  4352. abort();
  4353. #endif
  4354. case NPIPE:
  4355. lp = n->npipe.cmdlist;
  4356. for (;;) {
  4357. cmdtxt(lp->n);
  4358. lp = lp->next;
  4359. if (!lp)
  4360. break;
  4361. cmdputs(" | ");
  4362. }
  4363. break;
  4364. case NSEMI:
  4365. p = "; ";
  4366. goto binop;
  4367. case NAND:
  4368. p = " && ";
  4369. goto binop;
  4370. case NOR:
  4371. p = " || ";
  4372. binop:
  4373. cmdtxt(n->nbinary.ch1);
  4374. cmdputs(p);
  4375. n = n->nbinary.ch2;
  4376. goto donode;
  4377. case NREDIR:
  4378. case NBACKGND:
  4379. n = n->nredir.n;
  4380. goto donode;
  4381. case NNOT:
  4382. cmdputs("!");
  4383. n = n->nnot.com;
  4384. donode:
  4385. cmdtxt(n);
  4386. break;
  4387. case NIF:
  4388. cmdputs("if ");
  4389. cmdtxt(n->nif.test);
  4390. cmdputs("; then ");
  4391. if (n->nif.elsepart) {
  4392. cmdtxt(n->nif.ifpart);
  4393. cmdputs("; else ");
  4394. n = n->nif.elsepart;
  4395. } else {
  4396. n = n->nif.ifpart;
  4397. }
  4398. p = "; fi";
  4399. goto dotail;
  4400. case NSUBSHELL:
  4401. cmdputs("(");
  4402. n = n->nredir.n;
  4403. p = ")";
  4404. goto dotail;
  4405. case NWHILE:
  4406. p = "while ";
  4407. goto until;
  4408. case NUNTIL:
  4409. p = "until ";
  4410. until:
  4411. cmdputs(p);
  4412. cmdtxt(n->nbinary.ch1);
  4413. n = n->nbinary.ch2;
  4414. p = "; done";
  4415. dodo:
  4416. cmdputs("; do ");
  4417. dotail:
  4418. cmdtxt(n);
  4419. goto dotail2;
  4420. case NFOR:
  4421. cmdputs("for ");
  4422. cmdputs(n->nfor.var);
  4423. cmdputs(" in ");
  4424. cmdlist(n->nfor.args, 1);
  4425. n = n->nfor.body;
  4426. p = "; done";
  4427. goto dodo;
  4428. case NDEFUN:
  4429. cmdputs(n->ndefun.text);
  4430. p = "() { ... }";
  4431. goto dotail2;
  4432. case NCMD:
  4433. cmdlist(n->ncmd.args, 1);
  4434. cmdlist(n->ncmd.redirect, 0);
  4435. break;
  4436. case NARG:
  4437. p = n->narg.text;
  4438. dotail2:
  4439. cmdputs(p);
  4440. break;
  4441. case NHERE:
  4442. case NXHERE:
  4443. p = "<<...";
  4444. goto dotail2;
  4445. case NCASE:
  4446. cmdputs("case ");
  4447. cmdputs(n->ncase.expr->narg.text);
  4448. cmdputs(" in ");
  4449. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4450. cmdtxt(np->nclist.pattern);
  4451. cmdputs(") ");
  4452. cmdtxt(np->nclist.body);
  4453. cmdputs(";; ");
  4454. }
  4455. p = "esac";
  4456. goto dotail2;
  4457. case NTO:
  4458. p = ">";
  4459. goto redir;
  4460. case NCLOBBER:
  4461. p = ">|";
  4462. goto redir;
  4463. case NAPPEND:
  4464. p = ">>";
  4465. goto redir;
  4466. #if BASH_REDIR_OUTPUT
  4467. case NTO2:
  4468. #endif
  4469. case NTOFD:
  4470. p = ">&";
  4471. goto redir;
  4472. case NFROM:
  4473. p = "<";
  4474. goto redir;
  4475. case NFROMFD:
  4476. p = "<&";
  4477. goto redir;
  4478. case NFROMTO:
  4479. p = "<>";
  4480. redir:
  4481. cmdputs(utoa(n->nfile.fd));
  4482. cmdputs(p);
  4483. if (n->type == NTOFD || n->type == NFROMFD) {
  4484. if (n->ndup.dupfd >= 0)
  4485. cmdputs(utoa(n->ndup.dupfd));
  4486. else
  4487. cmdputs("-");
  4488. break;
  4489. }
  4490. n = n->nfile.fname;
  4491. goto donode;
  4492. }
  4493. }
  4494. static char *
  4495. commandtext(union node *n)
  4496. {
  4497. char *name;
  4498. STARTSTACKSTR(cmdnextc);
  4499. cmdtxt(n);
  4500. name = stackblock();
  4501. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4502. return ckstrdup(name);
  4503. }
  4504. #endif /* JOBS */
  4505. /*
  4506. * Fork off a subshell. If we are doing job control, give the subshell its
  4507. * own process group. Jp is a job structure that the job is to be added to.
  4508. * N is the command that will be evaluated by the child. Both jp and n may
  4509. * be NULL. The mode parameter can be one of the following:
  4510. * FORK_FG - Fork off a foreground process.
  4511. * FORK_BG - Fork off a background process.
  4512. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4513. * process group even if job control is on.
  4514. *
  4515. * When job control is turned off, background processes have their standard
  4516. * input redirected to /dev/null (except for the second and later processes
  4517. * in a pipeline).
  4518. *
  4519. * Called with interrupts off.
  4520. */
  4521. /*
  4522. * Clear traps on a fork.
  4523. */
  4524. static void
  4525. clear_traps(void)
  4526. {
  4527. char **tp;
  4528. INT_OFF;
  4529. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4530. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4531. if (trap_ptr == trap)
  4532. free(*tp);
  4533. /* else: it "belongs" to trap_ptr vector, don't free */
  4534. *tp = NULL;
  4535. if ((tp - trap) != 0)
  4536. setsignal(tp - trap);
  4537. }
  4538. }
  4539. may_have_traps = 0;
  4540. INT_ON;
  4541. }
  4542. /* Lives far away from here, needed for forkchild */
  4543. static void closescript(void);
  4544. /* Called after fork(), in child */
  4545. /* jp and n are NULL when called by openhere() for heredoc support */
  4546. static NOINLINE void
  4547. forkchild(struct job *jp, union node *n, int mode)
  4548. {
  4549. int oldlvl;
  4550. TRACE(("Child shell %d\n", getpid()));
  4551. oldlvl = shlvl;
  4552. shlvl++;
  4553. /* man bash: "Non-builtin commands run by bash have signal handlers
  4554. * set to the values inherited by the shell from its parent".
  4555. * Do we do it correctly? */
  4556. closescript();
  4557. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4558. && n && n->type == NCMD /* is it single cmd? */
  4559. /* && n->ncmd.args->type == NARG - always true? */
  4560. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4561. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4562. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4563. ) {
  4564. TRACE(("Trap hack\n"));
  4565. /* Awful hack for `trap` or $(trap).
  4566. *
  4567. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4568. * contains an example where "trap" is executed in a subshell:
  4569. *
  4570. * save_traps=$(trap)
  4571. * ...
  4572. * eval "$save_traps"
  4573. *
  4574. * Standard does not say that "trap" in subshell shall print
  4575. * parent shell's traps. It only says that its output
  4576. * must have suitable form, but then, in the above example
  4577. * (which is not supposed to be normative), it implies that.
  4578. *
  4579. * bash (and probably other shell) does implement it
  4580. * (traps are reset to defaults, but "trap" still shows them),
  4581. * but as a result, "trap" logic is hopelessly messed up:
  4582. *
  4583. * # trap
  4584. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4585. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4586. * # true | trap <--- trap is in subshell - no output (ditto)
  4587. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4588. * trap -- 'echo Ho' SIGWINCH
  4589. * # echo `(trap)` <--- in subshell in subshell - output
  4590. * trap -- 'echo Ho' SIGWINCH
  4591. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4592. * trap -- 'echo Ho' SIGWINCH
  4593. *
  4594. * The rules when to forget and when to not forget traps
  4595. * get really complex and nonsensical.
  4596. *
  4597. * Our solution: ONLY bare $(trap) or `trap` is special.
  4598. */
  4599. /* Save trap handler strings for trap builtin to print */
  4600. trap_ptr = xmemdup(trap, sizeof(trap));
  4601. /* Fall through into clearing traps */
  4602. }
  4603. clear_traps();
  4604. #if JOBS
  4605. /* do job control only in root shell */
  4606. doing_jobctl = 0;
  4607. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4608. pid_t pgrp;
  4609. if (jp->nprocs == 0)
  4610. pgrp = getpid();
  4611. else
  4612. pgrp = jp->ps[0].ps_pid;
  4613. /* this can fail because we are doing it in the parent also */
  4614. setpgid(0, pgrp);
  4615. if (mode == FORK_FG)
  4616. xtcsetpgrp(ttyfd, pgrp);
  4617. setsignal(SIGTSTP);
  4618. setsignal(SIGTTOU);
  4619. } else
  4620. #endif
  4621. if (mode == FORK_BG) {
  4622. /* man bash: "When job control is not in effect,
  4623. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4624. ignoresig(SIGINT);
  4625. ignoresig(SIGQUIT);
  4626. if (jp->nprocs == 0) {
  4627. close(0);
  4628. if (open(bb_dev_null, O_RDONLY) != 0)
  4629. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4630. }
  4631. }
  4632. if (oldlvl == 0) {
  4633. if (iflag) { /* why if iflag only? */
  4634. setsignal(SIGINT);
  4635. setsignal(SIGTERM);
  4636. }
  4637. /* man bash:
  4638. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4639. * commands run by bash have signal handlers
  4640. * set to the values inherited by the shell
  4641. * from its parent".
  4642. * Take care of the second rule: */
  4643. setsignal(SIGQUIT);
  4644. }
  4645. #if JOBS
  4646. if (n && n->type == NCMD
  4647. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4648. ) {
  4649. TRACE(("Job hack\n"));
  4650. /* "jobs": we do not want to clear job list for it,
  4651. * instead we remove only _its_ own_ job from job list.
  4652. * This makes "jobs .... | cat" more useful.
  4653. */
  4654. freejob(curjob);
  4655. return;
  4656. }
  4657. #endif
  4658. for (jp = curjob; jp; jp = jp->prev_job)
  4659. freejob(jp);
  4660. jobless = 0;
  4661. }
  4662. /* Called after fork(), in parent */
  4663. #if !JOBS
  4664. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4665. #endif
  4666. static void
  4667. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4668. {
  4669. TRACE(("In parent shell: child = %d\n", pid));
  4670. if (!jp) {
  4671. /* jp is NULL when called by openhere() for heredoc support */
  4672. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4673. continue;
  4674. jobless++;
  4675. return;
  4676. }
  4677. #if JOBS
  4678. if (mode != FORK_NOJOB && jp->jobctl) {
  4679. int pgrp;
  4680. if (jp->nprocs == 0)
  4681. pgrp = pid;
  4682. else
  4683. pgrp = jp->ps[0].ps_pid;
  4684. /* This can fail because we are doing it in the child also */
  4685. setpgid(pid, pgrp);
  4686. }
  4687. #endif
  4688. if (mode == FORK_BG) {
  4689. backgndpid = pid; /* set $! */
  4690. set_curjob(jp, CUR_RUNNING);
  4691. }
  4692. if (jp) {
  4693. struct procstat *ps = &jp->ps[jp->nprocs++];
  4694. ps->ps_pid = pid;
  4695. ps->ps_status = -1;
  4696. ps->ps_cmd = nullstr;
  4697. #if JOBS
  4698. if (doing_jobctl && n)
  4699. ps->ps_cmd = commandtext(n);
  4700. #endif
  4701. }
  4702. }
  4703. /* jp and n are NULL when called by openhere() for heredoc support */
  4704. static int
  4705. forkshell(struct job *jp, union node *n, int mode)
  4706. {
  4707. int pid;
  4708. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4709. pid = fork();
  4710. if (pid < 0) {
  4711. TRACE(("Fork failed, errno=%d", errno));
  4712. if (jp)
  4713. freejob(jp);
  4714. ash_msg_and_raise_perror("can't fork");
  4715. }
  4716. if (pid == 0) {
  4717. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4718. forkchild(jp, n, mode);
  4719. } else {
  4720. forkparent(jp, n, mode, pid);
  4721. }
  4722. return pid;
  4723. }
  4724. /*
  4725. * Wait for job to finish.
  4726. *
  4727. * Under job control we have the problem that while a child process
  4728. * is running interrupts generated by the user are sent to the child
  4729. * but not to the shell. This means that an infinite loop started by
  4730. * an interactive user may be hard to kill. With job control turned off,
  4731. * an interactive user may place an interactive program inside a loop.
  4732. * If the interactive program catches interrupts, the user doesn't want
  4733. * these interrupts to also abort the loop. The approach we take here
  4734. * is to have the shell ignore interrupt signals while waiting for a
  4735. * foreground process to terminate, and then send itself an interrupt
  4736. * signal if the child process was terminated by an interrupt signal.
  4737. * Unfortunately, some programs want to do a bit of cleanup and then
  4738. * exit on interrupt; unless these processes terminate themselves by
  4739. * sending a signal to themselves (instead of calling exit) they will
  4740. * confuse this approach.
  4741. *
  4742. * Called with interrupts off.
  4743. */
  4744. static int
  4745. waitforjob(struct job *jp)
  4746. {
  4747. int st;
  4748. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4749. INT_OFF;
  4750. while (jp->state == JOBRUNNING) {
  4751. /* In non-interactive shells, we _can_ get
  4752. * a keyboard signal here and be EINTRed,
  4753. * but we just loop back, waiting for command to complete.
  4754. *
  4755. * man bash:
  4756. * "If bash is waiting for a command to complete and receives
  4757. * a signal for which a trap has been set, the trap
  4758. * will not be executed until the command completes."
  4759. *
  4760. * Reality is that even if trap is not set, bash
  4761. * will not act on the signal until command completes.
  4762. * Try this. sleep5intoff.c:
  4763. * #include <signal.h>
  4764. * #include <unistd.h>
  4765. * int main() {
  4766. * sigset_t set;
  4767. * sigemptyset(&set);
  4768. * sigaddset(&set, SIGINT);
  4769. * sigaddset(&set, SIGQUIT);
  4770. * sigprocmask(SIG_BLOCK, &set, NULL);
  4771. * sleep(5);
  4772. * return 0;
  4773. * }
  4774. * $ bash -c './sleep5intoff; echo hi'
  4775. * ^C^C^C^C <--- pressing ^C once a second
  4776. * $ _
  4777. * $ bash -c './sleep5intoff; echo hi'
  4778. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4779. * $ _
  4780. */
  4781. dowait(DOWAIT_BLOCK, jp);
  4782. }
  4783. INT_ON;
  4784. st = getstatus(jp);
  4785. #if JOBS
  4786. if (jp->jobctl) {
  4787. xtcsetpgrp(ttyfd, rootpid);
  4788. restore_tty_if_stopped_or_signaled(jp);
  4789. /*
  4790. * This is truly gross.
  4791. * If we're doing job control, then we did a TIOCSPGRP which
  4792. * caused us (the shell) to no longer be in the controlling
  4793. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4794. * intuit from the subprocess exit status whether a SIGINT
  4795. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4796. */
  4797. if (jp->sigint) /* TODO: do the same with all signals */
  4798. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4799. }
  4800. if (jp->state == JOBDONE)
  4801. #endif
  4802. freejob(jp);
  4803. return st;
  4804. }
  4805. /*
  4806. * return 1 if there are stopped jobs, otherwise 0
  4807. */
  4808. static int
  4809. stoppedjobs(void)
  4810. {
  4811. struct job *jp;
  4812. int retval;
  4813. retval = 0;
  4814. if (job_warning)
  4815. goto out;
  4816. jp = curjob;
  4817. if (jp && jp->state == JOBSTOPPED) {
  4818. out2str("You have stopped jobs.\n");
  4819. job_warning = 2;
  4820. retval++;
  4821. }
  4822. out:
  4823. return retval;
  4824. }
  4825. /*
  4826. * Code for dealing with input/output redirection.
  4827. */
  4828. #undef EMPTY
  4829. #undef CLOSED
  4830. #define EMPTY -2 /* marks an unused slot in redirtab */
  4831. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4832. /*
  4833. * Handle here documents. Normally we fork off a process to write the
  4834. * data to a pipe. If the document is short, we can stuff the data in
  4835. * the pipe without forking.
  4836. */
  4837. /* openhere needs this forward reference */
  4838. static void expandhere(union node *arg, int fd);
  4839. static int
  4840. openhere(union node *redir)
  4841. {
  4842. int pip[2];
  4843. size_t len = 0;
  4844. if (pipe(pip) < 0)
  4845. ash_msg_and_raise_perror("can't create pipe");
  4846. if (redir->type == NHERE) {
  4847. len = strlen(redir->nhere.doc->narg.text);
  4848. if (len <= PIPE_BUF) {
  4849. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4850. goto out;
  4851. }
  4852. }
  4853. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4854. /* child */
  4855. close(pip[0]);
  4856. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4857. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4858. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4859. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4860. signal(SIGPIPE, SIG_DFL);
  4861. if (redir->type == NHERE)
  4862. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4863. else /* NXHERE */
  4864. expandhere(redir->nhere.doc, pip[1]);
  4865. _exit(EXIT_SUCCESS);
  4866. }
  4867. out:
  4868. close(pip[1]);
  4869. return pip[0];
  4870. }
  4871. static int
  4872. openredirect(union node *redir)
  4873. {
  4874. struct stat sb;
  4875. char *fname;
  4876. int f;
  4877. switch (redir->nfile.type) {
  4878. /* Can't happen, our single caller does this itself */
  4879. // case NTOFD:
  4880. // case NFROMFD:
  4881. // return -1;
  4882. case NHERE:
  4883. case NXHERE:
  4884. return openhere(redir);
  4885. }
  4886. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4887. * allocated space. Do it only when we know it is safe.
  4888. */
  4889. fname = redir->nfile.expfname;
  4890. switch (redir->nfile.type) {
  4891. default:
  4892. #if DEBUG
  4893. abort();
  4894. #endif
  4895. case NFROM:
  4896. f = open(fname, O_RDONLY);
  4897. if (f < 0)
  4898. goto eopen;
  4899. break;
  4900. case NFROMTO:
  4901. f = open(fname, O_RDWR|O_CREAT, 0666);
  4902. if (f < 0)
  4903. goto ecreate;
  4904. break;
  4905. case NTO:
  4906. #if BASH_REDIR_OUTPUT
  4907. case NTO2:
  4908. #endif
  4909. /* Take care of noclobber mode. */
  4910. if (Cflag) {
  4911. if (stat(fname, &sb) < 0) {
  4912. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4913. if (f < 0)
  4914. goto ecreate;
  4915. } else if (!S_ISREG(sb.st_mode)) {
  4916. f = open(fname, O_WRONLY, 0666);
  4917. if (f < 0)
  4918. goto ecreate;
  4919. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  4920. close(f);
  4921. errno = EEXIST;
  4922. goto ecreate;
  4923. }
  4924. } else {
  4925. errno = EEXIST;
  4926. goto ecreate;
  4927. }
  4928. break;
  4929. }
  4930. /* FALLTHROUGH */
  4931. case NCLOBBER:
  4932. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4933. if (f < 0)
  4934. goto ecreate;
  4935. break;
  4936. case NAPPEND:
  4937. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4938. if (f < 0)
  4939. goto ecreate;
  4940. break;
  4941. }
  4942. return f;
  4943. ecreate:
  4944. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4945. eopen:
  4946. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4947. }
  4948. /*
  4949. * Copy a file descriptor to be >= 10. Throws exception on error.
  4950. */
  4951. static int
  4952. savefd(int from)
  4953. {
  4954. int newfd;
  4955. int err;
  4956. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  4957. err = newfd < 0 ? errno : 0;
  4958. if (err != EBADF) {
  4959. if (err)
  4960. ash_msg_and_raise_perror("%d", from);
  4961. close(from);
  4962. if (F_DUPFD_CLOEXEC == F_DUPFD)
  4963. close_on_exec_on(newfd);
  4964. }
  4965. return newfd;
  4966. }
  4967. static int
  4968. dup2_or_raise(int from, int to)
  4969. {
  4970. int newfd;
  4971. newfd = (from != to) ? dup2(from, to) : to;
  4972. if (newfd < 0) {
  4973. /* Happens when source fd is not open: try "echo >&99" */
  4974. ash_msg_and_raise_perror("%d", from);
  4975. }
  4976. return newfd;
  4977. }
  4978. static int
  4979. dup_CLOEXEC(int fd, int avoid_fd)
  4980. {
  4981. int newfd;
  4982. repeat:
  4983. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  4984. if (newfd >= 0) {
  4985. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  4986. close_on_exec_on(newfd);
  4987. } else { /* newfd < 0 */
  4988. if (errno == EBUSY)
  4989. goto repeat;
  4990. if (errno == EINTR)
  4991. goto repeat;
  4992. }
  4993. return newfd;
  4994. }
  4995. static int
  4996. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  4997. {
  4998. int newfd;
  4999. repeat:
  5000. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5001. if (newfd < 0) {
  5002. if (errno == EBUSY)
  5003. goto repeat;
  5004. if (errno == EINTR)
  5005. goto repeat;
  5006. /* fd was not open? */
  5007. if (errno == EBADF)
  5008. return fd;
  5009. ash_msg_and_raise_perror("%d", newfd);
  5010. }
  5011. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5012. close_on_exec_on(newfd);
  5013. close(fd);
  5014. return newfd;
  5015. }
  5016. /* Struct def and variable are moved down to the first usage site */
  5017. struct squirrel {
  5018. int orig_fd;
  5019. int moved_to;
  5020. };
  5021. struct redirtab {
  5022. struct redirtab *next;
  5023. int pair_count;
  5024. struct squirrel two_fd[];
  5025. };
  5026. #define redirlist (G_var.redirlist)
  5027. static void
  5028. add_squirrel_closed(struct redirtab *sq, int fd)
  5029. {
  5030. int i;
  5031. if (!sq)
  5032. return;
  5033. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5034. /* If we collide with an already moved fd... */
  5035. if (fd == sq->two_fd[i].orig_fd) {
  5036. /* Examples:
  5037. * "echo 3>FILE 3>&- 3>FILE"
  5038. * "echo 3>&- 3>FILE"
  5039. * No need for last redirect to insert
  5040. * another "need to close 3" indicator.
  5041. */
  5042. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5043. return;
  5044. }
  5045. }
  5046. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5047. sq->two_fd[i].orig_fd = fd;
  5048. sq->two_fd[i].moved_to = CLOSED;
  5049. }
  5050. static int
  5051. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5052. {
  5053. int i, new_fd;
  5054. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5055. avoid_fd = 9;
  5056. #if JOBS
  5057. if (fd == ttyfd) {
  5058. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5059. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5060. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5061. return 1; /* "we closed fd" */
  5062. }
  5063. #endif
  5064. /* Are we called from redirect(0)? E.g. redirect
  5065. * in a forked child. No need to save fds,
  5066. * we aren't going to use them anymore, ok to trash.
  5067. */
  5068. if (!sq)
  5069. return 0;
  5070. /* If this one of script's fds? */
  5071. if (fd != 0) {
  5072. struct parsefile *pf = g_parsefile;
  5073. while (pf) {
  5074. /* We skip fd == 0 case because of the following:
  5075. * $ ash # running ash interactively
  5076. * $ . ./script.sh
  5077. * and in script.sh: "exec 9>&0".
  5078. * Even though top-level pf_fd _is_ 0,
  5079. * it's still ok to use it: "read" builtin uses it,
  5080. * why should we cripple "exec" builtin?
  5081. */
  5082. if (fd == pf->pf_fd) {
  5083. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5084. return 1; /* "we closed fd" */
  5085. }
  5086. pf = pf->prev;
  5087. }
  5088. }
  5089. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5090. /* First: do we collide with some already moved fds? */
  5091. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5092. /* If we collide with an already moved fd... */
  5093. if (fd == sq->two_fd[i].moved_to) {
  5094. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5095. sq->two_fd[i].moved_to = new_fd;
  5096. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5097. if (new_fd < 0) /* what? */
  5098. xfunc_die();
  5099. return 0; /* "we did not close fd" */
  5100. }
  5101. if (fd == sq->two_fd[i].orig_fd) {
  5102. /* Example: echo Hello >/dev/null 1>&2 */
  5103. TRACE(("redirect_fd %d: already moved\n", fd));
  5104. return 0; /* "we did not close fd" */
  5105. }
  5106. }
  5107. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5108. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5109. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5110. if (new_fd < 0) {
  5111. if (errno != EBADF)
  5112. xfunc_die();
  5113. /* new_fd = CLOSED; - already is -1 */
  5114. }
  5115. sq->two_fd[i].moved_to = new_fd;
  5116. sq->two_fd[i].orig_fd = fd;
  5117. /* if we move stderr, let "set -x" code know */
  5118. if (fd == preverrout_fd)
  5119. preverrout_fd = new_fd;
  5120. return 0; /* "we did not close fd" */
  5121. }
  5122. static int
  5123. internally_opened_fd(int fd, struct redirtab *sq)
  5124. {
  5125. int i;
  5126. #if JOBS
  5127. if (fd == ttyfd)
  5128. return 1;
  5129. #endif
  5130. /* If this one of script's fds? */
  5131. if (fd != 0) {
  5132. struct parsefile *pf = g_parsefile;
  5133. while (pf) {
  5134. if (fd == pf->pf_fd)
  5135. return 1;
  5136. pf = pf->prev;
  5137. }
  5138. }
  5139. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5140. if (fd == sq->two_fd[i].moved_to)
  5141. return 1;
  5142. }
  5143. return 0;
  5144. }
  5145. /*
  5146. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5147. * old file descriptors are stashed away so that the redirection can be
  5148. * undone by calling popredir.
  5149. */
  5150. /* flags passed to redirect */
  5151. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5152. static void
  5153. redirect(union node *redir, int flags)
  5154. {
  5155. struct redirtab *sv;
  5156. if (!redir)
  5157. return;
  5158. sv = NULL;
  5159. INT_OFF;
  5160. if (flags & REDIR_PUSH)
  5161. sv = redirlist;
  5162. do {
  5163. int fd;
  5164. int newfd;
  5165. int close_fd;
  5166. int closed;
  5167. fd = redir->nfile.fd;
  5168. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5169. //bb_error_msg("doing %d > %d", fd, newfd);
  5170. newfd = redir->ndup.dupfd;
  5171. close_fd = -1;
  5172. } else {
  5173. newfd = openredirect(redir); /* always >= 0 */
  5174. if (fd == newfd) {
  5175. /* open() gave us precisely the fd we wanted.
  5176. * This means that this fd was not busy
  5177. * (not opened to anywhere).
  5178. * Remember to close it on restore:
  5179. */
  5180. add_squirrel_closed(sv, fd);
  5181. continue;
  5182. }
  5183. close_fd = newfd;
  5184. }
  5185. if (fd == newfd)
  5186. continue;
  5187. /* if "N>FILE": move newfd to fd */
  5188. /* if "N>&M": dup newfd to fd */
  5189. /* if "N>&-": close fd (newfd is -1) */
  5190. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5191. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5192. if (newfd == -1) {
  5193. /* "N>&-" means "close me" */
  5194. if (!closed) {
  5195. /* ^^^ optimization: saving may already
  5196. * have closed it. If not... */
  5197. close(fd);
  5198. }
  5199. } else {
  5200. /* if newfd is a script fd or saved fd, simulate EBADF */
  5201. if (internally_opened_fd(newfd, sv)) {
  5202. errno = EBADF;
  5203. ash_msg_and_raise_perror("%d", newfd);
  5204. }
  5205. dup2_or_raise(newfd, fd);
  5206. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5207. close(close_fd);
  5208. #if BASH_REDIR_OUTPUT
  5209. if (redir->nfile.type == NTO2 && fd == 1) {
  5210. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5211. fd = 2;
  5212. newfd = 1;
  5213. close_fd = -1;
  5214. goto redirect_more;
  5215. }
  5216. #endif
  5217. }
  5218. } while ((redir = redir->nfile.next) != NULL);
  5219. INT_ON;
  5220. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5221. #define REDIR_SAVEFD2 0
  5222. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5223. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5224. // not only for calls with flags containing REDIR_SAVEFD2.
  5225. // We do this unconditionally (see save_fd_on_redirect()).
  5226. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5227. // preverrout_fd = copied_fd2;
  5228. }
  5229. static int
  5230. redirectsafe(union node *redir, int flags)
  5231. {
  5232. int err;
  5233. volatile int saveint;
  5234. struct jmploc *volatile savehandler = exception_handler;
  5235. struct jmploc jmploc;
  5236. SAVE_INT(saveint);
  5237. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5238. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5239. if (!err) {
  5240. exception_handler = &jmploc;
  5241. redirect(redir, flags);
  5242. }
  5243. exception_handler = savehandler;
  5244. if (err && exception_type != EXERROR)
  5245. longjmp(exception_handler->loc, 1);
  5246. RESTORE_INT(saveint);
  5247. return err;
  5248. }
  5249. static struct redirtab*
  5250. pushredir(union node *redir)
  5251. {
  5252. struct redirtab *sv;
  5253. int i;
  5254. if (!redir)
  5255. return redirlist;
  5256. i = 0;
  5257. do {
  5258. i++;
  5259. #if BASH_REDIR_OUTPUT
  5260. if (redir->nfile.type == NTO2)
  5261. i++;
  5262. #endif
  5263. redir = redir->nfile.next;
  5264. } while (redir);
  5265. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5266. sv->pair_count = i;
  5267. while (--i >= 0)
  5268. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5269. sv->next = redirlist;
  5270. redirlist = sv;
  5271. return sv->next;
  5272. }
  5273. /*
  5274. * Undo the effects of the last redirection.
  5275. */
  5276. static void
  5277. popredir(int drop)
  5278. {
  5279. struct redirtab *rp;
  5280. int i;
  5281. if (redirlist == NULL)
  5282. return;
  5283. INT_OFF;
  5284. rp = redirlist;
  5285. for (i = 0; i < rp->pair_count; i++) {
  5286. int fd = rp->two_fd[i].orig_fd;
  5287. int copy = rp->two_fd[i].moved_to;
  5288. if (copy == CLOSED) {
  5289. if (!drop)
  5290. close(fd);
  5291. continue;
  5292. }
  5293. if (copy != EMPTY) {
  5294. if (!drop) {
  5295. /*close(fd);*/
  5296. dup2_or_raise(copy, fd);
  5297. }
  5298. close(copy);
  5299. }
  5300. }
  5301. redirlist = rp->next;
  5302. free(rp);
  5303. INT_ON;
  5304. }
  5305. static void
  5306. unwindredir(struct redirtab *stop)
  5307. {
  5308. while (redirlist != stop)
  5309. popredir(/*drop:*/ 0);
  5310. }
  5311. /* ============ Routines to expand arguments to commands
  5312. *
  5313. * We have to deal with backquotes, shell variables, and file metacharacters.
  5314. */
  5315. #if ENABLE_FEATURE_SH_MATH
  5316. static arith_t
  5317. ash_arith(const char *s)
  5318. {
  5319. arith_state_t math_state;
  5320. arith_t result;
  5321. math_state.lookupvar = lookupvar;
  5322. math_state.setvar = setvar0;
  5323. //math_state.endofname = endofname;
  5324. INT_OFF;
  5325. result = arith(&math_state, s);
  5326. if (math_state.errmsg)
  5327. ash_msg_and_raise_error(math_state.errmsg);
  5328. INT_ON;
  5329. return result;
  5330. }
  5331. #endif
  5332. #if BASH_SUBSTR
  5333. # if ENABLE_FEATURE_SH_MATH
  5334. static int substr_atoi(const char *s)
  5335. {
  5336. arith_t t = ash_arith(s);
  5337. if (sizeof(t) > sizeof(int)) {
  5338. /* clamp very large or very large negative nums for ${v:N:M}:
  5339. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5340. */
  5341. if (t > INT_MAX)
  5342. t = INT_MAX;
  5343. if (t < INT_MIN)
  5344. t = INT_MIN;
  5345. }
  5346. return t;
  5347. }
  5348. # else
  5349. # define substr_atoi(s) number(s)
  5350. # endif
  5351. #endif
  5352. /*
  5353. * expandarg flags
  5354. */
  5355. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5356. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5357. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5358. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5359. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5360. * POSIX says for this case:
  5361. * Pathname expansion shall not be performed on the word by a
  5362. * non-interactive shell; an interactive shell may perform it, but shall
  5363. * do so only when the expansion would result in one word.
  5364. * Currently, our code complies to the above rule by never globbing
  5365. * redirection filenames.
  5366. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5367. * (this means that on a typical Linux distro, bash almost always
  5368. * performs globbing, and thus diverges from what we do).
  5369. */
  5370. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5371. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5372. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5373. #define EXP_QUOTED 0x80 /* expand word in double quotes */
  5374. /*
  5375. * rmescape() flags
  5376. */
  5377. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5378. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5379. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5380. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5381. /* Add CTLESC when necessary. */
  5382. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5383. /* Do not skip NUL characters. */
  5384. #define QUOTES_KEEPNUL EXP_TILDE
  5385. /*
  5386. * Structure specifying which parts of the string should be searched
  5387. * for IFS characters.
  5388. */
  5389. struct ifsregion {
  5390. struct ifsregion *next; /* next region in list */
  5391. int begoff; /* offset of start of region */
  5392. int endoff; /* offset of end of region */
  5393. int nulonly; /* search for nul bytes only */
  5394. };
  5395. struct arglist {
  5396. struct strlist *list;
  5397. struct strlist **lastp;
  5398. };
  5399. /* output of current string */
  5400. static char *expdest;
  5401. /* list of back quote expressions */
  5402. static struct nodelist *argbackq;
  5403. /* first struct in list of ifs regions */
  5404. static struct ifsregion ifsfirst;
  5405. /* last struct in list */
  5406. static struct ifsregion *ifslastp;
  5407. /* holds expanded arg list */
  5408. static struct arglist exparg;
  5409. /*
  5410. * Our own itoa().
  5411. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5412. */
  5413. static int
  5414. cvtnum(arith_t num)
  5415. {
  5416. int len;
  5417. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5418. len = sizeof(arith_t) * 3;
  5419. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5420. if (sizeof(arith_t) < 4) len += 2;
  5421. expdest = makestrspace(len, expdest);
  5422. len = fmtstr(expdest, len, ARITH_FMT, num);
  5423. STADJUST(len, expdest);
  5424. return len;
  5425. }
  5426. /*
  5427. * Break the argument string into pieces based upon IFS and add the
  5428. * strings to the argument list. The regions of the string to be
  5429. * searched for IFS characters have been stored by recordregion.
  5430. */
  5431. static void
  5432. ifsbreakup(char *string, struct arglist *arglist)
  5433. {
  5434. struct ifsregion *ifsp;
  5435. struct strlist *sp;
  5436. char *start;
  5437. char *p;
  5438. char *q;
  5439. const char *ifs, *realifs;
  5440. int ifsspc;
  5441. int nulonly;
  5442. start = string;
  5443. if (ifslastp != NULL) {
  5444. ifsspc = 0;
  5445. nulonly = 0;
  5446. realifs = ifsset() ? ifsval() : defifs;
  5447. ifsp = &ifsfirst;
  5448. do {
  5449. int afternul;
  5450. p = string + ifsp->begoff;
  5451. afternul = nulonly;
  5452. nulonly = ifsp->nulonly;
  5453. ifs = nulonly ? nullstr : realifs;
  5454. ifsspc = 0;
  5455. while (p < string + ifsp->endoff) {
  5456. q = p;
  5457. if ((unsigned char)*p == CTLESC)
  5458. p++;
  5459. if (!strchr(ifs, *p)) {
  5460. p++;
  5461. continue;
  5462. }
  5463. if (!(afternul || nulonly))
  5464. ifsspc = (strchr(defifs, *p) != NULL);
  5465. /* Ignore IFS whitespace at start */
  5466. if (q == start && ifsspc) {
  5467. p++;
  5468. start = p;
  5469. continue;
  5470. }
  5471. *q = '\0';
  5472. sp = stzalloc(sizeof(*sp));
  5473. sp->text = start;
  5474. *arglist->lastp = sp;
  5475. arglist->lastp = &sp->next;
  5476. p++;
  5477. if (!nulonly) {
  5478. for (;;) {
  5479. if (p >= string + ifsp->endoff) {
  5480. break;
  5481. }
  5482. q = p;
  5483. if ((unsigned char)*p == CTLESC)
  5484. p++;
  5485. if (strchr(ifs, *p) == NULL) {
  5486. p = q;
  5487. break;
  5488. }
  5489. if (strchr(defifs, *p) == NULL) {
  5490. if (ifsspc) {
  5491. p++;
  5492. ifsspc = 0;
  5493. } else {
  5494. p = q;
  5495. break;
  5496. }
  5497. } else
  5498. p++;
  5499. }
  5500. }
  5501. start = p;
  5502. } /* while */
  5503. ifsp = ifsp->next;
  5504. } while (ifsp != NULL);
  5505. if (nulonly)
  5506. goto add;
  5507. }
  5508. if (!*start)
  5509. return;
  5510. add:
  5511. sp = stzalloc(sizeof(*sp));
  5512. sp->text = start;
  5513. *arglist->lastp = sp;
  5514. arglist->lastp = &sp->next;
  5515. }
  5516. static void
  5517. ifsfree(void)
  5518. {
  5519. struct ifsregion *p = ifsfirst.next;
  5520. if (!p)
  5521. goto out;
  5522. INT_OFF;
  5523. do {
  5524. struct ifsregion *ifsp;
  5525. ifsp = p->next;
  5526. free(p);
  5527. p = ifsp;
  5528. } while (p);
  5529. ifsfirst.next = NULL;
  5530. INT_ON;
  5531. out:
  5532. ifslastp = NULL;
  5533. }
  5534. static size_t
  5535. esclen(const char *start, const char *p)
  5536. {
  5537. size_t esc = 0;
  5538. while (p > start && (unsigned char)*--p == CTLESC) {
  5539. esc++;
  5540. }
  5541. return esc;
  5542. }
  5543. /*
  5544. * Remove any CTLESC characters from a string.
  5545. */
  5546. #if !BASH_PATTERN_SUBST
  5547. #define rmescapes(str, flag, slash_position) \
  5548. rmescapes(str, flag)
  5549. #endif
  5550. static char *
  5551. rmescapes(char *str, int flag, int *slash_position)
  5552. {
  5553. static const char qchars[] ALIGN1 = {
  5554. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5555. char *p, *q, *r;
  5556. unsigned protect_against_glob;
  5557. unsigned globbing;
  5558. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5559. if (!p)
  5560. return str;
  5561. q = p;
  5562. r = str;
  5563. if (flag & RMESCAPE_ALLOC) {
  5564. size_t len = p - str;
  5565. size_t fulllen = len + strlen(p) + 1;
  5566. if (flag & RMESCAPE_GROW) {
  5567. int strloc = str - (char *)stackblock();
  5568. r = makestrspace(fulllen, expdest);
  5569. /* p and str may be invalidated by makestrspace */
  5570. str = (char *)stackblock() + strloc;
  5571. p = str + len;
  5572. } else if (flag & RMESCAPE_HEAP) {
  5573. r = ckmalloc(fulllen);
  5574. } else {
  5575. r = stalloc(fulllen);
  5576. }
  5577. q = r;
  5578. if (len > 0) {
  5579. q = (char *)mempcpy(q, str, len);
  5580. }
  5581. }
  5582. globbing = flag & RMESCAPE_GLOB;
  5583. protect_against_glob = globbing;
  5584. while (*p) {
  5585. if ((unsigned char)*p == CTLQUOTEMARK) {
  5586. // Note: protect_against_glob only affect whether
  5587. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5588. p++;
  5589. protect_against_glob = globbing;
  5590. continue;
  5591. }
  5592. if (*p == '\\') {
  5593. /* naked back slash */
  5594. protect_against_glob = 0;
  5595. goto copy;
  5596. }
  5597. if ((unsigned char)*p == CTLESC) {
  5598. p++;
  5599. #if DEBUG
  5600. if (*p == '\0')
  5601. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5602. #endif
  5603. if (protect_against_glob) {
  5604. /*
  5605. * We used to trust glob() and fnmatch() to eat
  5606. * superfluous escapes (\z where z has no
  5607. * special meaning anyway). But this causes
  5608. * bugs such as string of one greek letter rho
  5609. * (unicode-encoded as two bytes "cf,81")
  5610. * getting encoded as "cf,CTLESC,81"
  5611. * and here, converted to "cf,\,81" -
  5612. * which does not go well with some flavors
  5613. * of fnmatch() in unicode locales
  5614. * (for example, glibc <= 2.22).
  5615. *
  5616. * Lets add "\" only on the chars which need it.
  5617. * Testcases for less obvious chars are shown.
  5618. */
  5619. if (*p == '*'
  5620. || *p == '?'
  5621. || *p == '['
  5622. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5623. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5624. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5625. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5626. /* Some libc support [^negate], that's why "^" also needs love */
  5627. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5628. ) {
  5629. *q++ = '\\';
  5630. }
  5631. }
  5632. }
  5633. #if BASH_PATTERN_SUBST
  5634. else if (slash_position && p == str + *slash_position) {
  5635. /* stop handling globbing */
  5636. globbing = 0;
  5637. *slash_position = q - r;
  5638. slash_position = NULL;
  5639. }
  5640. #endif
  5641. protect_against_glob = globbing;
  5642. copy:
  5643. *q++ = *p++;
  5644. }
  5645. *q = '\0';
  5646. if (flag & RMESCAPE_GROW) {
  5647. expdest = r;
  5648. STADJUST(q - r + 1, expdest);
  5649. }
  5650. return r;
  5651. }
  5652. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5653. /*
  5654. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5655. *
  5656. * Returns an stalloced string.
  5657. */
  5658. static char *
  5659. preglob(const char *pattern, int flag)
  5660. {
  5661. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5662. }
  5663. /*
  5664. * Put a string on the stack.
  5665. */
  5666. static void
  5667. memtodest(const char *p, size_t len, int syntax, int quotes)
  5668. {
  5669. char *q;
  5670. if (!len)
  5671. return;
  5672. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5673. do {
  5674. unsigned char c = *p++;
  5675. if (c) {
  5676. if (quotes & QUOTES_ESC) {
  5677. int n = SIT(c, syntax);
  5678. if (n == CCTL
  5679. || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
  5680. && n == CBACK
  5681. )
  5682. ) {
  5683. USTPUTC(CTLESC, q);
  5684. }
  5685. }
  5686. } else if (!(quotes & QUOTES_KEEPNUL))
  5687. continue;
  5688. USTPUTC(c, q);
  5689. } while (--len);
  5690. expdest = q;
  5691. }
  5692. static size_t
  5693. strtodest(const char *p, int syntax, int quotes)
  5694. {
  5695. size_t len = strlen(p);
  5696. memtodest(p, len, syntax, quotes);
  5697. return len;
  5698. }
  5699. /*
  5700. * Record the fact that we have to scan this region of the
  5701. * string for IFS characters.
  5702. */
  5703. static void
  5704. recordregion(int start, int end, int nulonly)
  5705. {
  5706. struct ifsregion *ifsp;
  5707. if (ifslastp == NULL) {
  5708. ifsp = &ifsfirst;
  5709. } else {
  5710. INT_OFF;
  5711. ifsp = ckzalloc(sizeof(*ifsp));
  5712. /*ifsp->next = NULL; - ckzalloc did it */
  5713. ifslastp->next = ifsp;
  5714. INT_ON;
  5715. }
  5716. ifslastp = ifsp;
  5717. ifslastp->begoff = start;
  5718. ifslastp->endoff = end;
  5719. ifslastp->nulonly = nulonly;
  5720. }
  5721. static void
  5722. removerecordregions(int endoff)
  5723. {
  5724. if (ifslastp == NULL)
  5725. return;
  5726. if (ifsfirst.endoff > endoff) {
  5727. while (ifsfirst.next) {
  5728. struct ifsregion *ifsp;
  5729. INT_OFF;
  5730. ifsp = ifsfirst.next->next;
  5731. free(ifsfirst.next);
  5732. ifsfirst.next = ifsp;
  5733. INT_ON;
  5734. }
  5735. if (ifsfirst.begoff > endoff) {
  5736. ifslastp = NULL;
  5737. } else {
  5738. ifslastp = &ifsfirst;
  5739. ifsfirst.endoff = endoff;
  5740. }
  5741. return;
  5742. }
  5743. ifslastp = &ifsfirst;
  5744. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5745. ifslastp = ifslastp->next;
  5746. while (ifslastp->next) {
  5747. struct ifsregion *ifsp;
  5748. INT_OFF;
  5749. ifsp = ifslastp->next->next;
  5750. free(ifslastp->next);
  5751. ifslastp->next = ifsp;
  5752. INT_ON;
  5753. }
  5754. if (ifslastp->endoff > endoff)
  5755. ifslastp->endoff = endoff;
  5756. }
  5757. static char *
  5758. exptilde(char *startp, char *p, int flags)
  5759. {
  5760. unsigned char c;
  5761. char *name;
  5762. struct passwd *pw;
  5763. const char *home;
  5764. int quotes = flags & QUOTES_ESC;
  5765. name = p + 1;
  5766. while ((c = *++p) != '\0') {
  5767. switch (c) {
  5768. case CTLESC:
  5769. return startp;
  5770. case CTLQUOTEMARK:
  5771. return startp;
  5772. case ':':
  5773. if (flags & EXP_VARTILDE)
  5774. goto done;
  5775. break;
  5776. case '/':
  5777. case CTLENDVAR:
  5778. goto done;
  5779. }
  5780. }
  5781. done:
  5782. *p = '\0';
  5783. if (*name == '\0') {
  5784. home = lookupvar("HOME");
  5785. } else {
  5786. pw = getpwnam(name);
  5787. if (pw == NULL)
  5788. goto lose;
  5789. home = pw->pw_dir;
  5790. }
  5791. if (!home || !*home)
  5792. goto lose;
  5793. *p = c;
  5794. strtodest(home, SQSYNTAX, quotes);
  5795. return p;
  5796. lose:
  5797. *p = c;
  5798. return startp;
  5799. }
  5800. /*
  5801. * Execute a command inside back quotes. If it's a builtin command, we
  5802. * want to save its output in a block obtained from malloc. Otherwise
  5803. * we fork off a subprocess and get the output of the command via a pipe.
  5804. * Should be called with interrupts off.
  5805. */
  5806. struct backcmd { /* result of evalbackcmd */
  5807. int fd; /* file descriptor to read from */
  5808. int nleft; /* number of chars in buffer */
  5809. char *buf; /* buffer */
  5810. struct job *jp; /* job structure for command */
  5811. };
  5812. /* These forward decls are needed to use "eval" code for backticks handling: */
  5813. /* flags in argument to evaltree */
  5814. #define EV_EXIT 01 /* exit after evaluating tree */
  5815. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5816. static int evaltree(union node *, int);
  5817. /* An evaltree() which is known to never return.
  5818. * Used to use an alias:
  5819. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5820. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5821. */
  5822. static ALWAYS_INLINE NORETURN void
  5823. evaltreenr(union node *n, int flags)
  5824. {
  5825. evaltree(n, flags);
  5826. bb_unreachable(abort());
  5827. /* NOTREACHED */
  5828. }
  5829. static void FAST_FUNC
  5830. evalbackcmd(union node *n, struct backcmd *result)
  5831. {
  5832. int pip[2];
  5833. struct job *jp;
  5834. result->fd = -1;
  5835. result->buf = NULL;
  5836. result->nleft = 0;
  5837. result->jp = NULL;
  5838. if (n == NULL) {
  5839. goto out;
  5840. }
  5841. if (pipe(pip) < 0)
  5842. ash_msg_and_raise_perror("can't create pipe");
  5843. jp = makejob(/*n,*/ 1);
  5844. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5845. /* child */
  5846. FORCE_INT_ON;
  5847. close(pip[0]);
  5848. if (pip[1] != 1) {
  5849. /*close(1);*/
  5850. dup2_or_raise(pip[1], 1);
  5851. close(pip[1]);
  5852. }
  5853. /* TODO: eflag clearing makes the following not abort:
  5854. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5855. * which is what bash does (unless it is in POSIX mode).
  5856. * dash deleted "eflag = 0" line in the commit
  5857. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5858. * [EVAL] Don't clear eflag in evalbackcmd
  5859. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5860. */
  5861. eflag = 0;
  5862. ifsfree();
  5863. evaltreenr(n, EV_EXIT);
  5864. /* NOTREACHED */
  5865. }
  5866. /* parent */
  5867. close(pip[1]);
  5868. result->fd = pip[0];
  5869. result->jp = jp;
  5870. out:
  5871. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5872. result->fd, result->buf, result->nleft, result->jp));
  5873. }
  5874. /*
  5875. * Expand stuff in backwards quotes.
  5876. */
  5877. static void
  5878. expbackq(union node *cmd, int flag)
  5879. {
  5880. struct backcmd in;
  5881. int i;
  5882. char buf[128];
  5883. char *p;
  5884. char *dest;
  5885. int startloc;
  5886. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5887. struct stackmark smark;
  5888. INT_OFF;
  5889. startloc = expdest - (char *)stackblock();
  5890. pushstackmark(&smark, startloc);
  5891. evalbackcmd(cmd, &in);
  5892. popstackmark(&smark);
  5893. p = in.buf;
  5894. i = in.nleft;
  5895. if (i == 0)
  5896. goto read;
  5897. for (;;) {
  5898. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5899. read:
  5900. if (in.fd < 0)
  5901. break;
  5902. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5903. TRACE(("expbackq: read returns %d\n", i));
  5904. if (i <= 0)
  5905. break;
  5906. p = buf;
  5907. }
  5908. free(in.buf);
  5909. if (in.fd >= 0) {
  5910. close(in.fd);
  5911. back_exitstatus = waitforjob(in.jp);
  5912. }
  5913. INT_ON;
  5914. /* Eat all trailing newlines */
  5915. dest = expdest;
  5916. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5917. STUNPUTC(dest);
  5918. expdest = dest;
  5919. if (!(flag & EXP_QUOTED))
  5920. recordregion(startloc, dest - (char *)stackblock(), 0);
  5921. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5922. (int)((dest - (char *)stackblock()) - startloc),
  5923. (int)((dest - (char *)stackblock()) - startloc),
  5924. stackblock() + startloc));
  5925. }
  5926. #if ENABLE_FEATURE_SH_MATH
  5927. /*
  5928. * Expand arithmetic expression. Backup to start of expression,
  5929. * evaluate, place result in (backed up) result, adjust string position.
  5930. */
  5931. static void
  5932. expari(int flag)
  5933. {
  5934. char *p, *start;
  5935. int begoff;
  5936. int len;
  5937. /* ifsfree(); */
  5938. /*
  5939. * This routine is slightly over-complicated for
  5940. * efficiency. Next we scan backwards looking for the
  5941. * start of arithmetic.
  5942. */
  5943. start = stackblock();
  5944. p = expdest - 1;
  5945. *p = '\0';
  5946. p--;
  5947. while (1) {
  5948. int esc;
  5949. while ((unsigned char)*p != CTLARI) {
  5950. p--;
  5951. #if DEBUG
  5952. if (p < start) {
  5953. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5954. }
  5955. #endif
  5956. }
  5957. esc = esclen(start, p);
  5958. if (!(esc % 2)) {
  5959. break;
  5960. }
  5961. p -= esc + 1;
  5962. }
  5963. begoff = p - start;
  5964. removerecordregions(begoff);
  5965. expdest = p;
  5966. if (flag & QUOTES_ESC)
  5967. rmescapes(p + 1, 0, NULL);
  5968. len = cvtnum(ash_arith(p + 1));
  5969. if (!(flag & EXP_QUOTED))
  5970. recordregion(begoff, begoff + len, 0);
  5971. }
  5972. #endif
  5973. /* argstr needs it */
  5974. static char *evalvar(char *p, int flags);
  5975. /*
  5976. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5977. * characters to allow for further processing. Otherwise treat
  5978. * $@ like $* since no splitting will be performed.
  5979. */
  5980. static void
  5981. argstr(char *p, int flags)
  5982. {
  5983. static const char spclchars[] ALIGN1 = {
  5984. '=',
  5985. ':',
  5986. CTLQUOTEMARK,
  5987. CTLENDVAR,
  5988. CTLESC,
  5989. CTLVAR,
  5990. CTLBACKQ,
  5991. #if ENABLE_FEATURE_SH_MATH
  5992. CTLENDARI,
  5993. #endif
  5994. '\0'
  5995. };
  5996. const char *reject = spclchars;
  5997. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5998. int inquotes;
  5999. size_t length;
  6000. int startloc;
  6001. if (!(flags & EXP_VARTILDE)) {
  6002. reject += 2;
  6003. } else if (flags & EXP_VARTILDE2) {
  6004. reject++;
  6005. }
  6006. inquotes = 0;
  6007. length = 0;
  6008. if (flags & EXP_TILDE) {
  6009. char *q;
  6010. flags &= ~EXP_TILDE;
  6011. tilde:
  6012. q = p;
  6013. if (*q == '~')
  6014. p = exptilde(p, q, flags);
  6015. }
  6016. start:
  6017. startloc = expdest - (char *)stackblock();
  6018. for (;;) {
  6019. unsigned char c;
  6020. length += strcspn(p + length, reject);
  6021. c = p[length];
  6022. if (c) {
  6023. if (!(c & 0x80)
  6024. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6025. ) {
  6026. /* c == '=' || c == ':' || c == CTLENDARI */
  6027. length++;
  6028. }
  6029. }
  6030. if (length > 0) {
  6031. int newloc;
  6032. expdest = stack_nputstr(p, length, expdest);
  6033. newloc = expdest - (char *)stackblock();
  6034. if (breakall && !inquotes && newloc > startloc) {
  6035. recordregion(startloc, newloc, 0);
  6036. }
  6037. startloc = newloc;
  6038. }
  6039. p += length + 1;
  6040. length = 0;
  6041. switch (c) {
  6042. case '\0':
  6043. goto breakloop;
  6044. case '=':
  6045. if (flags & EXP_VARTILDE2) {
  6046. p--;
  6047. continue;
  6048. }
  6049. flags |= EXP_VARTILDE2;
  6050. reject++;
  6051. /* fall through */
  6052. case ':':
  6053. /*
  6054. * sort of a hack - expand tildes in variable
  6055. * assignments (after the first '=' and after ':'s).
  6056. */
  6057. if (*--p == '~') {
  6058. goto tilde;
  6059. }
  6060. continue;
  6061. }
  6062. switch (c) {
  6063. case CTLENDVAR: /* ??? */
  6064. goto breakloop;
  6065. case CTLQUOTEMARK:
  6066. /* "$@" syntax adherence hack */
  6067. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6068. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6069. goto start;
  6070. }
  6071. inquotes ^= EXP_QUOTED;
  6072. addquote:
  6073. if (flags & QUOTES_ESC) {
  6074. p--;
  6075. length++;
  6076. startloc++;
  6077. }
  6078. break;
  6079. case CTLESC:
  6080. startloc++;
  6081. length++;
  6082. goto addquote;
  6083. case CTLVAR:
  6084. TRACE(("argstr: evalvar('%s')\n", p));
  6085. p = evalvar(p, flags | inquotes);
  6086. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6087. goto start;
  6088. case CTLBACKQ:
  6089. expbackq(argbackq->n, flags | inquotes);
  6090. argbackq = argbackq->next;
  6091. goto start;
  6092. #if ENABLE_FEATURE_SH_MATH
  6093. case CTLENDARI:
  6094. p--;
  6095. expari(flags | inquotes);
  6096. goto start;
  6097. #endif
  6098. }
  6099. }
  6100. breakloop: ;
  6101. }
  6102. static char *
  6103. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6104. char *pattern, int quotes, int zero)
  6105. {
  6106. char *loc, *loc2;
  6107. char c;
  6108. loc = startp;
  6109. loc2 = rmesc;
  6110. do {
  6111. int match;
  6112. const char *s = loc2;
  6113. c = *loc2;
  6114. if (zero) {
  6115. *loc2 = '\0';
  6116. s = rmesc;
  6117. }
  6118. match = pmatch(pattern, s);
  6119. *loc2 = c;
  6120. if (match)
  6121. return loc;
  6122. if (quotes && (unsigned char)*loc == CTLESC)
  6123. loc++;
  6124. loc++;
  6125. loc2++;
  6126. } while (c);
  6127. return NULL;
  6128. }
  6129. static char *
  6130. scanright(char *startp, char *rmesc, char *rmescend,
  6131. char *pattern, int quotes, int match_at_start)
  6132. {
  6133. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6134. int try2optimize = match_at_start;
  6135. #endif
  6136. int esc = 0;
  6137. char *loc;
  6138. char *loc2;
  6139. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6140. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6141. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6142. * Logic:
  6143. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6144. * and on each iteration they go back two/one char until they reach the beginning.
  6145. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6146. */
  6147. /* TODO: document in what other circumstances we are called. */
  6148. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6149. int match;
  6150. char c = *loc2;
  6151. const char *s = loc2;
  6152. if (match_at_start) {
  6153. *loc2 = '\0';
  6154. s = rmesc;
  6155. }
  6156. match = pmatch(pattern, s);
  6157. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6158. *loc2 = c;
  6159. if (match)
  6160. return loc;
  6161. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6162. if (try2optimize) {
  6163. /* Maybe we can optimize this:
  6164. * if pattern ends with unescaped *, we can avoid checking
  6165. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6166. * it won't match truncated "raw_value_of_" strings too.
  6167. */
  6168. unsigned plen = strlen(pattern);
  6169. /* Does it end with "*"? */
  6170. if (plen != 0 && pattern[--plen] == '*') {
  6171. /* "xxxx*" is not escaped */
  6172. /* "xxx\*" is escaped */
  6173. /* "xx\\*" is not escaped */
  6174. /* "x\\\*" is escaped */
  6175. int slashes = 0;
  6176. while (plen != 0 && pattern[--plen] == '\\')
  6177. slashes++;
  6178. if (!(slashes & 1))
  6179. break; /* ends with unescaped "*" */
  6180. }
  6181. try2optimize = 0;
  6182. }
  6183. #endif
  6184. loc--;
  6185. if (quotes) {
  6186. if (--esc < 0) {
  6187. esc = esclen(startp, loc);
  6188. }
  6189. if (esc % 2) {
  6190. esc--;
  6191. loc--;
  6192. }
  6193. }
  6194. }
  6195. return NULL;
  6196. }
  6197. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6198. static void
  6199. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6200. {
  6201. const char *msg;
  6202. const char *tail;
  6203. tail = nullstr;
  6204. msg = "parameter not set";
  6205. if (umsg) {
  6206. if ((unsigned char)*end == CTLENDVAR) {
  6207. if (varflags & VSNUL)
  6208. tail = " or null";
  6209. } else {
  6210. msg = umsg;
  6211. }
  6212. }
  6213. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6214. }
  6215. static const char *
  6216. subevalvar(char *p, char *varname, int strloc, int subtype,
  6217. int startloc, int varflags, int flag)
  6218. {
  6219. struct nodelist *saveargbackq = argbackq;
  6220. int quotes = flag & QUOTES_ESC;
  6221. char *startp;
  6222. char *loc;
  6223. char *rmesc, *rmescend;
  6224. char *str;
  6225. int amount, resetloc;
  6226. int argstr_flags;
  6227. IF_BASH_PATTERN_SUBST(int workloc;)
  6228. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6229. IF_BASH_PATTERN_SUBST(char *repl;)
  6230. int zero;
  6231. char *(*scan)(char*, char*, char*, char*, int, int);
  6232. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6233. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6234. #if BASH_PATTERN_SUBST
  6235. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6236. * argstr() call expands possible variable references in pattern:
  6237. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6238. */
  6239. repl = NULL;
  6240. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6241. /* Find '/' and replace with NUL */
  6242. repl = p;
  6243. for (;;) {
  6244. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6245. if (*repl == '\0') {
  6246. repl = NULL;
  6247. break;
  6248. }
  6249. if (*repl == '/') {
  6250. *repl = '\0';
  6251. break;
  6252. }
  6253. if ((unsigned char)*repl == CTLESC && repl[1])
  6254. repl++;
  6255. repl++;
  6256. }
  6257. }
  6258. #endif
  6259. argstr_flags = EXP_TILDE;
  6260. if (subtype != VSASSIGN
  6261. && subtype != VSQUESTION
  6262. #if BASH_SUBSTR
  6263. && subtype != VSSUBSTR
  6264. #endif
  6265. ) {
  6266. /* EXP_CASE keeps CTLESC's */
  6267. argstr_flags = EXP_TILDE | EXP_CASE;
  6268. }
  6269. argstr(p, argstr_flags);
  6270. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6271. #if BASH_PATTERN_SUBST
  6272. slash_pos = -1;
  6273. if (repl) {
  6274. slash_pos = expdest - ((char *)stackblock() + strloc);
  6275. STPUTC('/', expdest);
  6276. //bb_error_msg("repl+1:'%s'", repl + 1);
  6277. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6278. *repl = '/';
  6279. }
  6280. #endif
  6281. STPUTC('\0', expdest);
  6282. argbackq = saveargbackq;
  6283. startp = (char *)stackblock() + startloc;
  6284. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6285. switch (subtype) {
  6286. case VSASSIGN:
  6287. setvar0(varname, startp);
  6288. amount = startp - expdest;
  6289. STADJUST(amount, expdest);
  6290. return startp;
  6291. case VSQUESTION:
  6292. varunset(p, varname, startp, varflags);
  6293. /* NOTREACHED */
  6294. #if BASH_SUBSTR
  6295. case VSSUBSTR: {
  6296. int pos, len, orig_len;
  6297. char *colon;
  6298. loc = str = stackblock() + strloc;
  6299. /* Read POS in ${var:POS:LEN} */
  6300. colon = strchr(loc, ':');
  6301. if (colon) *colon = '\0';
  6302. pos = substr_atoi(loc);
  6303. if (colon) *colon = ':';
  6304. /* Read LEN in ${var:POS:LEN} */
  6305. len = str - startp - 1;
  6306. /* *loc != '\0', guaranteed by parser */
  6307. if (quotes) {
  6308. char *ptr;
  6309. /* Adjust the length by the number of escapes */
  6310. for (ptr = startp; ptr < (str - 1); ptr++) {
  6311. if ((unsigned char)*ptr == CTLESC) {
  6312. len--;
  6313. ptr++;
  6314. }
  6315. }
  6316. }
  6317. orig_len = len;
  6318. if (*loc++ == ':') {
  6319. /* ${var::LEN} */
  6320. len = substr_atoi(loc);
  6321. } else {
  6322. /* Skip POS in ${var:POS:LEN} */
  6323. len = orig_len;
  6324. while (*loc && *loc != ':')
  6325. loc++;
  6326. if (*loc++ == ':')
  6327. len = substr_atoi(loc);
  6328. }
  6329. if (pos < 0) {
  6330. /* ${VAR:$((-n)):l} starts n chars from the end */
  6331. pos = orig_len + pos;
  6332. }
  6333. if ((unsigned)pos >= orig_len) {
  6334. /* apart from obvious ${VAR:999999:l},
  6335. * covers ${VAR:$((-9999999)):l} - result is ""
  6336. * (bash compat)
  6337. */
  6338. pos = 0;
  6339. len = 0;
  6340. }
  6341. if (len < 0) {
  6342. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6343. len = (orig_len - pos) + len;
  6344. }
  6345. if ((unsigned)len > (orig_len - pos))
  6346. len = orig_len - pos;
  6347. for (str = startp; pos; str++, pos--) {
  6348. if (quotes && (unsigned char)*str == CTLESC)
  6349. str++;
  6350. }
  6351. for (loc = startp; len; len--) {
  6352. if (quotes && (unsigned char)*str == CTLESC)
  6353. *loc++ = *str++;
  6354. *loc++ = *str++;
  6355. }
  6356. *loc = '\0';
  6357. amount = loc - expdest;
  6358. STADJUST(amount, expdest);
  6359. return loc;
  6360. }
  6361. #endif /* BASH_SUBSTR */
  6362. }
  6363. resetloc = expdest - (char *)stackblock();
  6364. #if BASH_PATTERN_SUBST
  6365. repl = NULL;
  6366. /* We'll comeback here if we grow the stack while handling
  6367. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6368. * stack will need rebasing, and we'll need to remove our work
  6369. * areas each time
  6370. */
  6371. restart:
  6372. #endif
  6373. amount = expdest - ((char *)stackblock() + resetloc);
  6374. STADJUST(-amount, expdest);
  6375. startp = (char *)stackblock() + startloc;
  6376. rmesc = startp;
  6377. rmescend = (char *)stackblock() + strloc;
  6378. //bb_error_msg("str7:'%s'", rmescend);
  6379. if (quotes) {
  6380. //TODO: how to handle slash_pos here if string changes (shortens?)
  6381. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6382. if (rmesc != startp) {
  6383. rmescend = expdest;
  6384. startp = (char *)stackblock() + startloc;
  6385. }
  6386. }
  6387. rmescend--;
  6388. str = (char *)stackblock() + strloc;
  6389. /*
  6390. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6391. * The result is a_\_z_c (not a\_\_z_c)!
  6392. *
  6393. * The search pattern and replace string treat backslashes differently!
  6394. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6395. * and string. It's only used on the first call.
  6396. */
  6397. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6398. rmescapes(str, RMESCAPE_GLOB,
  6399. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6400. );
  6401. #if BASH_PATTERN_SUBST
  6402. workloc = expdest - (char *)stackblock();
  6403. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6404. int len;
  6405. char *idx, *end;
  6406. if (!repl) {
  6407. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6408. repl = nullstr;
  6409. if (slash_pos >= 0) {
  6410. repl = str + slash_pos;
  6411. *repl++ = '\0';
  6412. }
  6413. }
  6414. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6415. /* If there's no pattern to match, return the expansion unmolested */
  6416. if (str[0] == '\0')
  6417. return NULL;
  6418. len = 0;
  6419. idx = startp;
  6420. end = str - 1;
  6421. while (idx < end) {
  6422. try_to_match:
  6423. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6424. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6425. if (!loc) {
  6426. /* No match, advance */
  6427. char *restart_detect = stackblock();
  6428. skip_matching:
  6429. STPUTC(*idx, expdest);
  6430. if (quotes && (unsigned char)*idx == CTLESC) {
  6431. idx++;
  6432. len++;
  6433. STPUTC(*idx, expdest);
  6434. }
  6435. if (stackblock() != restart_detect)
  6436. goto restart;
  6437. idx++;
  6438. len++;
  6439. rmesc++;
  6440. /* continue; - prone to quadratic behavior, smarter code: */
  6441. if (idx >= end)
  6442. break;
  6443. if (str[0] == '*') {
  6444. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6445. * it would never match "ong_string" etc, no point in trying.
  6446. */
  6447. goto skip_matching;
  6448. }
  6449. goto try_to_match;
  6450. }
  6451. if (subtype == VSREPLACEALL) {
  6452. while (idx < loc) {
  6453. if (quotes && (unsigned char)*idx == CTLESC)
  6454. idx++;
  6455. idx++;
  6456. rmesc++;
  6457. }
  6458. } else {
  6459. idx = loc;
  6460. }
  6461. //bb_error_msg("repl:'%s'", repl);
  6462. for (loc = (char*)repl; *loc; loc++) {
  6463. char *restart_detect = stackblock();
  6464. if (quotes && *loc == '\\') {
  6465. STPUTC(CTLESC, expdest);
  6466. len++;
  6467. }
  6468. STPUTC(*loc, expdest);
  6469. if (stackblock() != restart_detect)
  6470. goto restart;
  6471. len++;
  6472. }
  6473. if (subtype == VSREPLACE) {
  6474. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6475. while (*idx) {
  6476. char *restart_detect = stackblock();
  6477. STPUTC(*idx, expdest);
  6478. if (stackblock() != restart_detect)
  6479. goto restart;
  6480. len++;
  6481. idx++;
  6482. }
  6483. break;
  6484. }
  6485. }
  6486. /* We've put the replaced text into a buffer at workloc, now
  6487. * move it to the right place and adjust the stack.
  6488. */
  6489. STPUTC('\0', expdest);
  6490. startp = (char *)stackblock() + startloc;
  6491. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6492. //bb_error_msg("startp:'%s'", startp);
  6493. amount = expdest - (startp + len);
  6494. STADJUST(-amount, expdest);
  6495. return startp;
  6496. }
  6497. #endif /* BASH_PATTERN_SUBST */
  6498. subtype -= VSTRIMRIGHT;
  6499. #if DEBUG
  6500. if (subtype < 0 || subtype > 7)
  6501. abort();
  6502. #endif
  6503. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6504. zero = subtype >> 1;
  6505. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6506. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6507. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6508. if (loc) {
  6509. if (zero) {
  6510. memmove(startp, loc, str - loc);
  6511. loc = startp + (str - loc) - 1;
  6512. }
  6513. *loc = '\0';
  6514. amount = loc - expdest;
  6515. STADJUST(amount, expdest);
  6516. }
  6517. return loc;
  6518. }
  6519. /*
  6520. * Add the value of a specialized variable to the stack string.
  6521. * name parameter (examples):
  6522. * ash -c 'echo $1' name:'1='
  6523. * ash -c 'echo $qwe' name:'qwe='
  6524. * ash -c 'echo $$' name:'$='
  6525. * ash -c 'echo ${$}' name:'$='
  6526. * ash -c 'echo ${$##q}' name:'$=q'
  6527. * ash -c 'echo ${#$}' name:'$='
  6528. * note: examples with bad shell syntax:
  6529. * ash -c 'echo ${#$1}' name:'$=1'
  6530. * ash -c 'echo ${#1#}' name:'1=#'
  6531. */
  6532. static NOINLINE ssize_t
  6533. varvalue(char *name, int varflags, int flags, int *quotedp)
  6534. {
  6535. const char *p;
  6536. int num;
  6537. int i;
  6538. ssize_t len = 0;
  6539. int sep;
  6540. int quoted = *quotedp;
  6541. int subtype = varflags & VSTYPE;
  6542. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6543. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6544. int syntax;
  6545. sep = (flags & EXP_FULL) << CHAR_BIT;
  6546. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6547. switch (*name) {
  6548. case '$':
  6549. num = rootpid;
  6550. goto numvar;
  6551. case '?':
  6552. num = exitstatus;
  6553. goto numvar;
  6554. case '#':
  6555. num = shellparam.nparam;
  6556. goto numvar;
  6557. case '!':
  6558. num = backgndpid;
  6559. if (num == 0)
  6560. return -1;
  6561. numvar:
  6562. len = cvtnum(num);
  6563. goto check_1char_name;
  6564. case '-':
  6565. expdest = makestrspace(NOPTS, expdest);
  6566. for (i = NOPTS - 1; i >= 0; i--) {
  6567. if (optlist[i] && optletters(i)) {
  6568. USTPUTC(optletters(i), expdest);
  6569. len++;
  6570. }
  6571. }
  6572. check_1char_name:
  6573. #if 0
  6574. /* handles cases similar to ${#$1} */
  6575. if (name[2] != '\0')
  6576. raise_error_syntax("bad substitution");
  6577. #endif
  6578. break;
  6579. case '@':
  6580. if (quoted && sep)
  6581. goto param;
  6582. /* fall through */
  6583. case '*': {
  6584. char **ap;
  6585. char sepc;
  6586. if (quoted)
  6587. sep = 0;
  6588. sep |= ifsset() ? ifsval()[0] : ' ';
  6589. param:
  6590. sepc = sep;
  6591. *quotedp = !sepc;
  6592. ap = shellparam.p;
  6593. if (!ap)
  6594. return -1;
  6595. while ((p = *ap++) != NULL) {
  6596. len += strtodest(p, syntax, quotes);
  6597. if (*ap && sep) {
  6598. len++;
  6599. memtodest(&sepc, 1, syntax, quotes);
  6600. }
  6601. }
  6602. break;
  6603. } /* case '*' */
  6604. case '0':
  6605. case '1':
  6606. case '2':
  6607. case '3':
  6608. case '4':
  6609. case '5':
  6610. case '6':
  6611. case '7':
  6612. case '8':
  6613. case '9':
  6614. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6615. if (num < 0 || num > shellparam.nparam)
  6616. return -1;
  6617. p = num ? shellparam.p[num - 1] : arg0;
  6618. goto value;
  6619. default:
  6620. /* NB: name has form "VAR=..." */
  6621. p = lookupvar(name);
  6622. value:
  6623. if (!p)
  6624. return -1;
  6625. len = strtodest(p, syntax, quotes);
  6626. #if ENABLE_UNICODE_SUPPORT
  6627. if (subtype == VSLENGTH && len > 0) {
  6628. reinit_unicode_for_ash();
  6629. if (unicode_status == UNICODE_ON) {
  6630. STADJUST(-len, expdest);
  6631. discard = 0;
  6632. len = unicode_strlen(p);
  6633. }
  6634. }
  6635. #endif
  6636. break;
  6637. }
  6638. if (discard)
  6639. STADJUST(-len, expdest);
  6640. return len;
  6641. }
  6642. /*
  6643. * Expand a variable, and return a pointer to the next character in the
  6644. * input string.
  6645. */
  6646. static char *
  6647. evalvar(char *p, int flag)
  6648. {
  6649. char varflags;
  6650. char subtype;
  6651. int quoted;
  6652. char easy;
  6653. char *var;
  6654. int patloc;
  6655. int startloc;
  6656. ssize_t varlen;
  6657. varflags = (unsigned char) *p++;
  6658. subtype = varflags & VSTYPE;
  6659. if (!subtype)
  6660. raise_error_syntax("bad substitution");
  6661. quoted = flag & EXP_QUOTED;
  6662. var = p;
  6663. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6664. startloc = expdest - (char *)stackblock();
  6665. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6666. again:
  6667. varlen = varvalue(var, varflags, flag, &quoted);
  6668. if (varflags & VSNUL)
  6669. varlen--;
  6670. if (subtype == VSPLUS) {
  6671. varlen = -1 - varlen;
  6672. goto vsplus;
  6673. }
  6674. if (subtype == VSMINUS) {
  6675. vsplus:
  6676. if (varlen < 0) {
  6677. argstr(
  6678. p,
  6679. flag | EXP_TILDE | EXP_WORD
  6680. );
  6681. goto end;
  6682. }
  6683. goto record;
  6684. }
  6685. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6686. if (varlen >= 0)
  6687. goto record;
  6688. subevalvar(p, var, 0, subtype, startloc, varflags,
  6689. flag & ~QUOTES_ESC);
  6690. varflags &= ~VSNUL;
  6691. /*
  6692. * Remove any recorded regions beyond
  6693. * start of variable
  6694. */
  6695. removerecordregions(startloc);
  6696. goto again;
  6697. }
  6698. if (varlen < 0 && uflag)
  6699. varunset(p, var, 0, 0);
  6700. if (subtype == VSLENGTH) {
  6701. cvtnum(varlen > 0 ? varlen : 0);
  6702. goto record;
  6703. }
  6704. if (subtype == VSNORMAL) {
  6705. record:
  6706. if (!easy)
  6707. goto end;
  6708. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6709. goto end;
  6710. }
  6711. #if DEBUG
  6712. switch (subtype) {
  6713. case VSTRIMLEFT:
  6714. case VSTRIMLEFTMAX:
  6715. case VSTRIMRIGHT:
  6716. case VSTRIMRIGHTMAX:
  6717. #if BASH_SUBSTR
  6718. case VSSUBSTR:
  6719. #endif
  6720. #if BASH_PATTERN_SUBST
  6721. case VSREPLACE:
  6722. case VSREPLACEALL:
  6723. #endif
  6724. break;
  6725. default:
  6726. abort();
  6727. }
  6728. #endif
  6729. if (varlen >= 0) {
  6730. /*
  6731. * Terminate the string and start recording the pattern
  6732. * right after it
  6733. */
  6734. STPUTC('\0', expdest);
  6735. patloc = expdest - (char *)stackblock();
  6736. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6737. startloc, varflags, flag)) {
  6738. int amount = expdest - (
  6739. (char *)stackblock() + patloc - 1
  6740. );
  6741. STADJUST(-amount, expdest);
  6742. }
  6743. /* Remove any recorded regions beyond start of variable */
  6744. removerecordregions(startloc);
  6745. goto record;
  6746. }
  6747. end:
  6748. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6749. int nesting = 1;
  6750. for (;;) {
  6751. unsigned char c = *p++;
  6752. if (c == CTLESC)
  6753. p++;
  6754. else if (c == CTLBACKQ) {
  6755. if (varlen >= 0)
  6756. argbackq = argbackq->next;
  6757. } else if (c == CTLVAR) {
  6758. if ((*p++ & VSTYPE) != VSNORMAL)
  6759. nesting++;
  6760. } else if (c == CTLENDVAR) {
  6761. if (--nesting == 0)
  6762. break;
  6763. }
  6764. }
  6765. }
  6766. return p;
  6767. }
  6768. /*
  6769. * Add a file name to the list.
  6770. */
  6771. static void
  6772. addfname(const char *name)
  6773. {
  6774. struct strlist *sp;
  6775. sp = stzalloc(sizeof(*sp));
  6776. sp->text = sstrdup(name);
  6777. *exparg.lastp = sp;
  6778. exparg.lastp = &sp->next;
  6779. }
  6780. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6781. static int
  6782. hasmeta(const char *p)
  6783. {
  6784. static const char chars[] ALIGN1 = {
  6785. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6786. };
  6787. for (;;) {
  6788. p = strpbrk(p, chars);
  6789. if (!p)
  6790. break;
  6791. switch ((unsigned char)*p) {
  6792. case CTLQUOTEMARK:
  6793. for (;;) {
  6794. p++;
  6795. if ((unsigned char)*p == CTLQUOTEMARK)
  6796. break;
  6797. if ((unsigned char)*p == CTLESC)
  6798. p++;
  6799. if (*p == '\0') /* huh? */
  6800. return 0;
  6801. }
  6802. break;
  6803. case '\\':
  6804. case CTLESC:
  6805. p++;
  6806. if (*p == '\0')
  6807. return 0;
  6808. break;
  6809. case '[':
  6810. if (!strchr(p + 1, ']')) {
  6811. /* It's not a properly closed [] pattern,
  6812. * but other metas may follow. Continue checking.
  6813. * my[file* _is_ globbed by bash
  6814. * and matches filenames like "my[file1".
  6815. */
  6816. break;
  6817. }
  6818. /* fallthrough */
  6819. default:
  6820. /* case '*': */
  6821. /* case '?': */
  6822. return 1;
  6823. }
  6824. p++;
  6825. }
  6826. return 0;
  6827. }
  6828. /* If we want to use glob() from libc... */
  6829. #if !ENABLE_ASH_INTERNAL_GLOB
  6830. /* Add the result of glob() to the list */
  6831. static void
  6832. addglob(const glob_t *pglob)
  6833. {
  6834. char **p = pglob->gl_pathv;
  6835. do {
  6836. addfname(*p);
  6837. } while (*++p);
  6838. }
  6839. static void
  6840. expandmeta(struct strlist *str /*, int flag*/)
  6841. {
  6842. /* TODO - EXP_REDIR */
  6843. while (str) {
  6844. char *p;
  6845. glob_t pglob;
  6846. int i;
  6847. if (fflag)
  6848. goto nometa;
  6849. if (!hasmeta(str->text))
  6850. goto nometa;
  6851. INT_OFF;
  6852. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6853. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6854. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6855. //
  6856. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6857. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6858. // Which means you need to unescape the string, right? Not so fast:
  6859. // if there _is_ a file named "file\?" (with backslash), it is returned
  6860. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6861. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6862. //
  6863. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6864. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6865. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6866. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6867. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6868. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6869. i = glob(p, 0, NULL, &pglob);
  6870. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6871. if (p != str->text)
  6872. free(p);
  6873. switch (i) {
  6874. case 0:
  6875. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6876. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6877. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6878. goto nometa2;
  6879. #endif
  6880. addglob(&pglob);
  6881. globfree(&pglob);
  6882. INT_ON;
  6883. break;
  6884. case GLOB_NOMATCH:
  6885. //nometa2:
  6886. globfree(&pglob);
  6887. INT_ON;
  6888. nometa:
  6889. *exparg.lastp = str;
  6890. rmescapes(str->text, 0, NULL);
  6891. exparg.lastp = &str->next;
  6892. break;
  6893. default: /* GLOB_NOSPACE */
  6894. globfree(&pglob);
  6895. INT_ON;
  6896. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6897. }
  6898. str = str->next;
  6899. }
  6900. }
  6901. #else
  6902. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6903. /*
  6904. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6905. */
  6906. typedef struct exp_t {
  6907. char *dir;
  6908. unsigned dir_max;
  6909. } exp_t;
  6910. static void
  6911. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  6912. {
  6913. #define expdir exp->dir
  6914. #define expdir_max exp->dir_max
  6915. char *enddir = expdir + expdir_len;
  6916. char *p;
  6917. const char *cp;
  6918. char *start;
  6919. char *endname;
  6920. int metaflag;
  6921. struct stat statb;
  6922. DIR *dirp;
  6923. struct dirent *dp;
  6924. int atend;
  6925. int matchdot;
  6926. int esc;
  6927. metaflag = 0;
  6928. start = name;
  6929. for (p = name; esc = 0, *p; p += esc + 1) {
  6930. if (*p == '*' || *p == '?')
  6931. metaflag = 1;
  6932. else if (*p == '[') {
  6933. char *q = p + 1;
  6934. if (*q == '!')
  6935. q++;
  6936. for (;;) {
  6937. if (*q == '\\')
  6938. q++;
  6939. if (*q == '/' || *q == '\0')
  6940. break;
  6941. if (*++q == ']') {
  6942. metaflag = 1;
  6943. break;
  6944. }
  6945. }
  6946. } else {
  6947. if (*p == '\\')
  6948. esc++;
  6949. if (p[esc] == '/') {
  6950. if (metaflag)
  6951. break;
  6952. start = p + esc + 1;
  6953. }
  6954. }
  6955. }
  6956. if (metaflag == 0) { /* we've reached the end of the file name */
  6957. if (!expdir_len)
  6958. return;
  6959. p = name;
  6960. do {
  6961. if (*p == '\\')
  6962. p++;
  6963. *enddir++ = *p;
  6964. } while (*p++);
  6965. if (lstat(expdir, &statb) == 0)
  6966. addfname(expdir);
  6967. return;
  6968. }
  6969. endname = p;
  6970. if (name < start) {
  6971. p = name;
  6972. do {
  6973. if (*p == '\\')
  6974. p++;
  6975. *enddir++ = *p++;
  6976. } while (p < start);
  6977. }
  6978. *enddir = '\0';
  6979. cp = expdir;
  6980. expdir_len = enddir - cp;
  6981. if (!expdir_len)
  6982. cp = ".";
  6983. dirp = opendir(cp);
  6984. if (dirp == NULL)
  6985. return;
  6986. if (*endname == 0) {
  6987. atend = 1;
  6988. } else {
  6989. atend = 0;
  6990. *endname = '\0';
  6991. endname += esc + 1;
  6992. }
  6993. name_len -= endname - name;
  6994. matchdot = 0;
  6995. p = start;
  6996. if (*p == '\\')
  6997. p++;
  6998. if (*p == '.')
  6999. matchdot++;
  7000. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7001. if (dp->d_name[0] == '.' && !matchdot)
  7002. continue;
  7003. if (pmatch(start, dp->d_name)) {
  7004. if (atend) {
  7005. strcpy(enddir, dp->d_name);
  7006. addfname(expdir);
  7007. } else {
  7008. unsigned offset;
  7009. unsigned len;
  7010. p = stpcpy(enddir, dp->d_name);
  7011. *p = '/';
  7012. offset = p - expdir + 1;
  7013. len = offset + name_len + NAME_MAX;
  7014. if (len > expdir_max) {
  7015. len += PATH_MAX;
  7016. expdir = ckrealloc(expdir, len);
  7017. expdir_max = len;
  7018. }
  7019. expmeta(exp, endname, name_len, offset);
  7020. enddir = expdir + expdir_len;
  7021. }
  7022. }
  7023. }
  7024. closedir(dirp);
  7025. if (!atend)
  7026. endname[-esc - 1] = esc ? '\\' : '/';
  7027. #undef expdir
  7028. #undef expdir_max
  7029. }
  7030. static struct strlist *
  7031. msort(struct strlist *list, int len)
  7032. {
  7033. struct strlist *p, *q = NULL;
  7034. struct strlist **lpp;
  7035. int half;
  7036. int n;
  7037. if (len <= 1)
  7038. return list;
  7039. half = len >> 1;
  7040. p = list;
  7041. for (n = half; --n >= 0;) {
  7042. q = p;
  7043. p = p->next;
  7044. }
  7045. q->next = NULL; /* terminate first half of list */
  7046. q = msort(list, half); /* sort first half of list */
  7047. p = msort(p, len - half); /* sort second half */
  7048. lpp = &list;
  7049. for (;;) {
  7050. #if ENABLE_LOCALE_SUPPORT
  7051. if (strcoll(p->text, q->text) < 0)
  7052. #else
  7053. if (strcmp(p->text, q->text) < 0)
  7054. #endif
  7055. {
  7056. *lpp = p;
  7057. lpp = &p->next;
  7058. p = *lpp;
  7059. if (p == NULL) {
  7060. *lpp = q;
  7061. break;
  7062. }
  7063. } else {
  7064. *lpp = q;
  7065. lpp = &q->next;
  7066. q = *lpp;
  7067. if (q == NULL) {
  7068. *lpp = p;
  7069. break;
  7070. }
  7071. }
  7072. }
  7073. return list;
  7074. }
  7075. /*
  7076. * Sort the results of file name expansion. It calculates the number of
  7077. * strings to sort and then calls msort (short for merge sort) to do the
  7078. * work.
  7079. */
  7080. static struct strlist *
  7081. expsort(struct strlist *str)
  7082. {
  7083. int len;
  7084. struct strlist *sp;
  7085. len = 0;
  7086. for (sp = str; sp; sp = sp->next)
  7087. len++;
  7088. return msort(str, len);
  7089. }
  7090. static void
  7091. expandmeta(struct strlist *str /*, int flag*/)
  7092. {
  7093. /* TODO - EXP_REDIR */
  7094. while (str) {
  7095. exp_t exp;
  7096. struct strlist **savelastp;
  7097. struct strlist *sp;
  7098. char *p;
  7099. unsigned len;
  7100. if (fflag)
  7101. goto nometa;
  7102. if (!hasmeta(str->text))
  7103. goto nometa;
  7104. savelastp = exparg.lastp;
  7105. INT_OFF;
  7106. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7107. len = strlen(p);
  7108. exp.dir_max = len + PATH_MAX;
  7109. exp.dir = ckmalloc(exp.dir_max);
  7110. expmeta(&exp, p, len, 0);
  7111. free(exp.dir);
  7112. if (p != str->text)
  7113. free(p);
  7114. INT_ON;
  7115. if (exparg.lastp == savelastp) {
  7116. /*
  7117. * no matches
  7118. */
  7119. nometa:
  7120. *exparg.lastp = str;
  7121. rmescapes(str->text, 0, NULL);
  7122. exparg.lastp = &str->next;
  7123. } else {
  7124. *exparg.lastp = NULL;
  7125. *savelastp = sp = expsort(*savelastp);
  7126. while (sp->next != NULL)
  7127. sp = sp->next;
  7128. exparg.lastp = &sp->next;
  7129. }
  7130. str = str->next;
  7131. }
  7132. }
  7133. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7134. /*
  7135. * Perform variable substitution and command substitution on an argument,
  7136. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7137. * perform splitting and file name expansion. When arglist is NULL, perform
  7138. * here document expansion.
  7139. */
  7140. static void
  7141. expandarg(union node *arg, struct arglist *arglist, int flag)
  7142. {
  7143. struct strlist *sp;
  7144. char *p;
  7145. argbackq = arg->narg.backquote;
  7146. STARTSTACKSTR(expdest);
  7147. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7148. argstr(arg->narg.text, flag);
  7149. p = _STPUTC('\0', expdest);
  7150. expdest = p - 1;
  7151. if (arglist == NULL) {
  7152. /* here document expanded */
  7153. goto out;
  7154. }
  7155. p = grabstackstr(p);
  7156. TRACE(("expandarg: p:'%s'\n", p));
  7157. exparg.lastp = &exparg.list;
  7158. /*
  7159. * TODO - EXP_REDIR
  7160. */
  7161. if (flag & EXP_FULL) {
  7162. ifsbreakup(p, &exparg);
  7163. *exparg.lastp = NULL;
  7164. exparg.lastp = &exparg.list;
  7165. expandmeta(exparg.list /*, flag*/);
  7166. } else {
  7167. sp = stzalloc(sizeof(*sp));
  7168. sp->text = p;
  7169. *exparg.lastp = sp;
  7170. exparg.lastp = &sp->next;
  7171. }
  7172. *exparg.lastp = NULL;
  7173. if (exparg.list) {
  7174. *arglist->lastp = exparg.list;
  7175. arglist->lastp = exparg.lastp;
  7176. }
  7177. out:
  7178. ifsfree();
  7179. }
  7180. /*
  7181. * Expand shell variables and backquotes inside a here document.
  7182. */
  7183. static void
  7184. expandhere(union node *arg, int fd)
  7185. {
  7186. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7187. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7188. }
  7189. /*
  7190. * Returns true if the pattern matches the string.
  7191. */
  7192. static int
  7193. patmatch(char *pattern, const char *string)
  7194. {
  7195. char *p = preglob(pattern, 0);
  7196. int r = pmatch(p, string);
  7197. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7198. return r;
  7199. }
  7200. /*
  7201. * See if a pattern matches in a case statement.
  7202. */
  7203. static int
  7204. casematch(union node *pattern, char *val)
  7205. {
  7206. struct stackmark smark;
  7207. int result;
  7208. setstackmark(&smark);
  7209. argbackq = pattern->narg.backquote;
  7210. STARTSTACKSTR(expdest);
  7211. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7212. STACKSTRNUL(expdest);
  7213. ifsfree();
  7214. result = patmatch(stackblock(), val);
  7215. popstackmark(&smark);
  7216. return result;
  7217. }
  7218. /* ============ find_command */
  7219. struct builtincmd {
  7220. const char *name;
  7221. int (*builtin)(int, char **) FAST_FUNC;
  7222. /* unsigned flags; */
  7223. };
  7224. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7225. /* "regular" builtins always take precedence over commands,
  7226. * regardless of PATH=....%builtin... position */
  7227. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7228. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7229. struct cmdentry {
  7230. smallint cmdtype; /* CMDxxx */
  7231. union param {
  7232. int index;
  7233. /* index >= 0 for commands without path (slashes) */
  7234. /* (TODO: what exactly does the value mean? PATH position?) */
  7235. /* index == -1 for commands with slashes */
  7236. /* index == (-2 - applet_no) for NOFORK applets */
  7237. const struct builtincmd *cmd;
  7238. struct funcnode *func;
  7239. } u;
  7240. };
  7241. /* values of cmdtype */
  7242. #define CMDUNKNOWN -1 /* no entry in table for command */
  7243. #define CMDNORMAL 0 /* command is an executable program */
  7244. #define CMDFUNCTION 1 /* command is a shell function */
  7245. #define CMDBUILTIN 2 /* command is a shell builtin */
  7246. /* action to find_command() */
  7247. #define DO_ERR 0x01 /* prints errors */
  7248. #define DO_ABS 0x02 /* checks absolute paths */
  7249. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7250. #define DO_ALTPATH 0x08 /* using alternate path */
  7251. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7252. static void find_command(char *, struct cmdentry *, int, const char *);
  7253. /* ============ Hashing commands */
  7254. /*
  7255. * When commands are first encountered, they are entered in a hash table.
  7256. * This ensures that a full path search will not have to be done for them
  7257. * on each invocation.
  7258. *
  7259. * We should investigate converting to a linear search, even though that
  7260. * would make the command name "hash" a misnomer.
  7261. */
  7262. struct tblentry {
  7263. struct tblentry *next; /* next entry in hash chain */
  7264. union param param; /* definition of builtin function */
  7265. smallint cmdtype; /* CMDxxx */
  7266. char rehash; /* if set, cd done since entry created */
  7267. char cmdname[1]; /* name of command */
  7268. };
  7269. static struct tblentry **cmdtable;
  7270. #define INIT_G_cmdtable() do { \
  7271. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7272. } while (0)
  7273. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7274. static void
  7275. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7276. {
  7277. #if ENABLE_FEATURE_SH_STANDALONE
  7278. if (applet_no >= 0) {
  7279. if (APPLET_IS_NOEXEC(applet_no)) {
  7280. clearenv();
  7281. while (*envp)
  7282. putenv(*envp++);
  7283. popredir(/*drop:*/ 1);
  7284. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7285. }
  7286. /* re-exec ourselves with the new arguments */
  7287. execve(bb_busybox_exec_path, argv, envp);
  7288. /* If they called chroot or otherwise made the binary no longer
  7289. * executable, fall through */
  7290. }
  7291. #endif
  7292. repeat:
  7293. #ifdef SYSV
  7294. do {
  7295. execve(cmd, argv, envp);
  7296. } while (errno == EINTR);
  7297. #else
  7298. execve(cmd, argv, envp);
  7299. #endif
  7300. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7301. /* Run "cmd" as a shell script:
  7302. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7303. * "If the execve() function fails with ENOEXEC, the shell
  7304. * shall execute a command equivalent to having a shell invoked
  7305. * with the command name as its first operand,
  7306. * with any remaining arguments passed to the new shell"
  7307. *
  7308. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7309. * just call ourselves.
  7310. *
  7311. * Note that bash reads ~80 chars of the file, and if it sees
  7312. * a zero byte before it sees newline, it doesn't try to
  7313. * interpret it, but fails with "cannot execute binary file"
  7314. * message and exit code 126. For one, this prevents attempts
  7315. * to interpret foreign ELF binaries as shell scripts.
  7316. */
  7317. argv[0] = (char*) cmd;
  7318. cmd = bb_busybox_exec_path;
  7319. /* NB: this is only possible because all callers of shellexec()
  7320. * ensure that the argv[-1] slot exists!
  7321. */
  7322. argv--;
  7323. argv[0] = (char*) "ash";
  7324. goto repeat;
  7325. }
  7326. }
  7327. /*
  7328. * Exec a program. Never returns. If you change this routine, you may
  7329. * have to change the find_command routine as well.
  7330. * argv[-1] must exist and be writable! See tryexec() for why.
  7331. */
  7332. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7333. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7334. {
  7335. char *cmdname;
  7336. int e;
  7337. char **envp;
  7338. int exerrno;
  7339. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7340. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7341. if (strchr(prog, '/') != NULL
  7342. #if ENABLE_FEATURE_SH_STANDALONE
  7343. || (applet_no = find_applet_by_name(prog)) >= 0
  7344. #endif
  7345. ) {
  7346. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7347. if (applet_no >= 0) {
  7348. /* We tried execing ourself, but it didn't work.
  7349. * Maybe /proc/self/exe doesn't exist?
  7350. * Try $PATH search.
  7351. */
  7352. goto try_PATH;
  7353. }
  7354. e = errno;
  7355. } else {
  7356. try_PATH:
  7357. e = ENOENT;
  7358. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7359. if (--idx < 0 && pathopt == NULL) {
  7360. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7361. if (errno != ENOENT && errno != ENOTDIR)
  7362. e = errno;
  7363. }
  7364. stunalloc(cmdname);
  7365. }
  7366. }
  7367. /* Map to POSIX errors */
  7368. switch (e) {
  7369. case EACCES:
  7370. exerrno = 126;
  7371. break;
  7372. case ENOENT:
  7373. exerrno = 127;
  7374. break;
  7375. default:
  7376. exerrno = 2;
  7377. break;
  7378. }
  7379. exitstatus = exerrno;
  7380. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7381. prog, e, suppress_int));
  7382. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7383. /* NOTREACHED */
  7384. }
  7385. static void
  7386. printentry(struct tblentry *cmdp)
  7387. {
  7388. int idx;
  7389. const char *path;
  7390. char *name;
  7391. idx = cmdp->param.index;
  7392. path = pathval();
  7393. do {
  7394. name = path_advance(&path, cmdp->cmdname);
  7395. stunalloc(name);
  7396. } while (--idx >= 0);
  7397. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7398. }
  7399. /*
  7400. * Clear out command entries. The argument specifies the first entry in
  7401. * PATH which has changed.
  7402. */
  7403. static void
  7404. clearcmdentry(int firstchange)
  7405. {
  7406. struct tblentry **tblp;
  7407. struct tblentry **pp;
  7408. struct tblentry *cmdp;
  7409. INT_OFF;
  7410. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7411. pp = tblp;
  7412. while ((cmdp = *pp) != NULL) {
  7413. if ((cmdp->cmdtype == CMDNORMAL &&
  7414. cmdp->param.index >= firstchange)
  7415. || (cmdp->cmdtype == CMDBUILTIN &&
  7416. builtinloc >= firstchange)
  7417. ) {
  7418. *pp = cmdp->next;
  7419. free(cmdp);
  7420. } else {
  7421. pp = &cmdp->next;
  7422. }
  7423. }
  7424. }
  7425. INT_ON;
  7426. }
  7427. /*
  7428. * Locate a command in the command hash table. If "add" is nonzero,
  7429. * add the command to the table if it is not already present. The
  7430. * variable "lastcmdentry" is set to point to the address of the link
  7431. * pointing to the entry, so that delete_cmd_entry can delete the
  7432. * entry.
  7433. *
  7434. * Interrupts must be off if called with add != 0.
  7435. */
  7436. static struct tblentry **lastcmdentry;
  7437. static struct tblentry *
  7438. cmdlookup(const char *name, int add)
  7439. {
  7440. unsigned int hashval;
  7441. const char *p;
  7442. struct tblentry *cmdp;
  7443. struct tblentry **pp;
  7444. p = name;
  7445. hashval = (unsigned char)*p << 4;
  7446. while (*p)
  7447. hashval += (unsigned char)*p++;
  7448. hashval &= 0x7FFF;
  7449. pp = &cmdtable[hashval % CMDTABLESIZE];
  7450. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7451. if (strcmp(cmdp->cmdname, name) == 0)
  7452. break;
  7453. pp = &cmdp->next;
  7454. }
  7455. if (add && cmdp == NULL) {
  7456. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7457. + strlen(name)
  7458. /* + 1 - already done because
  7459. * tblentry::cmdname is char[1] */);
  7460. /*cmdp->next = NULL; - ckzalloc did it */
  7461. cmdp->cmdtype = CMDUNKNOWN;
  7462. strcpy(cmdp->cmdname, name);
  7463. }
  7464. lastcmdentry = pp;
  7465. return cmdp;
  7466. }
  7467. /*
  7468. * Delete the command entry returned on the last lookup.
  7469. */
  7470. static void
  7471. delete_cmd_entry(void)
  7472. {
  7473. struct tblentry *cmdp;
  7474. INT_OFF;
  7475. cmdp = *lastcmdentry;
  7476. *lastcmdentry = cmdp->next;
  7477. if (cmdp->cmdtype == CMDFUNCTION)
  7478. freefunc(cmdp->param.func);
  7479. free(cmdp);
  7480. INT_ON;
  7481. }
  7482. /*
  7483. * Add a new command entry, replacing any existing command entry for
  7484. * the same name - except special builtins.
  7485. */
  7486. static void
  7487. addcmdentry(char *name, struct cmdentry *entry)
  7488. {
  7489. struct tblentry *cmdp;
  7490. cmdp = cmdlookup(name, 1);
  7491. if (cmdp->cmdtype == CMDFUNCTION) {
  7492. freefunc(cmdp->param.func);
  7493. }
  7494. cmdp->cmdtype = entry->cmdtype;
  7495. cmdp->param = entry->u;
  7496. cmdp->rehash = 0;
  7497. }
  7498. static int FAST_FUNC
  7499. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7500. {
  7501. struct tblentry **pp;
  7502. struct tblentry *cmdp;
  7503. int c;
  7504. struct cmdentry entry;
  7505. char *name;
  7506. if (nextopt("r") != '\0') {
  7507. clearcmdentry(0);
  7508. return 0;
  7509. }
  7510. if (*argptr == NULL) {
  7511. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7512. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7513. if (cmdp->cmdtype == CMDNORMAL)
  7514. printentry(cmdp);
  7515. }
  7516. }
  7517. return 0;
  7518. }
  7519. c = 0;
  7520. while ((name = *argptr) != NULL) {
  7521. cmdp = cmdlookup(name, 0);
  7522. if (cmdp != NULL
  7523. && (cmdp->cmdtype == CMDNORMAL
  7524. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7525. ) {
  7526. delete_cmd_entry();
  7527. }
  7528. find_command(name, &entry, DO_ERR, pathval());
  7529. if (entry.cmdtype == CMDUNKNOWN)
  7530. c = 1;
  7531. argptr++;
  7532. }
  7533. return c;
  7534. }
  7535. /*
  7536. * Called when a cd is done. Marks all commands so the next time they
  7537. * are executed they will be rehashed.
  7538. */
  7539. static void
  7540. hashcd(void)
  7541. {
  7542. struct tblentry **pp;
  7543. struct tblentry *cmdp;
  7544. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7545. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7546. if (cmdp->cmdtype == CMDNORMAL
  7547. || (cmdp->cmdtype == CMDBUILTIN
  7548. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7549. && builtinloc > 0)
  7550. ) {
  7551. cmdp->rehash = 1;
  7552. }
  7553. }
  7554. }
  7555. }
  7556. /*
  7557. * Fix command hash table when PATH changed.
  7558. * Called before PATH is changed. The argument is the new value of PATH;
  7559. * pathval() still returns the old value at this point.
  7560. * Called with interrupts off.
  7561. */
  7562. static void FAST_FUNC
  7563. changepath(const char *new)
  7564. {
  7565. const char *old;
  7566. int firstchange;
  7567. int idx;
  7568. int idx_bltin;
  7569. old = pathval();
  7570. firstchange = 9999; /* assume no change */
  7571. idx = 0;
  7572. idx_bltin = -1;
  7573. for (;;) {
  7574. if (*old != *new) {
  7575. firstchange = idx;
  7576. if ((*old == '\0' && *new == ':')
  7577. || (*old == ':' && *new == '\0')
  7578. ) {
  7579. firstchange++;
  7580. }
  7581. old = new; /* ignore subsequent differences */
  7582. }
  7583. if (*new == '\0')
  7584. break;
  7585. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7586. idx_bltin = idx;
  7587. if (*new == ':')
  7588. idx++;
  7589. new++;
  7590. old++;
  7591. }
  7592. if (builtinloc < 0 && idx_bltin >= 0)
  7593. builtinloc = idx_bltin; /* zap builtins */
  7594. if (builtinloc >= 0 && idx_bltin < 0)
  7595. firstchange = 0;
  7596. clearcmdentry(firstchange);
  7597. builtinloc = idx_bltin;
  7598. }
  7599. enum {
  7600. TEOF,
  7601. TNL,
  7602. TREDIR,
  7603. TWORD,
  7604. TSEMI,
  7605. TBACKGND,
  7606. TAND,
  7607. TOR,
  7608. TPIPE,
  7609. TLP,
  7610. TRP,
  7611. TENDCASE,
  7612. TENDBQUOTE,
  7613. TNOT,
  7614. TCASE,
  7615. TDO,
  7616. TDONE,
  7617. TELIF,
  7618. TELSE,
  7619. TESAC,
  7620. TFI,
  7621. TFOR,
  7622. #if BASH_FUNCTION
  7623. TFUNCTION,
  7624. #endif
  7625. TIF,
  7626. TIN,
  7627. TTHEN,
  7628. TUNTIL,
  7629. TWHILE,
  7630. TBEGIN,
  7631. TEND
  7632. };
  7633. typedef smallint token_id_t;
  7634. /* Nth bit indicates if token marks the end of a list */
  7635. enum {
  7636. tokendlist = 0
  7637. /* 0 */ | (1u << TEOF)
  7638. /* 1 */ | (0u << TNL)
  7639. /* 2 */ | (0u << TREDIR)
  7640. /* 3 */ | (0u << TWORD)
  7641. /* 4 */ | (0u << TSEMI)
  7642. /* 5 */ | (0u << TBACKGND)
  7643. /* 6 */ | (0u << TAND)
  7644. /* 7 */ | (0u << TOR)
  7645. /* 8 */ | (0u << TPIPE)
  7646. /* 9 */ | (0u << TLP)
  7647. /* 10 */ | (1u << TRP)
  7648. /* 11 */ | (1u << TENDCASE)
  7649. /* 12 */ | (1u << TENDBQUOTE)
  7650. /* 13 */ | (0u << TNOT)
  7651. /* 14 */ | (0u << TCASE)
  7652. /* 15 */ | (1u << TDO)
  7653. /* 16 */ | (1u << TDONE)
  7654. /* 17 */ | (1u << TELIF)
  7655. /* 18 */ | (1u << TELSE)
  7656. /* 19 */ | (1u << TESAC)
  7657. /* 20 */ | (1u << TFI)
  7658. /* 21 */ | (0u << TFOR)
  7659. #if BASH_FUNCTION
  7660. /* 22 */ | (0u << TFUNCTION)
  7661. #endif
  7662. /* 23 */ | (0u << TIF)
  7663. /* 24 */ | (0u << TIN)
  7664. /* 25 */ | (1u << TTHEN)
  7665. /* 26 */ | (0u << TUNTIL)
  7666. /* 27 */ | (0u << TWHILE)
  7667. /* 28 */ | (0u << TBEGIN)
  7668. /* 29 */ | (1u << TEND)
  7669. , /* thus far 29 bits used */
  7670. };
  7671. static const char *const tokname_array[] = {
  7672. "end of file",
  7673. "newline",
  7674. "redirection",
  7675. "word",
  7676. ";",
  7677. "&",
  7678. "&&",
  7679. "||",
  7680. "|",
  7681. "(",
  7682. ")",
  7683. ";;",
  7684. "`",
  7685. #define KWDOFFSET 13
  7686. /* the following are keywords */
  7687. "!",
  7688. "case",
  7689. "do",
  7690. "done",
  7691. "elif",
  7692. "else",
  7693. "esac",
  7694. "fi",
  7695. "for",
  7696. #if BASH_FUNCTION
  7697. "function",
  7698. #endif
  7699. "if",
  7700. "in",
  7701. "then",
  7702. "until",
  7703. "while",
  7704. "{",
  7705. "}",
  7706. };
  7707. /* Wrapper around strcmp for qsort/bsearch/... */
  7708. static int
  7709. pstrcmp(const void *a, const void *b)
  7710. {
  7711. return strcmp((char*)a, *(char**)b);
  7712. }
  7713. static const char *const *
  7714. findkwd(const char *s)
  7715. {
  7716. return bsearch(s, tokname_array + KWDOFFSET,
  7717. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7718. sizeof(tokname_array[0]), pstrcmp);
  7719. }
  7720. /*
  7721. * Locate and print what a word is...
  7722. */
  7723. static int
  7724. describe_command(char *command, const char *path, int describe_command_verbose)
  7725. {
  7726. struct cmdentry entry;
  7727. #if ENABLE_ASH_ALIAS
  7728. const struct alias *ap;
  7729. #endif
  7730. path = path ? path : pathval();
  7731. if (describe_command_verbose) {
  7732. out1str(command);
  7733. }
  7734. /* First look at the keywords */
  7735. if (findkwd(command)) {
  7736. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7737. goto out;
  7738. }
  7739. #if ENABLE_ASH_ALIAS
  7740. /* Then look at the aliases */
  7741. ap = lookupalias(command, 0);
  7742. if (ap != NULL) {
  7743. if (!describe_command_verbose) {
  7744. out1str("alias ");
  7745. printalias(ap);
  7746. return 0;
  7747. }
  7748. out1fmt(" is an alias for %s", ap->val);
  7749. goto out;
  7750. }
  7751. #endif
  7752. /* Brute force */
  7753. find_command(command, &entry, DO_ABS, path);
  7754. switch (entry.cmdtype) {
  7755. case CMDNORMAL: {
  7756. int j = entry.u.index;
  7757. char *p;
  7758. if (j < 0) {
  7759. p = command;
  7760. } else {
  7761. do {
  7762. p = path_advance(&path, command);
  7763. stunalloc(p);
  7764. } while (--j >= 0);
  7765. }
  7766. if (describe_command_verbose) {
  7767. out1fmt(" is %s", p);
  7768. } else {
  7769. out1str(p);
  7770. }
  7771. break;
  7772. }
  7773. case CMDFUNCTION:
  7774. if (describe_command_verbose) {
  7775. out1str(" is a shell function");
  7776. } else {
  7777. out1str(command);
  7778. }
  7779. break;
  7780. case CMDBUILTIN:
  7781. if (describe_command_verbose) {
  7782. out1fmt(" is a %sshell builtin",
  7783. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7784. "special " : nullstr
  7785. );
  7786. } else {
  7787. out1str(command);
  7788. }
  7789. break;
  7790. default:
  7791. if (describe_command_verbose) {
  7792. out1str(": not found\n");
  7793. }
  7794. return 127;
  7795. }
  7796. out:
  7797. out1str("\n");
  7798. return 0;
  7799. }
  7800. static int FAST_FUNC
  7801. typecmd(int argc UNUSED_PARAM, char **argv)
  7802. {
  7803. int i = 1;
  7804. int err = 0;
  7805. int verbose = 1;
  7806. /* type -p ... ? (we don't bother checking for 'p') */
  7807. if (argv[1] && argv[1][0] == '-') {
  7808. i++;
  7809. verbose = 0;
  7810. }
  7811. while (argv[i]) {
  7812. err |= describe_command(argv[i++], NULL, verbose);
  7813. }
  7814. return err;
  7815. }
  7816. #if ENABLE_ASH_CMDCMD
  7817. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7818. static char **
  7819. parse_command_args(char **argv, const char **path)
  7820. {
  7821. char *cp, c;
  7822. for (;;) {
  7823. cp = *++argv;
  7824. if (!cp)
  7825. return NULL;
  7826. if (*cp++ != '-')
  7827. break;
  7828. c = *cp++;
  7829. if (!c)
  7830. break;
  7831. if (c == '-' && !*cp) {
  7832. if (!*++argv)
  7833. return NULL;
  7834. break;
  7835. }
  7836. do {
  7837. switch (c) {
  7838. case 'p':
  7839. *path = bb_default_path;
  7840. break;
  7841. default:
  7842. /* run 'typecmd' for other options */
  7843. return NULL;
  7844. }
  7845. c = *cp++;
  7846. } while (c);
  7847. }
  7848. return argv;
  7849. }
  7850. static int FAST_FUNC
  7851. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7852. {
  7853. char *cmd;
  7854. int c;
  7855. enum {
  7856. VERIFY_BRIEF = 1,
  7857. VERIFY_VERBOSE = 2,
  7858. } verify = 0;
  7859. const char *path = NULL;
  7860. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7861. * never reaches this function.
  7862. */
  7863. while ((c = nextopt("pvV")) != '\0')
  7864. if (c == 'V')
  7865. verify |= VERIFY_VERBOSE;
  7866. else if (c == 'v')
  7867. /*verify |= VERIFY_BRIEF*/;
  7868. #if DEBUG
  7869. else if (c != 'p')
  7870. abort();
  7871. #endif
  7872. else
  7873. path = bb_default_path;
  7874. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7875. cmd = *argptr;
  7876. if (/*verify && */ cmd)
  7877. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7878. return 0;
  7879. }
  7880. #endif
  7881. /*static int funcblocksize; // size of structures in function */
  7882. /*static int funcstringsize; // size of strings in node */
  7883. static void *funcblock; /* block to allocate function from */
  7884. static char *funcstring_end; /* end of block to allocate strings from */
  7885. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7886. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7887. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7888. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7889. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7890. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7891. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7892. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7893. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7894. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7895. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7896. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7897. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7898. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7899. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7900. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7901. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7902. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7903. #if BASH_REDIR_OUTPUT
  7904. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7905. #endif
  7906. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7907. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7908. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7909. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7910. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7911. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7912. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7913. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7914. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7915. };
  7916. static int calcsize(int funcblocksize, union node *n);
  7917. static int
  7918. sizenodelist(int funcblocksize, struct nodelist *lp)
  7919. {
  7920. while (lp) {
  7921. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7922. funcblocksize = calcsize(funcblocksize, lp->n);
  7923. lp = lp->next;
  7924. }
  7925. return funcblocksize;
  7926. }
  7927. static int
  7928. calcsize(int funcblocksize, union node *n)
  7929. {
  7930. if (n == NULL)
  7931. return funcblocksize;
  7932. funcblocksize += nodesize[n->type];
  7933. switch (n->type) {
  7934. case NCMD:
  7935. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7936. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7937. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7938. break;
  7939. case NPIPE:
  7940. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7941. break;
  7942. case NREDIR:
  7943. case NBACKGND:
  7944. case NSUBSHELL:
  7945. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7946. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7947. break;
  7948. case NAND:
  7949. case NOR:
  7950. case NSEMI:
  7951. case NWHILE:
  7952. case NUNTIL:
  7953. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7954. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7955. break;
  7956. case NIF:
  7957. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7958. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7959. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7960. break;
  7961. case NFOR:
  7962. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7963. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7964. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7965. break;
  7966. case NCASE:
  7967. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7968. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7969. break;
  7970. case NCLIST:
  7971. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7972. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7973. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7974. break;
  7975. case NDEFUN:
  7976. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  7977. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  7978. break;
  7979. case NARG:
  7980. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  7981. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  7982. funcblocksize = calcsize(funcblocksize, n->narg.next);
  7983. break;
  7984. case NTO:
  7985. #if BASH_REDIR_OUTPUT
  7986. case NTO2:
  7987. #endif
  7988. case NCLOBBER:
  7989. case NFROM:
  7990. case NFROMTO:
  7991. case NAPPEND:
  7992. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  7993. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  7994. break;
  7995. case NTOFD:
  7996. case NFROMFD:
  7997. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  7998. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  7999. break;
  8000. case NHERE:
  8001. case NXHERE:
  8002. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8003. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8004. break;
  8005. case NNOT:
  8006. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8007. break;
  8008. };
  8009. return funcblocksize;
  8010. }
  8011. static char *
  8012. nodeckstrdup(char *s)
  8013. {
  8014. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8015. return strcpy(funcstring_end, s);
  8016. }
  8017. static union node *copynode(union node *);
  8018. static struct nodelist *
  8019. copynodelist(struct nodelist *lp)
  8020. {
  8021. struct nodelist *start;
  8022. struct nodelist **lpp;
  8023. lpp = &start;
  8024. while (lp) {
  8025. *lpp = funcblock;
  8026. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8027. (*lpp)->n = copynode(lp->n);
  8028. lp = lp->next;
  8029. lpp = &(*lpp)->next;
  8030. }
  8031. *lpp = NULL;
  8032. return start;
  8033. }
  8034. static union node *
  8035. copynode(union node *n)
  8036. {
  8037. union node *new;
  8038. if (n == NULL)
  8039. return NULL;
  8040. new = funcblock;
  8041. funcblock = (char *) funcblock + nodesize[n->type];
  8042. switch (n->type) {
  8043. case NCMD:
  8044. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8045. new->ncmd.args = copynode(n->ncmd.args);
  8046. new->ncmd.assign = copynode(n->ncmd.assign);
  8047. new->ncmd.linno = n->ncmd.linno;
  8048. break;
  8049. case NPIPE:
  8050. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8051. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8052. break;
  8053. case NREDIR:
  8054. case NBACKGND:
  8055. case NSUBSHELL:
  8056. new->nredir.redirect = copynode(n->nredir.redirect);
  8057. new->nredir.n = copynode(n->nredir.n);
  8058. new->nredir.linno = n->nredir.linno;
  8059. break;
  8060. case NAND:
  8061. case NOR:
  8062. case NSEMI:
  8063. case NWHILE:
  8064. case NUNTIL:
  8065. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8066. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8067. break;
  8068. case NIF:
  8069. new->nif.elsepart = copynode(n->nif.elsepart);
  8070. new->nif.ifpart = copynode(n->nif.ifpart);
  8071. new->nif.test = copynode(n->nif.test);
  8072. break;
  8073. case NFOR:
  8074. new->nfor.var = nodeckstrdup(n->nfor.var);
  8075. new->nfor.body = copynode(n->nfor.body);
  8076. new->nfor.args = copynode(n->nfor.args);
  8077. new->nfor.linno = n->nfor.linno;
  8078. break;
  8079. case NCASE:
  8080. new->ncase.cases = copynode(n->ncase.cases);
  8081. new->ncase.expr = copynode(n->ncase.expr);
  8082. new->ncase.linno = n->ncase.linno;
  8083. break;
  8084. case NCLIST:
  8085. new->nclist.body = copynode(n->nclist.body);
  8086. new->nclist.pattern = copynode(n->nclist.pattern);
  8087. new->nclist.next = copynode(n->nclist.next);
  8088. break;
  8089. case NDEFUN:
  8090. new->ndefun.body = copynode(n->ndefun.body);
  8091. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8092. new->ndefun.linno = n->ndefun.linno;
  8093. break;
  8094. case NARG:
  8095. new->narg.backquote = copynodelist(n->narg.backquote);
  8096. new->narg.text = nodeckstrdup(n->narg.text);
  8097. new->narg.next = copynode(n->narg.next);
  8098. break;
  8099. case NTO:
  8100. #if BASH_REDIR_OUTPUT
  8101. case NTO2:
  8102. #endif
  8103. case NCLOBBER:
  8104. case NFROM:
  8105. case NFROMTO:
  8106. case NAPPEND:
  8107. new->nfile.fname = copynode(n->nfile.fname);
  8108. new->nfile.fd = n->nfile.fd;
  8109. new->nfile.next = copynode(n->nfile.next);
  8110. break;
  8111. case NTOFD:
  8112. case NFROMFD:
  8113. new->ndup.vname = copynode(n->ndup.vname);
  8114. new->ndup.dupfd = n->ndup.dupfd;
  8115. new->ndup.fd = n->ndup.fd;
  8116. new->ndup.next = copynode(n->ndup.next);
  8117. break;
  8118. case NHERE:
  8119. case NXHERE:
  8120. new->nhere.doc = copynode(n->nhere.doc);
  8121. new->nhere.fd = n->nhere.fd;
  8122. new->nhere.next = copynode(n->nhere.next);
  8123. break;
  8124. case NNOT:
  8125. new->nnot.com = copynode(n->nnot.com);
  8126. break;
  8127. };
  8128. new->type = n->type;
  8129. return new;
  8130. }
  8131. /*
  8132. * Make a copy of a parse tree.
  8133. */
  8134. static struct funcnode *
  8135. copyfunc(union node *n)
  8136. {
  8137. struct funcnode *f;
  8138. size_t blocksize;
  8139. /*funcstringsize = 0;*/
  8140. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8141. f = ckzalloc(blocksize /* + funcstringsize */);
  8142. funcblock = (char *) f + offsetof(struct funcnode, n);
  8143. funcstring_end = (char *) f + blocksize;
  8144. copynode(n);
  8145. /* f->count = 0; - ckzalloc did it */
  8146. return f;
  8147. }
  8148. /*
  8149. * Define a shell function.
  8150. */
  8151. static void
  8152. defun(union node *func)
  8153. {
  8154. struct cmdentry entry;
  8155. INT_OFF;
  8156. entry.cmdtype = CMDFUNCTION;
  8157. entry.u.func = copyfunc(func);
  8158. addcmdentry(func->ndefun.text, &entry);
  8159. INT_ON;
  8160. }
  8161. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8162. #define SKIPBREAK (1 << 0)
  8163. #define SKIPCONT (1 << 1)
  8164. #define SKIPFUNC (1 << 2)
  8165. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8166. static int skipcount; /* number of levels to skip */
  8167. static int loopnest; /* current loop nesting level */
  8168. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8169. /* Forward decl way out to parsing code - dotrap needs it */
  8170. static int evalstring(char *s, int flags);
  8171. /* Called to execute a trap.
  8172. * Single callsite - at the end of evaltree().
  8173. * If we return non-zero, evaltree raises EXEXIT exception.
  8174. *
  8175. * Perhaps we should avoid entering new trap handlers
  8176. * while we are executing a trap handler. [is it a TODO?]
  8177. */
  8178. static void
  8179. dotrap(void)
  8180. {
  8181. uint8_t *g;
  8182. int sig;
  8183. uint8_t last_status;
  8184. if (!pending_sig)
  8185. return;
  8186. last_status = exitstatus;
  8187. pending_sig = 0;
  8188. barrier();
  8189. TRACE(("dotrap entered\n"));
  8190. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8191. char *p;
  8192. if (!*g)
  8193. continue;
  8194. if (evalskip) {
  8195. pending_sig = sig;
  8196. break;
  8197. }
  8198. p = trap[sig];
  8199. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8200. * don't upset it by resetting gotsig[SIGINT-1] */
  8201. if (sig == SIGINT && !p)
  8202. continue;
  8203. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8204. *g = 0;
  8205. if (!p)
  8206. continue;
  8207. evalstring(p, 0);
  8208. }
  8209. exitstatus = last_status;
  8210. TRACE(("dotrap returns\n"));
  8211. }
  8212. /* forward declarations - evaluation is fairly recursive business... */
  8213. static int evalloop(union node *, int);
  8214. static int evalfor(union node *, int);
  8215. static int evalcase(union node *, int);
  8216. static int evalsubshell(union node *, int);
  8217. static void expredir(union node *);
  8218. static int evalpipe(union node *, int);
  8219. static int evalcommand(union node *, int);
  8220. static int evalbltin(const struct builtincmd *, int, char **, int);
  8221. static void prehash(union node *);
  8222. /*
  8223. * Evaluate a parse tree. The value is left in the global variable
  8224. * exitstatus.
  8225. */
  8226. static int
  8227. evaltree(union node *n, int flags)
  8228. {
  8229. int checkexit = 0;
  8230. int (*evalfn)(union node *, int);
  8231. int status = 0;
  8232. if (n == NULL) {
  8233. TRACE(("evaltree(NULL) called\n"));
  8234. goto out;
  8235. }
  8236. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8237. dotrap();
  8238. switch (n->type) {
  8239. default:
  8240. #if DEBUG
  8241. out1fmt("Node type = %d\n", n->type);
  8242. fflush_all();
  8243. break;
  8244. #endif
  8245. case NNOT:
  8246. status = !evaltree(n->nnot.com, EV_TESTED);
  8247. goto setstatus;
  8248. case NREDIR:
  8249. errlinno = lineno = n->nredir.linno;
  8250. if (funcline)
  8251. lineno -= funcline - 1;
  8252. expredir(n->nredir.redirect);
  8253. pushredir(n->nredir.redirect);
  8254. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8255. if (!status) {
  8256. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8257. }
  8258. if (n->nredir.redirect)
  8259. popredir(/*drop:*/ 0);
  8260. goto setstatus;
  8261. case NCMD:
  8262. evalfn = evalcommand;
  8263. checkexit:
  8264. if (eflag && !(flags & EV_TESTED))
  8265. checkexit = ~0;
  8266. goto calleval;
  8267. case NFOR:
  8268. evalfn = evalfor;
  8269. goto calleval;
  8270. case NWHILE:
  8271. case NUNTIL:
  8272. evalfn = evalloop;
  8273. goto calleval;
  8274. case NSUBSHELL:
  8275. case NBACKGND:
  8276. evalfn = evalsubshell;
  8277. goto checkexit;
  8278. case NPIPE:
  8279. evalfn = evalpipe;
  8280. goto checkexit;
  8281. case NCASE:
  8282. evalfn = evalcase;
  8283. goto calleval;
  8284. case NAND:
  8285. case NOR:
  8286. case NSEMI: {
  8287. #if NAND + 1 != NOR
  8288. #error NAND + 1 != NOR
  8289. #endif
  8290. #if NOR + 1 != NSEMI
  8291. #error NOR + 1 != NSEMI
  8292. #endif
  8293. unsigned is_or = n->type - NAND;
  8294. status = evaltree(
  8295. n->nbinary.ch1,
  8296. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8297. );
  8298. if ((!status) == is_or || evalskip)
  8299. break;
  8300. n = n->nbinary.ch2;
  8301. evaln:
  8302. evalfn = evaltree;
  8303. calleval:
  8304. status = evalfn(n, flags);
  8305. goto setstatus;
  8306. }
  8307. case NIF:
  8308. status = evaltree(n->nif.test, EV_TESTED);
  8309. if (evalskip)
  8310. break;
  8311. if (!status) {
  8312. n = n->nif.ifpart;
  8313. goto evaln;
  8314. }
  8315. if (n->nif.elsepart) {
  8316. n = n->nif.elsepart;
  8317. goto evaln;
  8318. }
  8319. status = 0;
  8320. goto setstatus;
  8321. case NDEFUN:
  8322. defun(n);
  8323. /* Not necessary. To test it:
  8324. * "false; f() { qwerty; }; echo $?" should print 0.
  8325. */
  8326. /* status = 0; */
  8327. setstatus:
  8328. exitstatus = status;
  8329. break;
  8330. }
  8331. out:
  8332. /* Order of checks below is important:
  8333. * signal handlers trigger before exit caused by "set -e".
  8334. */
  8335. dotrap();
  8336. if (checkexit & status)
  8337. raise_exception(EXEXIT);
  8338. if (flags & EV_EXIT)
  8339. raise_exception(EXEXIT);
  8340. TRACE(("leaving evaltree (no interrupts)\n"));
  8341. return exitstatus;
  8342. }
  8343. static int
  8344. skiploop(void)
  8345. {
  8346. int skip = evalskip;
  8347. switch (skip) {
  8348. case 0:
  8349. break;
  8350. case SKIPBREAK:
  8351. case SKIPCONT:
  8352. if (--skipcount <= 0) {
  8353. evalskip = 0;
  8354. break;
  8355. }
  8356. skip = SKIPBREAK;
  8357. break;
  8358. }
  8359. return skip;
  8360. }
  8361. static int
  8362. evalloop(union node *n, int flags)
  8363. {
  8364. int skip;
  8365. int status;
  8366. loopnest++;
  8367. status = 0;
  8368. flags &= EV_TESTED;
  8369. do {
  8370. int i;
  8371. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8372. skip = skiploop();
  8373. if (skip == SKIPFUNC)
  8374. status = i;
  8375. if (skip)
  8376. continue;
  8377. if (n->type != NWHILE)
  8378. i = !i;
  8379. if (i != 0)
  8380. break;
  8381. status = evaltree(n->nbinary.ch2, flags);
  8382. skip = skiploop();
  8383. } while (!(skip & ~SKIPCONT));
  8384. loopnest--;
  8385. return status;
  8386. }
  8387. static int
  8388. evalfor(union node *n, int flags)
  8389. {
  8390. struct arglist arglist;
  8391. union node *argp;
  8392. struct strlist *sp;
  8393. struct stackmark smark;
  8394. int status = 0;
  8395. errlinno = lineno = n->ncase.linno;
  8396. if (funcline)
  8397. lineno -= funcline - 1;
  8398. setstackmark(&smark);
  8399. arglist.list = NULL;
  8400. arglist.lastp = &arglist.list;
  8401. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8402. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8403. }
  8404. *arglist.lastp = NULL;
  8405. loopnest++;
  8406. flags &= EV_TESTED;
  8407. for (sp = arglist.list; sp; sp = sp->next) {
  8408. setvar0(n->nfor.var, sp->text);
  8409. status = evaltree(n->nfor.body, flags);
  8410. if (skiploop() & ~SKIPCONT)
  8411. break;
  8412. }
  8413. loopnest--;
  8414. popstackmark(&smark);
  8415. return status;
  8416. }
  8417. static int
  8418. evalcase(union node *n, int flags)
  8419. {
  8420. union node *cp;
  8421. union node *patp;
  8422. struct arglist arglist;
  8423. struct stackmark smark;
  8424. int status = 0;
  8425. errlinno = lineno = n->ncase.linno;
  8426. if (funcline)
  8427. lineno -= funcline - 1;
  8428. setstackmark(&smark);
  8429. arglist.list = NULL;
  8430. arglist.lastp = &arglist.list;
  8431. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8432. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8433. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8434. if (casematch(patp, arglist.list->text)) {
  8435. /* Ensure body is non-empty as otherwise
  8436. * EV_EXIT may prevent us from setting the
  8437. * exit status.
  8438. */
  8439. if (evalskip == 0 && cp->nclist.body) {
  8440. status = evaltree(cp->nclist.body, flags);
  8441. }
  8442. goto out;
  8443. }
  8444. }
  8445. }
  8446. out:
  8447. popstackmark(&smark);
  8448. return status;
  8449. }
  8450. /*
  8451. * Kick off a subshell to evaluate a tree.
  8452. */
  8453. static int
  8454. evalsubshell(union node *n, int flags)
  8455. {
  8456. struct job *jp;
  8457. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8458. int status;
  8459. errlinno = lineno = n->nredir.linno;
  8460. if (funcline)
  8461. lineno -= funcline - 1;
  8462. expredir(n->nredir.redirect);
  8463. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8464. goto nofork;
  8465. INT_OFF;
  8466. if (backgnd == FORK_FG)
  8467. get_tty_state();
  8468. jp = makejob(/*n,*/ 1);
  8469. if (forkshell(jp, n, backgnd) == 0) {
  8470. /* child */
  8471. INT_ON;
  8472. flags |= EV_EXIT;
  8473. if (backgnd)
  8474. flags &= ~EV_TESTED;
  8475. nofork:
  8476. redirect(n->nredir.redirect, 0);
  8477. evaltreenr(n->nredir.n, flags);
  8478. /* never returns */
  8479. }
  8480. /* parent */
  8481. status = 0;
  8482. if (backgnd == FORK_FG)
  8483. status = waitforjob(jp);
  8484. INT_ON;
  8485. return status;
  8486. }
  8487. /*
  8488. * Compute the names of the files in a redirection list.
  8489. */
  8490. static void fixredir(union node *, const char *, int);
  8491. static void
  8492. expredir(union node *n)
  8493. {
  8494. union node *redir;
  8495. for (redir = n; redir; redir = redir->nfile.next) {
  8496. struct arglist fn;
  8497. fn.list = NULL;
  8498. fn.lastp = &fn.list;
  8499. switch (redir->type) {
  8500. case NFROMTO:
  8501. case NFROM:
  8502. case NTO:
  8503. #if BASH_REDIR_OUTPUT
  8504. case NTO2:
  8505. #endif
  8506. case NCLOBBER:
  8507. case NAPPEND:
  8508. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8509. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8510. #if BASH_REDIR_OUTPUT
  8511. store_expfname:
  8512. #endif
  8513. #if 0
  8514. // By the design of stack allocator, the loop of this kind:
  8515. // while true; do while true; do break; done </dev/null; done
  8516. // will look like a memory leak: ash plans to free expfname's
  8517. // of "/dev/null" as soon as it finishes running the loop
  8518. // (in this case, never).
  8519. // This "fix" is wrong:
  8520. if (redir->nfile.expfname)
  8521. stunalloc(redir->nfile.expfname);
  8522. // It results in corrupted state of stacked allocations.
  8523. #endif
  8524. redir->nfile.expfname = fn.list->text;
  8525. break;
  8526. case NFROMFD:
  8527. case NTOFD: /* >& */
  8528. if (redir->ndup.vname) {
  8529. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8530. if (fn.list == NULL)
  8531. ash_msg_and_raise_error("redir error");
  8532. #if BASH_REDIR_OUTPUT
  8533. //FIXME: we used expandarg with different args!
  8534. if (!isdigit_str9(fn.list->text)) {
  8535. /* >&file, not >&fd */
  8536. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8537. ash_msg_and_raise_error("redir error");
  8538. redir->type = NTO2;
  8539. goto store_expfname;
  8540. }
  8541. #endif
  8542. fixredir(redir, fn.list->text, 1);
  8543. }
  8544. break;
  8545. }
  8546. }
  8547. }
  8548. /*
  8549. * Evaluate a pipeline. All the processes in the pipeline are children
  8550. * of the process creating the pipeline. (This differs from some versions
  8551. * of the shell, which make the last process in a pipeline the parent
  8552. * of all the rest.)
  8553. */
  8554. static int
  8555. evalpipe(union node *n, int flags)
  8556. {
  8557. struct job *jp;
  8558. struct nodelist *lp;
  8559. int pipelen;
  8560. int prevfd;
  8561. int pip[2];
  8562. int status = 0;
  8563. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8564. pipelen = 0;
  8565. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8566. pipelen++;
  8567. flags |= EV_EXIT;
  8568. INT_OFF;
  8569. if (n->npipe.pipe_backgnd == 0)
  8570. get_tty_state();
  8571. jp = makejob(/*n,*/ pipelen);
  8572. prevfd = -1;
  8573. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8574. prehash(lp->n);
  8575. pip[1] = -1;
  8576. if (lp->next) {
  8577. if (pipe(pip) < 0) {
  8578. close(prevfd);
  8579. ash_msg_and_raise_perror("can't create pipe");
  8580. }
  8581. }
  8582. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8583. /* child */
  8584. INT_ON;
  8585. if (pip[1] >= 0) {
  8586. close(pip[0]);
  8587. }
  8588. if (prevfd > 0) {
  8589. dup2(prevfd, 0);
  8590. close(prevfd);
  8591. }
  8592. if (pip[1] > 1) {
  8593. dup2(pip[1], 1);
  8594. close(pip[1]);
  8595. }
  8596. evaltreenr(lp->n, flags);
  8597. /* never returns */
  8598. }
  8599. /* parent */
  8600. if (prevfd >= 0)
  8601. close(prevfd);
  8602. prevfd = pip[0];
  8603. /* Don't want to trigger debugging */
  8604. if (pip[1] != -1)
  8605. close(pip[1]);
  8606. }
  8607. if (n->npipe.pipe_backgnd == 0) {
  8608. status = waitforjob(jp);
  8609. TRACE(("evalpipe: job done exit status %d\n", status));
  8610. }
  8611. INT_ON;
  8612. return status;
  8613. }
  8614. /*
  8615. * Controls whether the shell is interactive or not.
  8616. */
  8617. static void
  8618. setinteractive(int on)
  8619. {
  8620. static smallint is_interactive;
  8621. if (++on == is_interactive)
  8622. return;
  8623. is_interactive = on;
  8624. setsignal(SIGINT);
  8625. setsignal(SIGQUIT);
  8626. setsignal(SIGTERM);
  8627. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8628. if (is_interactive > 1) {
  8629. /* Looks like they want an interactive shell */
  8630. static smallint did_banner;
  8631. if (!did_banner) {
  8632. /* note: ash and hush share this string */
  8633. out1fmt("\n\n%s %s\n"
  8634. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8635. "\n",
  8636. bb_banner,
  8637. "built-in shell (ash)"
  8638. );
  8639. did_banner = 1;
  8640. }
  8641. }
  8642. #endif
  8643. }
  8644. static void
  8645. optschanged(void)
  8646. {
  8647. #if DEBUG
  8648. opentrace();
  8649. #endif
  8650. setinteractive(iflag);
  8651. setjobctl(mflag);
  8652. #if ENABLE_FEATURE_EDITING_VI
  8653. if (viflag)
  8654. line_input_state->flags |= VI_MODE;
  8655. else
  8656. line_input_state->flags &= ~VI_MODE;
  8657. #else
  8658. viflag = 0; /* forcibly keep the option off */
  8659. #endif
  8660. }
  8661. struct localvar_list {
  8662. struct localvar_list *next;
  8663. struct localvar *lv;
  8664. };
  8665. static struct localvar_list *localvar_stack;
  8666. /*
  8667. * Called after a function returns.
  8668. * Interrupts must be off.
  8669. */
  8670. static void
  8671. poplocalvars(int keep)
  8672. {
  8673. struct localvar_list *ll;
  8674. struct localvar *lvp, *next;
  8675. struct var *vp;
  8676. INT_OFF;
  8677. ll = localvar_stack;
  8678. localvar_stack = ll->next;
  8679. next = ll->lv;
  8680. free(ll);
  8681. while ((lvp = next) != NULL) {
  8682. next = lvp->next;
  8683. vp = lvp->vp;
  8684. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8685. if (keep) {
  8686. int bits = VSTRFIXED;
  8687. if (lvp->flags != VUNSET) {
  8688. if (vp->var_text == lvp->text)
  8689. bits |= VTEXTFIXED;
  8690. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8691. free((char*)lvp->text);
  8692. }
  8693. vp->flags &= ~bits;
  8694. vp->flags |= (lvp->flags & bits);
  8695. if ((vp->flags &
  8696. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8697. unsetvar(vp->var_text);
  8698. } else if (vp == NULL) { /* $- saved */
  8699. memcpy(optlist, lvp->text, sizeof(optlist));
  8700. free((char*)lvp->text);
  8701. optschanged();
  8702. } else if (lvp->flags == VUNSET) {
  8703. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8704. unsetvar(vp->var_text);
  8705. } else {
  8706. if (vp->var_func)
  8707. vp->var_func(var_end(lvp->text));
  8708. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8709. free((char*)vp->var_text);
  8710. vp->flags = lvp->flags;
  8711. vp->var_text = lvp->text;
  8712. }
  8713. free(lvp);
  8714. }
  8715. INT_ON;
  8716. }
  8717. /*
  8718. * Create a new localvar environment.
  8719. */
  8720. static struct localvar_list *
  8721. pushlocalvars(void)
  8722. {
  8723. struct localvar_list *ll;
  8724. INT_OFF;
  8725. ll = ckzalloc(sizeof(*ll));
  8726. /*ll->lv = NULL; - zalloc did it */
  8727. ll->next = localvar_stack;
  8728. localvar_stack = ll;
  8729. INT_ON;
  8730. return ll->next;
  8731. }
  8732. static void
  8733. unwindlocalvars(struct localvar_list *stop)
  8734. {
  8735. while (localvar_stack != stop)
  8736. poplocalvars(0);
  8737. }
  8738. static int
  8739. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8740. {
  8741. volatile struct shparam saveparam;
  8742. struct jmploc *volatile savehandler;
  8743. struct jmploc jmploc;
  8744. int e;
  8745. int savefuncline;
  8746. saveparam = shellparam;
  8747. savefuncline = funcline;
  8748. savehandler = exception_handler;
  8749. e = setjmp(jmploc.loc);
  8750. if (e) {
  8751. goto funcdone;
  8752. }
  8753. INT_OFF;
  8754. exception_handler = &jmploc;
  8755. shellparam.malloced = 0;
  8756. func->count++;
  8757. funcline = func->n.ndefun.linno;
  8758. INT_ON;
  8759. shellparam.nparam = argc - 1;
  8760. shellparam.p = argv + 1;
  8761. #if ENABLE_ASH_GETOPTS
  8762. shellparam.optind = 1;
  8763. shellparam.optoff = -1;
  8764. #endif
  8765. pushlocalvars();
  8766. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8767. poplocalvars(0);
  8768. funcdone:
  8769. INT_OFF;
  8770. funcline = savefuncline;
  8771. freefunc(func);
  8772. freeparam(&shellparam);
  8773. shellparam = saveparam;
  8774. exception_handler = savehandler;
  8775. INT_ON;
  8776. evalskip &= ~SKIPFUNC;
  8777. return e;
  8778. }
  8779. /*
  8780. * Make a variable a local variable. When a variable is made local, it's
  8781. * value and flags are saved in a localvar structure. The saved values
  8782. * will be restored when the shell function returns. We handle the name
  8783. * "-" as a special case: it makes changes to "set +-options" local
  8784. * (options will be restored on return from the function).
  8785. */
  8786. static void
  8787. mklocal(char *name)
  8788. {
  8789. struct localvar *lvp;
  8790. struct var **vpp;
  8791. struct var *vp;
  8792. char *eq = strchr(name, '=');
  8793. INT_OFF;
  8794. /* Cater for duplicate "local". Examples:
  8795. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8796. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8797. */
  8798. lvp = localvar_stack->lv;
  8799. while (lvp) {
  8800. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8801. if (eq)
  8802. setvareq(name, 0);
  8803. /* else:
  8804. * it's a duplicate "local VAR" declaration, do nothing
  8805. */
  8806. goto ret;
  8807. }
  8808. lvp = lvp->next;
  8809. }
  8810. lvp = ckzalloc(sizeof(*lvp));
  8811. if (LONE_DASH(name)) {
  8812. char *p;
  8813. p = ckmalloc(sizeof(optlist));
  8814. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8815. vp = NULL;
  8816. } else {
  8817. vpp = hashvar(name);
  8818. vp = *findvar(vpp, name);
  8819. if (vp == NULL) {
  8820. /* variable did not exist yet */
  8821. if (eq)
  8822. vp = setvareq(name, VSTRFIXED);
  8823. else
  8824. vp = setvar(name, NULL, VSTRFIXED);
  8825. lvp->flags = VUNSET;
  8826. } else {
  8827. lvp->text = vp->var_text;
  8828. lvp->flags = vp->flags;
  8829. /* make sure neither "struct var" nor string gets freed
  8830. * during (un)setting:
  8831. */
  8832. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8833. if (eq)
  8834. setvareq(name, 0);
  8835. else
  8836. /* "local VAR" unsets VAR: */
  8837. setvar0(name, NULL);
  8838. }
  8839. }
  8840. lvp->vp = vp;
  8841. lvp->next = localvar_stack->lv;
  8842. localvar_stack->lv = lvp;
  8843. ret:
  8844. INT_ON;
  8845. }
  8846. /*
  8847. * The "local" command.
  8848. */
  8849. static int FAST_FUNC
  8850. localcmd(int argc UNUSED_PARAM, char **argv)
  8851. {
  8852. char *name;
  8853. if (!localvar_stack)
  8854. ash_msg_and_raise_error("not in a function");
  8855. argv = argptr;
  8856. while ((name = *argv++) != NULL) {
  8857. mklocal(name);
  8858. }
  8859. return 0;
  8860. }
  8861. static int FAST_FUNC
  8862. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8863. {
  8864. return 1;
  8865. }
  8866. static int FAST_FUNC
  8867. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8868. {
  8869. return 0;
  8870. }
  8871. static int FAST_FUNC
  8872. execcmd(int argc UNUSED_PARAM, char **argv)
  8873. {
  8874. optionarg = NULL;
  8875. while (nextopt("a:") != '\0')
  8876. /* nextopt() sets optionarg to "-a ARGV0" */;
  8877. argv = argptr;
  8878. if (argv[0]) {
  8879. char *prog;
  8880. iflag = 0; /* exit on error */
  8881. mflag = 0;
  8882. optschanged();
  8883. /* We should set up signals for "exec CMD"
  8884. * the same way as for "CMD" without "exec".
  8885. * But optschanged->setinteractive->setsignal
  8886. * still thought we are a root shell. Therefore, for example,
  8887. * SIGQUIT is still set to IGN. Fix it:
  8888. */
  8889. shlvl++;
  8890. setsignal(SIGQUIT);
  8891. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8892. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8893. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8894. prog = argv[0];
  8895. if (optionarg)
  8896. argv[0] = optionarg;
  8897. shellexec(prog, argv, pathval(), 0);
  8898. /* NOTREACHED */
  8899. }
  8900. return 0;
  8901. }
  8902. /*
  8903. * The return command.
  8904. */
  8905. static int FAST_FUNC
  8906. returncmd(int argc UNUSED_PARAM, char **argv)
  8907. {
  8908. /*
  8909. * If called outside a function, do what ksh does;
  8910. * skip the rest of the file.
  8911. */
  8912. evalskip = SKIPFUNC;
  8913. return argv[1] ? number(argv[1]) : exitstatus;
  8914. }
  8915. /* Forward declarations for builtintab[] */
  8916. static int breakcmd(int, char **) FAST_FUNC;
  8917. static int dotcmd(int, char **) FAST_FUNC;
  8918. static int evalcmd(int, char **, int) FAST_FUNC;
  8919. static int exitcmd(int, char **) FAST_FUNC;
  8920. static int exportcmd(int, char **) FAST_FUNC;
  8921. #if ENABLE_ASH_GETOPTS
  8922. static int getoptscmd(int, char **) FAST_FUNC;
  8923. #endif
  8924. #if ENABLE_ASH_HELP
  8925. static int helpcmd(int, char **) FAST_FUNC;
  8926. #endif
  8927. #if MAX_HISTORY
  8928. static int historycmd(int, char **) FAST_FUNC;
  8929. #endif
  8930. #if ENABLE_FEATURE_SH_MATH
  8931. static int letcmd(int, char **) FAST_FUNC;
  8932. #endif
  8933. static int readcmd(int, char **) FAST_FUNC;
  8934. static int setcmd(int, char **) FAST_FUNC;
  8935. static int shiftcmd(int, char **) FAST_FUNC;
  8936. static int timescmd(int, char **) FAST_FUNC;
  8937. static int trapcmd(int, char **) FAST_FUNC;
  8938. static int umaskcmd(int, char **) FAST_FUNC;
  8939. static int unsetcmd(int, char **) FAST_FUNC;
  8940. static int ulimitcmd(int, char **) FAST_FUNC;
  8941. #define BUILTIN_NOSPEC "0"
  8942. #define BUILTIN_SPECIAL "1"
  8943. #define BUILTIN_REGULAR "2"
  8944. #define BUILTIN_SPEC_REG "3"
  8945. #define BUILTIN_ASSIGN "4"
  8946. #define BUILTIN_SPEC_ASSG "5"
  8947. #define BUILTIN_REG_ASSG "6"
  8948. #define BUILTIN_SPEC_REG_ASSG "7"
  8949. /* Stubs for calling non-FAST_FUNC's */
  8950. #if ENABLE_ASH_ECHO
  8951. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8952. #endif
  8953. #if ENABLE_ASH_PRINTF
  8954. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8955. #endif
  8956. #if ENABLE_ASH_TEST || BASH_TEST2
  8957. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8958. #endif
  8959. /* Keep these in proper order since it is searched via bsearch() */
  8960. static const struct builtincmd builtintab[] = {
  8961. { BUILTIN_SPEC_REG "." , dotcmd },
  8962. { BUILTIN_SPEC_REG ":" , truecmd },
  8963. #if ENABLE_ASH_TEST
  8964. { BUILTIN_REGULAR "[" , testcmd },
  8965. #endif
  8966. #if BASH_TEST2
  8967. { BUILTIN_REGULAR "[[" , testcmd },
  8968. #endif
  8969. #if ENABLE_ASH_ALIAS
  8970. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8971. #endif
  8972. #if JOBS
  8973. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8974. #endif
  8975. { BUILTIN_SPEC_REG "break" , breakcmd },
  8976. { BUILTIN_REGULAR "cd" , cdcmd },
  8977. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8978. #if ENABLE_ASH_CMDCMD
  8979. { BUILTIN_REGULAR "command" , commandcmd },
  8980. #endif
  8981. { BUILTIN_SPEC_REG "continue", breakcmd },
  8982. #if ENABLE_ASH_ECHO
  8983. { BUILTIN_REGULAR "echo" , echocmd },
  8984. #endif
  8985. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  8986. { BUILTIN_SPEC_REG "exec" , execcmd },
  8987. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8988. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8989. { BUILTIN_REGULAR "false" , falsecmd },
  8990. #if JOBS
  8991. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8992. #endif
  8993. #if ENABLE_ASH_GETOPTS
  8994. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8995. #endif
  8996. { BUILTIN_NOSPEC "hash" , hashcmd },
  8997. #if ENABLE_ASH_HELP
  8998. { BUILTIN_NOSPEC "help" , helpcmd },
  8999. #endif
  9000. #if MAX_HISTORY
  9001. { BUILTIN_NOSPEC "history" , historycmd },
  9002. #endif
  9003. #if JOBS
  9004. { BUILTIN_REGULAR "jobs" , jobscmd },
  9005. { BUILTIN_REGULAR "kill" , killcmd },
  9006. #endif
  9007. #if ENABLE_FEATURE_SH_MATH
  9008. { BUILTIN_NOSPEC "let" , letcmd },
  9009. #endif
  9010. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9011. #if ENABLE_ASH_PRINTF
  9012. { BUILTIN_REGULAR "printf" , printfcmd },
  9013. #endif
  9014. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9015. { BUILTIN_REGULAR "read" , readcmd },
  9016. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9017. { BUILTIN_SPEC_REG "return" , returncmd },
  9018. { BUILTIN_SPEC_REG "set" , setcmd },
  9019. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9020. #if BASH_SOURCE
  9021. { BUILTIN_SPEC_REG "source" , dotcmd },
  9022. #endif
  9023. #if ENABLE_ASH_TEST
  9024. { BUILTIN_REGULAR "test" , testcmd },
  9025. #endif
  9026. { BUILTIN_SPEC_REG "times" , timescmd },
  9027. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9028. { BUILTIN_REGULAR "true" , truecmd },
  9029. { BUILTIN_NOSPEC "type" , typecmd },
  9030. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9031. { BUILTIN_REGULAR "umask" , umaskcmd },
  9032. #if ENABLE_ASH_ALIAS
  9033. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9034. #endif
  9035. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9036. { BUILTIN_REGULAR "wait" , waitcmd },
  9037. };
  9038. /* Should match the above table! */
  9039. #define COMMANDCMD (builtintab + \
  9040. /* . : */ 2 + \
  9041. /* [ */ 1 * ENABLE_ASH_TEST + \
  9042. /* [[ */ 1 * BASH_TEST2 + \
  9043. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9044. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9045. /* break cd cddir */ 3)
  9046. #define EVALCMD (COMMANDCMD + \
  9047. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9048. /* continue */ 1 + \
  9049. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9050. 0)
  9051. #define EXECCMD (EVALCMD + \
  9052. /* eval */ 1)
  9053. /*
  9054. * Search the table of builtin commands.
  9055. */
  9056. static int
  9057. pstrcmp1(const void *a, const void *b)
  9058. {
  9059. return strcmp((char*)a, *(char**)b + 1);
  9060. }
  9061. static struct builtincmd *
  9062. find_builtin(const char *name)
  9063. {
  9064. struct builtincmd *bp;
  9065. bp = bsearch(
  9066. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9067. pstrcmp1
  9068. );
  9069. return bp;
  9070. }
  9071. /*
  9072. * Execute a simple command.
  9073. */
  9074. static int
  9075. isassignment(const char *p)
  9076. {
  9077. const char *q = endofname(p);
  9078. if (p == q)
  9079. return 0;
  9080. return *q == '=';
  9081. }
  9082. static int FAST_FUNC
  9083. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9084. {
  9085. /* Preserve exitstatus of a previous possible redirection
  9086. * as POSIX mandates */
  9087. return back_exitstatus;
  9088. }
  9089. static int
  9090. evalcommand(union node *cmd, int flags)
  9091. {
  9092. static const struct builtincmd null_bltin = {
  9093. "\0\0", bltincmd /* why three NULs? */
  9094. };
  9095. struct localvar_list *localvar_stop;
  9096. struct redirtab *redir_stop;
  9097. struct stackmark smark;
  9098. union node *argp;
  9099. struct arglist arglist;
  9100. struct arglist varlist;
  9101. char **argv;
  9102. int argc;
  9103. const struct strlist *sp;
  9104. struct cmdentry cmdentry;
  9105. struct job *jp;
  9106. char *lastarg;
  9107. const char *path;
  9108. int spclbltin;
  9109. int status;
  9110. char **nargv;
  9111. smallint cmd_is_exec;
  9112. errlinno = lineno = cmd->ncmd.linno;
  9113. if (funcline)
  9114. lineno -= funcline - 1;
  9115. /* First expand the arguments. */
  9116. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9117. setstackmark(&smark);
  9118. localvar_stop = pushlocalvars();
  9119. back_exitstatus = 0;
  9120. cmdentry.cmdtype = CMDBUILTIN;
  9121. cmdentry.u.cmd = &null_bltin;
  9122. varlist.lastp = &varlist.list;
  9123. *varlist.lastp = NULL;
  9124. arglist.lastp = &arglist.list;
  9125. *arglist.lastp = NULL;
  9126. argc = 0;
  9127. if (cmd->ncmd.args) {
  9128. struct builtincmd *bcmd;
  9129. smallint pseudovarflag;
  9130. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9131. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9132. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9133. struct strlist **spp;
  9134. spp = arglist.lastp;
  9135. if (pseudovarflag && isassignment(argp->narg.text))
  9136. expandarg(argp, &arglist, EXP_VARTILDE);
  9137. else
  9138. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9139. for (sp = *spp; sp; sp = sp->next)
  9140. argc++;
  9141. }
  9142. }
  9143. /* Reserve one extra spot at the front for shellexec. */
  9144. nargv = stalloc(sizeof(char *) * (argc + 2));
  9145. argv = ++nargv;
  9146. for (sp = arglist.list; sp; sp = sp->next) {
  9147. TRACE(("evalcommand arg: %s\n", sp->text));
  9148. *nargv++ = sp->text;
  9149. }
  9150. *nargv = NULL;
  9151. lastarg = NULL;
  9152. if (iflag && funcline == 0 && argc > 0)
  9153. lastarg = nargv[-1];
  9154. expredir(cmd->ncmd.redirect);
  9155. redir_stop = pushredir(cmd->ncmd.redirect);
  9156. preverrout_fd = 2;
  9157. if (BASH_XTRACEFD && xflag) {
  9158. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9159. * we do not emulate this. We only use its value.
  9160. */
  9161. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9162. if (xtracefd && is_number(xtracefd))
  9163. preverrout_fd = atoi(xtracefd);
  9164. }
  9165. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9166. path = vpath.var_text;
  9167. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9168. struct strlist **spp;
  9169. char *p;
  9170. spp = varlist.lastp;
  9171. expandarg(argp, &varlist, EXP_VARTILDE);
  9172. mklocal((*spp)->text);
  9173. /*
  9174. * Modify the command lookup path, if a PATH= assignment
  9175. * is present
  9176. */
  9177. p = (*spp)->text;
  9178. if (varcmp(p, path) == 0)
  9179. path = p;
  9180. }
  9181. /* Print the command if xflag is set. */
  9182. if (xflag) {
  9183. const char *pfx = "";
  9184. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9185. sp = varlist.list;
  9186. while (sp) {
  9187. char *varval = sp->text;
  9188. char *eq = strchrnul(varval, '=');
  9189. if (*eq)
  9190. eq++;
  9191. fdprintf(preverrout_fd, "%s%.*s%s",
  9192. pfx,
  9193. (int)(eq - varval), varval,
  9194. maybe_single_quote(eq)
  9195. );
  9196. sp = sp->next;
  9197. pfx = " ";
  9198. }
  9199. sp = arglist.list;
  9200. while (sp) {
  9201. fdprintf(preverrout_fd, "%s%s",
  9202. pfx,
  9203. /* always quote if matches reserved word: */
  9204. findkwd(sp->text)
  9205. ? single_quote(sp->text)
  9206. : maybe_single_quote(sp->text)
  9207. );
  9208. sp = sp->next;
  9209. pfx = " ";
  9210. }
  9211. safe_write(preverrout_fd, "\n", 1);
  9212. }
  9213. cmd_is_exec = 0;
  9214. spclbltin = -1;
  9215. /* Now locate the command. */
  9216. if (argc) {
  9217. int cmd_flag = DO_ERR;
  9218. #if ENABLE_ASH_CMDCMD
  9219. const char *oldpath = path + 5;
  9220. #endif
  9221. path += 5;
  9222. for (;;) {
  9223. find_command(argv[0], &cmdentry, cmd_flag, path);
  9224. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9225. flush_stdout_stderr();
  9226. status = 127;
  9227. goto bail;
  9228. }
  9229. /* implement bltin and command here */
  9230. if (cmdentry.cmdtype != CMDBUILTIN)
  9231. break;
  9232. if (spclbltin < 0)
  9233. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9234. if (cmdentry.u.cmd == EXECCMD)
  9235. cmd_is_exec = 1;
  9236. #if ENABLE_ASH_CMDCMD
  9237. if (cmdentry.u.cmd == COMMANDCMD) {
  9238. path = oldpath;
  9239. nargv = parse_command_args(argv, &path);
  9240. if (!nargv)
  9241. break;
  9242. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9243. * nargv => "PROG". path is updated if -p.
  9244. */
  9245. argc -= nargv - argv;
  9246. argv = nargv;
  9247. cmd_flag |= DO_NOFUNC;
  9248. } else
  9249. #endif
  9250. break;
  9251. }
  9252. }
  9253. if (status) {
  9254. bail:
  9255. exitstatus = status;
  9256. /* We have a redirection error. */
  9257. if (spclbltin > 0)
  9258. raise_exception(EXERROR);
  9259. goto out;
  9260. }
  9261. /* Execute the command. */
  9262. switch (cmdentry.cmdtype) {
  9263. default: {
  9264. #if ENABLE_FEATURE_SH_STANDALONE \
  9265. && ENABLE_FEATURE_SH_NOFORK \
  9266. && NUM_APPLETS > 1
  9267. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9268. * around run_nofork_applet() call.
  9269. * (2) Should this check also be done in forkshell()?
  9270. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9271. */
  9272. /* find_command() encodes applet_no as (-2 - applet_no) */
  9273. int applet_no = (- cmdentry.u.index - 2);
  9274. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9275. char **sv_environ;
  9276. INT_OFF;
  9277. sv_environ = environ;
  9278. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9279. /*
  9280. * Run <applet>_main().
  9281. * Signals (^C) can't interrupt here.
  9282. * Otherwise we can mangle stdio or malloc internal state.
  9283. * This makes applets which can run for a long time
  9284. * and/or wait for user input ineligible for NOFORK:
  9285. * for example, "yes" or "rm" (rm -i waits for input).
  9286. */
  9287. status = run_nofork_applet(applet_no, argv);
  9288. environ = sv_environ;
  9289. /*
  9290. * Try enabling NOFORK for "yes" applet.
  9291. * ^C _will_ stop it (write returns EINTR),
  9292. * but this causes stdout FILE to be stuck
  9293. * and needing clearerr(). What if other applets
  9294. * also can get EINTRs? Do we need to switch
  9295. * our signals to SA_RESTART?
  9296. */
  9297. /*clearerr(stdout);*/
  9298. INT_ON;
  9299. break;
  9300. }
  9301. #endif
  9302. /* Can we avoid forking? For example, very last command
  9303. * in a script or a subshell does not need forking,
  9304. * we can just exec it.
  9305. */
  9306. if (!(flags & EV_EXIT) || may_have_traps) {
  9307. /* No, forking off a child is necessary */
  9308. INT_OFF;
  9309. get_tty_state();
  9310. jp = makejob(/*cmd,*/ 1);
  9311. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9312. /* parent */
  9313. status = waitforjob(jp);
  9314. INT_ON;
  9315. TRACE(("forked child exited with %d\n", status));
  9316. break;
  9317. }
  9318. /* child */
  9319. FORCE_INT_ON;
  9320. /* fall through to exec'ing external program */
  9321. }
  9322. listsetvar(varlist.list, VEXPORT|VSTACK);
  9323. shellexec(argv[0], argv, path, cmdentry.u.index);
  9324. /* NOTREACHED */
  9325. } /* default */
  9326. case CMDBUILTIN:
  9327. if (spclbltin > 0 || argc == 0) {
  9328. poplocalvars(1);
  9329. if (cmd_is_exec && argc > 1)
  9330. listsetvar(varlist.list, VEXPORT);
  9331. }
  9332. /* Tight loop with builtins only:
  9333. * "while kill -0 $child; do true; done"
  9334. * will never exit even if $child died, unless we do this
  9335. * to reap the zombie and make kill detect that it's gone: */
  9336. dowait(DOWAIT_NONBLOCK, NULL);
  9337. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9338. if (exception_type == EXERROR && spclbltin <= 0) {
  9339. FORCE_INT_ON;
  9340. goto readstatus;
  9341. }
  9342. raise:
  9343. longjmp(exception_handler->loc, 1);
  9344. }
  9345. goto readstatus;
  9346. case CMDFUNCTION:
  9347. poplocalvars(1);
  9348. /* See above for the rationale */
  9349. dowait(DOWAIT_NONBLOCK, NULL);
  9350. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9351. goto raise;
  9352. readstatus:
  9353. status = exitstatus;
  9354. break;
  9355. } /* switch */
  9356. out:
  9357. if (cmd->ncmd.redirect)
  9358. popredir(/*drop:*/ cmd_is_exec);
  9359. unwindredir(redir_stop);
  9360. unwindlocalvars(localvar_stop);
  9361. if (lastarg) {
  9362. /* dsl: I think this is intended to be used to support
  9363. * '_' in 'vi' command mode during line editing...
  9364. * However I implemented that within libedit itself.
  9365. */
  9366. setvar0("_", lastarg);
  9367. }
  9368. popstackmark(&smark);
  9369. return status;
  9370. }
  9371. static int
  9372. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9373. {
  9374. char *volatile savecmdname;
  9375. struct jmploc *volatile savehandler;
  9376. struct jmploc jmploc;
  9377. int status;
  9378. int i;
  9379. savecmdname = commandname;
  9380. savehandler = exception_handler;
  9381. i = setjmp(jmploc.loc);
  9382. if (i)
  9383. goto cmddone;
  9384. exception_handler = &jmploc;
  9385. commandname = argv[0];
  9386. argptr = argv + 1;
  9387. optptr = NULL; /* initialize nextopt */
  9388. if (cmd == EVALCMD)
  9389. status = evalcmd(argc, argv, flags);
  9390. else
  9391. status = (*cmd->builtin)(argc, argv);
  9392. flush_stdout_stderr();
  9393. status |= ferror(stdout);
  9394. exitstatus = status;
  9395. cmddone:
  9396. clearerr(stdout);
  9397. commandname = savecmdname;
  9398. exception_handler = savehandler;
  9399. return i;
  9400. }
  9401. static int
  9402. goodname(const char *p)
  9403. {
  9404. return endofname(p)[0] == '\0';
  9405. }
  9406. /*
  9407. * Search for a command. This is called before we fork so that the
  9408. * location of the command will be available in the parent as well as
  9409. * the child. The check for "goodname" is an overly conservative
  9410. * check that the name will not be subject to expansion.
  9411. */
  9412. static void
  9413. prehash(union node *n)
  9414. {
  9415. struct cmdentry entry;
  9416. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9417. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9418. }
  9419. /* ============ Builtin commands
  9420. *
  9421. * Builtin commands whose functions are closely tied to evaluation
  9422. * are implemented here.
  9423. */
  9424. /*
  9425. * Handle break and continue commands. Break, continue, and return are
  9426. * all handled by setting the evalskip flag. The evaluation routines
  9427. * above all check this flag, and if it is set they start skipping
  9428. * commands rather than executing them. The variable skipcount is
  9429. * the number of loops to break/continue, or the number of function
  9430. * levels to return. (The latter is always 1.) It should probably
  9431. * be an error to break out of more loops than exist, but it isn't
  9432. * in the standard shell so we don't make it one here.
  9433. */
  9434. static int FAST_FUNC
  9435. breakcmd(int argc UNUSED_PARAM, char **argv)
  9436. {
  9437. int n = argv[1] ? number(argv[1]) : 1;
  9438. if (n <= 0)
  9439. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9440. if (n > loopnest)
  9441. n = loopnest;
  9442. if (n > 0) {
  9443. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9444. skipcount = n;
  9445. }
  9446. return 0;
  9447. }
  9448. /*
  9449. * This implements the input routines used by the parser.
  9450. */
  9451. enum {
  9452. INPUT_PUSH_FILE = 1,
  9453. INPUT_NOFILE_OK = 2,
  9454. };
  9455. static smallint checkkwd;
  9456. /* values of checkkwd variable */
  9457. #define CHKALIAS 0x1
  9458. #define CHKKWD 0x2
  9459. #define CHKNL 0x4
  9460. #define CHKEOFMARK 0x8
  9461. /*
  9462. * Push a string back onto the input at this current parsefile level.
  9463. * We handle aliases this way.
  9464. */
  9465. #if !ENABLE_ASH_ALIAS
  9466. #define pushstring(s, ap) pushstring(s)
  9467. #endif
  9468. static void
  9469. pushstring(char *s, struct alias *ap)
  9470. {
  9471. struct strpush *sp;
  9472. int len;
  9473. len = strlen(s);
  9474. INT_OFF;
  9475. if (g_parsefile->strpush) {
  9476. sp = ckzalloc(sizeof(*sp));
  9477. sp->prev = g_parsefile->strpush;
  9478. } else {
  9479. sp = &(g_parsefile->basestrpush);
  9480. }
  9481. g_parsefile->strpush = sp;
  9482. sp->prev_string = g_parsefile->next_to_pgetc;
  9483. sp->prev_left_in_line = g_parsefile->left_in_line;
  9484. sp->unget = g_parsefile->unget;
  9485. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9486. #if ENABLE_ASH_ALIAS
  9487. sp->ap = ap;
  9488. if (ap) {
  9489. ap->flag |= ALIASINUSE;
  9490. sp->string = s;
  9491. }
  9492. #endif
  9493. g_parsefile->next_to_pgetc = s;
  9494. g_parsefile->left_in_line = len;
  9495. g_parsefile->unget = 0;
  9496. INT_ON;
  9497. }
  9498. static void
  9499. popstring(void)
  9500. {
  9501. struct strpush *sp = g_parsefile->strpush;
  9502. INT_OFF;
  9503. #if ENABLE_ASH_ALIAS
  9504. if (sp->ap) {
  9505. if (g_parsefile->next_to_pgetc[-1] == ' '
  9506. || g_parsefile->next_to_pgetc[-1] == '\t'
  9507. ) {
  9508. checkkwd |= CHKALIAS;
  9509. }
  9510. if (sp->string != sp->ap->val) {
  9511. free(sp->string);
  9512. }
  9513. sp->ap->flag &= ~ALIASINUSE;
  9514. if (sp->ap->flag & ALIASDEAD) {
  9515. unalias(sp->ap->name);
  9516. }
  9517. }
  9518. #endif
  9519. g_parsefile->next_to_pgetc = sp->prev_string;
  9520. g_parsefile->left_in_line = sp->prev_left_in_line;
  9521. g_parsefile->unget = sp->unget;
  9522. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9523. g_parsefile->strpush = sp->prev;
  9524. if (sp != &(g_parsefile->basestrpush))
  9525. free(sp);
  9526. INT_ON;
  9527. }
  9528. static int
  9529. preadfd(void)
  9530. {
  9531. int nr;
  9532. char *buf = g_parsefile->buf;
  9533. g_parsefile->next_to_pgetc = buf;
  9534. #if ENABLE_FEATURE_EDITING
  9535. retry:
  9536. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9537. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9538. else {
  9539. # if ENABLE_ASH_IDLE_TIMEOUT
  9540. int timeout = -1;
  9541. if (iflag) {
  9542. const char *tmout_var = lookupvar("TMOUT");
  9543. if (tmout_var) {
  9544. timeout = atoi(tmout_var) * 1000;
  9545. if (timeout <= 0)
  9546. timeout = -1;
  9547. }
  9548. }
  9549. line_input_state->timeout = timeout;
  9550. # endif
  9551. # if ENABLE_FEATURE_TAB_COMPLETION
  9552. line_input_state->path_lookup = pathval();
  9553. # endif
  9554. reinit_unicode_for_ash();
  9555. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9556. if (nr == 0) {
  9557. /* ^C pressed, "convert" to SIGINT */
  9558. write(STDOUT_FILENO, "^C", 2);
  9559. if (trap[SIGINT]) {
  9560. buf[0] = '\n';
  9561. buf[1] = '\0';
  9562. raise(SIGINT);
  9563. return 1;
  9564. }
  9565. exitstatus = 128 + SIGINT;
  9566. bb_putchar('\n');
  9567. goto retry;
  9568. }
  9569. if (nr < 0) {
  9570. if (errno == 0) {
  9571. /* Ctrl+D pressed */
  9572. nr = 0;
  9573. }
  9574. # if ENABLE_ASH_IDLE_TIMEOUT
  9575. else if (errno == EAGAIN && timeout > 0) {
  9576. puts("\007timed out waiting for input: auto-logout");
  9577. exitshell();
  9578. }
  9579. # endif
  9580. }
  9581. }
  9582. #else
  9583. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9584. #endif
  9585. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9586. if (nr < 0) {
  9587. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9588. int flags = fcntl(0, F_GETFL);
  9589. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9590. flags &= ~O_NONBLOCK;
  9591. if (fcntl(0, F_SETFL, flags) >= 0) {
  9592. out2str("sh: turning off NDELAY mode\n");
  9593. goto retry;
  9594. }
  9595. }
  9596. }
  9597. }
  9598. #endif
  9599. return nr;
  9600. }
  9601. /*
  9602. * Refill the input buffer and return the next input character:
  9603. *
  9604. * 1) If a string was pushed back on the input, pop it;
  9605. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9606. * or we are reading from a string so we can't refill the buffer,
  9607. * return EOF.
  9608. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9609. * 4) Process input up to the next newline, deleting nul characters.
  9610. */
  9611. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9612. #define pgetc_debug(...) ((void)0)
  9613. static int pgetc(void);
  9614. static int
  9615. preadbuffer(void)
  9616. {
  9617. char *q;
  9618. int more;
  9619. if (g_parsefile->strpush) {
  9620. #if ENABLE_ASH_ALIAS
  9621. if (g_parsefile->left_in_line == -1
  9622. && g_parsefile->strpush->ap
  9623. && g_parsefile->next_to_pgetc[-1] != ' '
  9624. && g_parsefile->next_to_pgetc[-1] != '\t'
  9625. ) {
  9626. pgetc_debug("preadbuffer PEOA");
  9627. return PEOA;
  9628. }
  9629. #endif
  9630. popstring();
  9631. return pgetc();
  9632. }
  9633. /* on both branches above g_parsefile->left_in_line < 0.
  9634. * "pgetc" needs refilling.
  9635. */
  9636. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9637. * pungetc() may increment it a few times.
  9638. * Assuming it won't increment it to less than -90.
  9639. */
  9640. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9641. pgetc_debug("preadbuffer PEOF1");
  9642. /* even in failure keep left_in_line and next_to_pgetc
  9643. * in lock step, for correct multi-layer pungetc.
  9644. * left_in_line was decremented before preadbuffer(),
  9645. * must inc next_to_pgetc: */
  9646. g_parsefile->next_to_pgetc++;
  9647. return PEOF;
  9648. }
  9649. more = g_parsefile->left_in_buffer;
  9650. if (more <= 0) {
  9651. flush_stdout_stderr();
  9652. again:
  9653. more = preadfd();
  9654. if (more <= 0) {
  9655. /* don't try reading again */
  9656. g_parsefile->left_in_line = -99;
  9657. pgetc_debug("preadbuffer PEOF2");
  9658. g_parsefile->next_to_pgetc++;
  9659. return PEOF;
  9660. }
  9661. }
  9662. /* Find out where's the end of line.
  9663. * Set g_parsefile->left_in_line
  9664. * and g_parsefile->left_in_buffer acordingly.
  9665. * NUL chars are deleted.
  9666. */
  9667. q = g_parsefile->next_to_pgetc;
  9668. for (;;) {
  9669. char c;
  9670. more--;
  9671. c = *q;
  9672. if (c == '\0') {
  9673. memmove(q, q + 1, more);
  9674. } else {
  9675. q++;
  9676. if (c == '\n') {
  9677. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9678. break;
  9679. }
  9680. }
  9681. if (more <= 0) {
  9682. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9683. if (g_parsefile->left_in_line < 0)
  9684. goto again;
  9685. break;
  9686. }
  9687. }
  9688. g_parsefile->left_in_buffer = more;
  9689. if (vflag) {
  9690. char save = *q;
  9691. *q = '\0';
  9692. out2str(g_parsefile->next_to_pgetc);
  9693. *q = save;
  9694. }
  9695. pgetc_debug("preadbuffer at %d:%p'%s'",
  9696. g_parsefile->left_in_line,
  9697. g_parsefile->next_to_pgetc,
  9698. g_parsefile->next_to_pgetc);
  9699. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9700. }
  9701. static void
  9702. nlprompt(void)
  9703. {
  9704. g_parsefile->linno++;
  9705. setprompt_if(doprompt, 2);
  9706. }
  9707. static void
  9708. nlnoprompt(void)
  9709. {
  9710. g_parsefile->linno++;
  9711. needprompt = doprompt;
  9712. }
  9713. static int
  9714. pgetc(void)
  9715. {
  9716. int c;
  9717. pgetc_debug("pgetc at %d:%p'%s'",
  9718. g_parsefile->left_in_line,
  9719. g_parsefile->next_to_pgetc,
  9720. g_parsefile->next_to_pgetc);
  9721. if (g_parsefile->unget)
  9722. return g_parsefile->lastc[--g_parsefile->unget];
  9723. if (--g_parsefile->left_in_line >= 0)
  9724. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9725. else
  9726. c = preadbuffer();
  9727. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9728. g_parsefile->lastc[0] = c;
  9729. return c;
  9730. }
  9731. #if ENABLE_ASH_ALIAS
  9732. static int
  9733. pgetc_without_PEOA(void)
  9734. {
  9735. int c;
  9736. do {
  9737. pgetc_debug("pgetc at %d:%p'%s'",
  9738. g_parsefile->left_in_line,
  9739. g_parsefile->next_to_pgetc,
  9740. g_parsefile->next_to_pgetc);
  9741. c = pgetc();
  9742. } while (c == PEOA);
  9743. return c;
  9744. }
  9745. #else
  9746. # define pgetc_without_PEOA() pgetc()
  9747. #endif
  9748. /*
  9749. * Undo a call to pgetc. Only two characters may be pushed back.
  9750. * PEOF may be pushed back.
  9751. */
  9752. static void
  9753. pungetc(void)
  9754. {
  9755. g_parsefile->unget++;
  9756. }
  9757. /* This one eats backslash+newline */
  9758. static int
  9759. pgetc_eatbnl(void)
  9760. {
  9761. int c;
  9762. while ((c = pgetc()) == '\\') {
  9763. if (pgetc() != '\n') {
  9764. pungetc();
  9765. break;
  9766. }
  9767. nlprompt();
  9768. }
  9769. return c;
  9770. }
  9771. struct synstack {
  9772. smalluint syntax;
  9773. uint8_t innerdq :1;
  9774. uint8_t varpushed :1;
  9775. uint8_t dblquote :1;
  9776. int varnest; /* levels of variables expansion */
  9777. int dqvarnest; /* levels of variables expansion within double quotes */
  9778. int parenlevel; /* levels of parens in arithmetic */
  9779. struct synstack *prev;
  9780. struct synstack *next;
  9781. };
  9782. static void
  9783. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9784. {
  9785. memset(next, 0, sizeof(*next));
  9786. next->syntax = syntax;
  9787. next->next = *stack;
  9788. (*stack)->prev = next;
  9789. *stack = next;
  9790. }
  9791. static ALWAYS_INLINE void
  9792. synstack_pop(struct synstack **stack)
  9793. {
  9794. *stack = (*stack)->next;
  9795. }
  9796. /*
  9797. * To handle the "." command, a stack of input files is used. Pushfile
  9798. * adds a new entry to the stack and popfile restores the previous level.
  9799. */
  9800. static void
  9801. pushfile(void)
  9802. {
  9803. struct parsefile *pf;
  9804. pf = ckzalloc(sizeof(*pf));
  9805. pf->prev = g_parsefile;
  9806. pf->pf_fd = -1;
  9807. /*pf->strpush = NULL; - ckzalloc did it */
  9808. /*pf->basestrpush.prev = NULL;*/
  9809. /*pf->unget = 0;*/
  9810. g_parsefile = pf;
  9811. }
  9812. static void
  9813. popfile(void)
  9814. {
  9815. struct parsefile *pf = g_parsefile;
  9816. if (pf == &basepf)
  9817. return;
  9818. INT_OFF;
  9819. if (pf->pf_fd >= 0)
  9820. close(pf->pf_fd);
  9821. free(pf->buf);
  9822. while (pf->strpush)
  9823. popstring();
  9824. g_parsefile = pf->prev;
  9825. free(pf);
  9826. INT_ON;
  9827. }
  9828. /*
  9829. * Return to top level.
  9830. */
  9831. static void
  9832. popallfiles(void)
  9833. {
  9834. while (g_parsefile != &basepf)
  9835. popfile();
  9836. }
  9837. /*
  9838. * Close the file(s) that the shell is reading commands from. Called
  9839. * after a fork is done.
  9840. */
  9841. static void
  9842. closescript(void)
  9843. {
  9844. popallfiles();
  9845. if (g_parsefile->pf_fd > 0) {
  9846. close(g_parsefile->pf_fd);
  9847. g_parsefile->pf_fd = 0;
  9848. }
  9849. }
  9850. /*
  9851. * Like setinputfile, but takes an open file descriptor. Call this with
  9852. * interrupts off.
  9853. */
  9854. static void
  9855. setinputfd(int fd, int push)
  9856. {
  9857. if (push) {
  9858. pushfile();
  9859. g_parsefile->buf = NULL;
  9860. }
  9861. g_parsefile->pf_fd = fd;
  9862. if (g_parsefile->buf == NULL)
  9863. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9864. g_parsefile->left_in_buffer = 0;
  9865. g_parsefile->left_in_line = 0;
  9866. g_parsefile->linno = 1;
  9867. }
  9868. /*
  9869. * Set the input to take input from a file. If push is set, push the
  9870. * old input onto the stack first.
  9871. */
  9872. static int
  9873. setinputfile(const char *fname, int flags)
  9874. {
  9875. int fd;
  9876. INT_OFF;
  9877. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9878. if (fd < 0) {
  9879. if (flags & INPUT_NOFILE_OK)
  9880. goto out;
  9881. exitstatus = 127;
  9882. ash_msg_and_raise_perror("can't open '%s'", fname);
  9883. }
  9884. if (fd < 10)
  9885. fd = savefd(fd);
  9886. else if (O_CLOEXEC == 0) /* old libc */
  9887. close_on_exec_on(fd);
  9888. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9889. out:
  9890. INT_ON;
  9891. return fd;
  9892. }
  9893. /*
  9894. * Like setinputfile, but takes input from a string.
  9895. */
  9896. static void
  9897. setinputstring(char *string)
  9898. {
  9899. INT_OFF;
  9900. pushfile();
  9901. g_parsefile->next_to_pgetc = string;
  9902. g_parsefile->left_in_line = strlen(string);
  9903. g_parsefile->buf = NULL;
  9904. g_parsefile->linno = 1;
  9905. INT_ON;
  9906. }
  9907. /*
  9908. * Routines to check for mail.
  9909. */
  9910. #if ENABLE_ASH_MAIL
  9911. /* Hash of mtimes of mailboxes */
  9912. static unsigned mailtime_hash;
  9913. /* Set if MAIL or MAILPATH is changed. */
  9914. static smallint mail_var_path_changed;
  9915. /*
  9916. * Print appropriate message(s) if mail has arrived.
  9917. * If mail_var_path_changed is set,
  9918. * then the value of MAIL has mail_var_path_changed,
  9919. * so we just update the values.
  9920. */
  9921. static void
  9922. chkmail(void)
  9923. {
  9924. const char *mpath;
  9925. char *p;
  9926. char *q;
  9927. unsigned new_hash;
  9928. struct stackmark smark;
  9929. struct stat statb;
  9930. setstackmark(&smark);
  9931. mpath = mpathset() ? mpathval() : mailval();
  9932. new_hash = 0;
  9933. for (;;) {
  9934. p = path_advance(&mpath, nullstr);
  9935. if (p == NULL)
  9936. break;
  9937. if (*p == '\0')
  9938. continue;
  9939. for (q = p; *q; q++)
  9940. continue;
  9941. #if DEBUG
  9942. if (q[-1] != '/')
  9943. abort();
  9944. #endif
  9945. q[-1] = '\0'; /* delete trailing '/' */
  9946. if (stat(p, &statb) < 0) {
  9947. continue;
  9948. }
  9949. /* Very simplistic "hash": just a sum of all mtimes */
  9950. new_hash += (unsigned)statb.st_mtime;
  9951. }
  9952. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9953. if (mailtime_hash != 0)
  9954. out2str("you have mail\n");
  9955. mailtime_hash = new_hash;
  9956. }
  9957. mail_var_path_changed = 0;
  9958. popstackmark(&smark);
  9959. }
  9960. static void FAST_FUNC
  9961. changemail(const char *val UNUSED_PARAM)
  9962. {
  9963. mail_var_path_changed = 1;
  9964. }
  9965. #endif /* ASH_MAIL */
  9966. /* ============ ??? */
  9967. /*
  9968. * Set the shell parameters.
  9969. */
  9970. static void
  9971. setparam(char **argv)
  9972. {
  9973. char **newparam;
  9974. char **ap;
  9975. int nparam;
  9976. for (nparam = 0; argv[nparam]; nparam++)
  9977. continue;
  9978. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9979. while (*argv) {
  9980. *ap++ = ckstrdup(*argv++);
  9981. }
  9982. *ap = NULL;
  9983. freeparam(&shellparam);
  9984. shellparam.malloced = 1;
  9985. shellparam.nparam = nparam;
  9986. shellparam.p = newparam;
  9987. #if ENABLE_ASH_GETOPTS
  9988. shellparam.optind = 1;
  9989. shellparam.optoff = -1;
  9990. #endif
  9991. }
  9992. /*
  9993. * Process shell options. The global variable argptr contains a pointer
  9994. * to the argument list; we advance it past the options.
  9995. *
  9996. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9997. * For a non-interactive shell, an error condition encountered
  9998. * by a special built-in ... shall cause the shell to write a diagnostic message
  9999. * to standard error and exit as shown in the following table:
  10000. * Error Special Built-In
  10001. * ...
  10002. * Utility syntax error (option or operand error) Shall exit
  10003. * ...
  10004. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10005. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10006. * and shell continues), and people rely on this behavior!
  10007. * Testcase:
  10008. * set -o barfoo 2>/dev/null
  10009. * echo $?
  10010. *
  10011. * Oh well. Let's mimic that.
  10012. */
  10013. static int
  10014. plus_minus_o(char *name, int val)
  10015. {
  10016. int i;
  10017. if (name) {
  10018. for (i = 0; i < NOPTS; i++) {
  10019. if (strcmp(name, optnames(i)) == 0) {
  10020. optlist[i] = val;
  10021. return 0;
  10022. }
  10023. }
  10024. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10025. return 1;
  10026. }
  10027. for (i = 0; i < NOPTS; i++) {
  10028. if (val) {
  10029. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10030. } else {
  10031. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10032. }
  10033. }
  10034. return 0;
  10035. }
  10036. static void
  10037. setoption(int flag, int val)
  10038. {
  10039. int i;
  10040. for (i = 0; i < NOPTS; i++) {
  10041. if (optletters(i) == flag) {
  10042. optlist[i] = val;
  10043. return;
  10044. }
  10045. }
  10046. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10047. /* NOTREACHED */
  10048. }
  10049. static int
  10050. options(int cmdline, int *login_sh)
  10051. {
  10052. char *p;
  10053. int val;
  10054. int c;
  10055. if (cmdline)
  10056. minusc = NULL;
  10057. while ((p = *argptr) != NULL) {
  10058. c = *p++;
  10059. if (c != '-' && c != '+')
  10060. break;
  10061. argptr++;
  10062. val = 0; /* val = 0 if c == '+' */
  10063. if (c == '-') {
  10064. val = 1;
  10065. if (p[0] == '\0' || LONE_DASH(p)) {
  10066. if (!cmdline) {
  10067. /* "-" means turn off -x and -v */
  10068. if (p[0] == '\0')
  10069. xflag = vflag = 0;
  10070. /* "--" means reset params */
  10071. else if (*argptr == NULL)
  10072. setparam(argptr);
  10073. }
  10074. break; /* "-" or "--" terminates options */
  10075. }
  10076. }
  10077. /* first char was + or - */
  10078. while ((c = *p++) != '\0') {
  10079. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10080. if (c == 'c' && cmdline) {
  10081. minusc = p; /* command is after shell args */
  10082. } else if (c == 'o') {
  10083. if (plus_minus_o(*argptr, val)) {
  10084. /* it already printed err message */
  10085. return 1; /* error */
  10086. }
  10087. if (*argptr)
  10088. argptr++;
  10089. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  10090. if (login_sh)
  10091. *login_sh = 1;
  10092. /* bash does not accept +-login, we also won't */
  10093. } else if (cmdline && val && (c == '-')) { /* long options */
  10094. if (strcmp(p, "login") == 0) {
  10095. if (login_sh)
  10096. *login_sh = 1;
  10097. }
  10098. break;
  10099. } else {
  10100. setoption(c, val);
  10101. }
  10102. }
  10103. }
  10104. return 0;
  10105. }
  10106. /*
  10107. * The shift builtin command.
  10108. */
  10109. static int FAST_FUNC
  10110. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10111. {
  10112. int n;
  10113. char **ap1, **ap2;
  10114. n = 1;
  10115. if (argv[1])
  10116. n = number(argv[1]);
  10117. if (n > shellparam.nparam)
  10118. return 1;
  10119. INT_OFF;
  10120. shellparam.nparam -= n;
  10121. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10122. if (shellparam.malloced)
  10123. free(*ap1);
  10124. }
  10125. ap2 = shellparam.p;
  10126. while ((*ap2++ = *ap1++) != NULL)
  10127. continue;
  10128. #if ENABLE_ASH_GETOPTS
  10129. shellparam.optind = 1;
  10130. shellparam.optoff = -1;
  10131. #endif
  10132. INT_ON;
  10133. return 0;
  10134. }
  10135. /*
  10136. * POSIX requires that 'set' (but not export or readonly) output the
  10137. * variables in lexicographic order - by the locale's collating order (sigh).
  10138. * Maybe we could keep them in an ordered balanced binary tree
  10139. * instead of hashed lists.
  10140. * For now just roll 'em through qsort for printing...
  10141. */
  10142. static int
  10143. showvars(const char *sep_prefix, int on, int off)
  10144. {
  10145. const char *sep;
  10146. char **ep, **epend;
  10147. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10148. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10149. sep = *sep_prefix ? " " : sep_prefix;
  10150. for (; ep < epend; ep++) {
  10151. const char *p;
  10152. const char *q;
  10153. p = endofname(*ep);
  10154. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10155. * makes "export -p" to have output not suitable for "eval":
  10156. * import os
  10157. * os.environ["test-test"]="test"
  10158. * if os.fork() == 0:
  10159. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10160. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10161. */
  10162. q = nullstr;
  10163. if (*p == '=')
  10164. q = single_quote(++p);
  10165. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10166. }
  10167. return 0;
  10168. }
  10169. /*
  10170. * The set command builtin.
  10171. */
  10172. static int FAST_FUNC
  10173. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10174. {
  10175. int retval;
  10176. if (!argv[1])
  10177. return showvars(nullstr, 0, VUNSET);
  10178. INT_OFF;
  10179. retval = options(/*cmdline:*/ 0, NULL);
  10180. if (retval == 0) { /* if no parse error... */
  10181. optschanged();
  10182. if (*argptr != NULL) {
  10183. setparam(argptr);
  10184. }
  10185. }
  10186. INT_ON;
  10187. return retval;
  10188. }
  10189. #if ENABLE_ASH_RANDOM_SUPPORT
  10190. static void FAST_FUNC
  10191. change_random(const char *value)
  10192. {
  10193. uint32_t t;
  10194. if (value == NULL) {
  10195. /* "get", generate */
  10196. t = next_random(&random_gen);
  10197. /* set without recursion */
  10198. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10199. vrandom.flags &= ~VNOFUNC;
  10200. } else {
  10201. /* set/reset */
  10202. t = strtoul(value, NULL, 10);
  10203. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10204. }
  10205. }
  10206. #endif
  10207. #if ENABLE_ASH_GETOPTS
  10208. static int
  10209. getopts(char *optstr, char *optvar, char **optfirst)
  10210. {
  10211. char *p, *q;
  10212. char c = '?';
  10213. int done = 0;
  10214. char sbuf[2];
  10215. char **optnext;
  10216. int ind = shellparam.optind;
  10217. int off = shellparam.optoff;
  10218. sbuf[1] = '\0';
  10219. shellparam.optind = -1;
  10220. optnext = optfirst + ind - 1;
  10221. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10222. p = NULL;
  10223. else
  10224. p = optnext[-1] + off;
  10225. if (p == NULL || *p == '\0') {
  10226. /* Current word is done, advance */
  10227. p = *optnext;
  10228. if (p == NULL || *p != '-' || *++p == '\0') {
  10229. atend:
  10230. unsetvar("OPTARG");
  10231. p = NULL;
  10232. done = 1;
  10233. goto out;
  10234. }
  10235. optnext++;
  10236. if (LONE_DASH(p)) /* check for "--" */
  10237. goto atend;
  10238. }
  10239. c = *p++;
  10240. for (q = optstr; *q != c;) {
  10241. if (*q == '\0') {
  10242. /* OPTERR is a bashism */
  10243. const char *cp = lookupvar("OPTERR");
  10244. if ((cp && LONE_CHAR(cp, '0'))
  10245. || (optstr[0] == ':')
  10246. ) {
  10247. sbuf[0] = c;
  10248. /*sbuf[1] = '\0'; - already is */
  10249. setvar0("OPTARG", sbuf);
  10250. } else {
  10251. fprintf(stderr, "Illegal option -%c\n", c);
  10252. unsetvar("OPTARG");
  10253. }
  10254. c = '?';
  10255. goto out;
  10256. }
  10257. if (*++q == ':')
  10258. q++;
  10259. }
  10260. if (*++q == ':') {
  10261. if (*p == '\0' && (p = *optnext) == NULL) {
  10262. /* OPTERR is a bashism */
  10263. const char *cp = lookupvar("OPTERR");
  10264. if ((cp && LONE_CHAR(cp, '0'))
  10265. || (optstr[0] == ':')
  10266. ) {
  10267. sbuf[0] = c;
  10268. /*sbuf[1] = '\0'; - already is */
  10269. setvar0("OPTARG", sbuf);
  10270. c = ':';
  10271. } else {
  10272. fprintf(stderr, "No arg for -%c option\n", c);
  10273. unsetvar("OPTARG");
  10274. c = '?';
  10275. }
  10276. goto out;
  10277. }
  10278. if (p == *optnext)
  10279. optnext++;
  10280. setvar0("OPTARG", p);
  10281. p = NULL;
  10282. } else
  10283. setvar0("OPTARG", nullstr);
  10284. out:
  10285. ind = optnext - optfirst + 1;
  10286. setvar("OPTIND", itoa(ind), VNOFUNC);
  10287. sbuf[0] = c;
  10288. /*sbuf[1] = '\0'; - already is */
  10289. setvar0(optvar, sbuf);
  10290. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10291. shellparam.optind = ind;
  10292. return done;
  10293. }
  10294. /*
  10295. * The getopts builtin. Shellparam.optnext points to the next argument
  10296. * to be processed. Shellparam.optptr points to the next character to
  10297. * be processed in the current argument. If shellparam.optnext is NULL,
  10298. * then it's the first time getopts has been called.
  10299. */
  10300. static int FAST_FUNC
  10301. getoptscmd(int argc, char **argv)
  10302. {
  10303. char **optbase;
  10304. if (argc < 3)
  10305. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10306. if (argc == 3) {
  10307. optbase = shellparam.p;
  10308. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10309. shellparam.optind = 1;
  10310. shellparam.optoff = -1;
  10311. }
  10312. } else {
  10313. optbase = &argv[3];
  10314. if ((unsigned)shellparam.optind > argc - 2) {
  10315. shellparam.optind = 1;
  10316. shellparam.optoff = -1;
  10317. }
  10318. }
  10319. return getopts(argv[1], argv[2], optbase);
  10320. }
  10321. #endif /* ASH_GETOPTS */
  10322. /* ============ Shell parser */
  10323. struct heredoc {
  10324. struct heredoc *next; /* next here document in list */
  10325. union node *here; /* redirection node */
  10326. char *eofmark; /* string indicating end of input */
  10327. smallint striptabs; /* if set, strip leading tabs */
  10328. };
  10329. static smallint tokpushback; /* last token pushed back */
  10330. static smallint quoteflag; /* set if (part of) last token was quoted */
  10331. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10332. static struct heredoc *heredoclist; /* list of here documents to read */
  10333. static char *wordtext; /* text of last word returned by readtoken */
  10334. static struct nodelist *backquotelist;
  10335. static union node *redirnode;
  10336. static struct heredoc *heredoc;
  10337. static const char *
  10338. tokname(char *buf, int tok)
  10339. {
  10340. if (tok < TSEMI)
  10341. return tokname_array[tok];
  10342. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10343. return buf;
  10344. }
  10345. /* raise_error_unexpected_syntax:
  10346. * Called when an unexpected token is read during the parse. The argument
  10347. * is the token that is expected, or -1 if more than one type of token can
  10348. * occur at this point.
  10349. */
  10350. static void raise_error_unexpected_syntax(int) NORETURN;
  10351. static void
  10352. raise_error_unexpected_syntax(int token)
  10353. {
  10354. char msg[64];
  10355. char buf[16];
  10356. int l;
  10357. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10358. if (token >= 0)
  10359. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10360. raise_error_syntax(msg);
  10361. /* NOTREACHED */
  10362. }
  10363. /* parsing is heavily cross-recursive, need these forward decls */
  10364. static union node *andor(void);
  10365. static union node *pipeline(void);
  10366. static union node *parse_command(void);
  10367. static void parseheredoc(void);
  10368. static int peektoken(void);
  10369. static int readtoken(void);
  10370. static union node *
  10371. list(int nlflag)
  10372. {
  10373. union node *n1, *n2, *n3;
  10374. int tok;
  10375. n1 = NULL;
  10376. for (;;) {
  10377. switch (peektoken()) {
  10378. case TNL:
  10379. if (!(nlflag & 1))
  10380. break;
  10381. parseheredoc();
  10382. return n1;
  10383. case TEOF:
  10384. if (!n1 && (nlflag & 1))
  10385. n1 = NODE_EOF;
  10386. parseheredoc();
  10387. return n1;
  10388. }
  10389. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10390. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10391. return n1;
  10392. nlflag |= 2;
  10393. n2 = andor();
  10394. tok = readtoken();
  10395. if (tok == TBACKGND) {
  10396. if (n2->type == NPIPE) {
  10397. n2->npipe.pipe_backgnd = 1;
  10398. } else {
  10399. if (n2->type != NREDIR) {
  10400. n3 = stzalloc(sizeof(struct nredir));
  10401. n3->nredir.n = n2;
  10402. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10403. n2 = n3;
  10404. }
  10405. n2->type = NBACKGND;
  10406. }
  10407. }
  10408. if (n1 == NULL) {
  10409. n1 = n2;
  10410. } else {
  10411. n3 = stzalloc(sizeof(struct nbinary));
  10412. n3->type = NSEMI;
  10413. n3->nbinary.ch1 = n1;
  10414. n3->nbinary.ch2 = n2;
  10415. n1 = n3;
  10416. }
  10417. switch (tok) {
  10418. case TNL:
  10419. case TEOF:
  10420. tokpushback = 1;
  10421. /* fall through */
  10422. case TBACKGND:
  10423. case TSEMI:
  10424. break;
  10425. default:
  10426. if ((nlflag & 1))
  10427. raise_error_unexpected_syntax(-1);
  10428. tokpushback = 1;
  10429. return n1;
  10430. }
  10431. }
  10432. }
  10433. static union node *
  10434. andor(void)
  10435. {
  10436. union node *n1, *n2, *n3;
  10437. int t;
  10438. n1 = pipeline();
  10439. for (;;) {
  10440. t = readtoken();
  10441. if (t == TAND) {
  10442. t = NAND;
  10443. } else if (t == TOR) {
  10444. t = NOR;
  10445. } else {
  10446. tokpushback = 1;
  10447. return n1;
  10448. }
  10449. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10450. n2 = pipeline();
  10451. n3 = stzalloc(sizeof(struct nbinary));
  10452. n3->type = t;
  10453. n3->nbinary.ch1 = n1;
  10454. n3->nbinary.ch2 = n2;
  10455. n1 = n3;
  10456. }
  10457. }
  10458. static union node *
  10459. pipeline(void)
  10460. {
  10461. union node *n1, *n2, *pipenode;
  10462. struct nodelist *lp, *prev;
  10463. int negate;
  10464. negate = 0;
  10465. TRACE(("pipeline: entered\n"));
  10466. if (readtoken() == TNOT) {
  10467. negate = !negate;
  10468. checkkwd = CHKKWD | CHKALIAS;
  10469. } else
  10470. tokpushback = 1;
  10471. n1 = parse_command();
  10472. if (readtoken() == TPIPE) {
  10473. pipenode = stzalloc(sizeof(struct npipe));
  10474. pipenode->type = NPIPE;
  10475. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10476. lp = stzalloc(sizeof(struct nodelist));
  10477. pipenode->npipe.cmdlist = lp;
  10478. lp->n = n1;
  10479. do {
  10480. prev = lp;
  10481. lp = stzalloc(sizeof(struct nodelist));
  10482. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10483. lp->n = parse_command();
  10484. prev->next = lp;
  10485. } while (readtoken() == TPIPE);
  10486. lp->next = NULL;
  10487. n1 = pipenode;
  10488. }
  10489. tokpushback = 1;
  10490. if (negate) {
  10491. n2 = stzalloc(sizeof(struct nnot));
  10492. n2->type = NNOT;
  10493. n2->nnot.com = n1;
  10494. return n2;
  10495. }
  10496. return n1;
  10497. }
  10498. static union node *
  10499. makename(void)
  10500. {
  10501. union node *n;
  10502. n = stzalloc(sizeof(struct narg));
  10503. n->type = NARG;
  10504. /*n->narg.next = NULL; - stzalloc did it */
  10505. n->narg.text = wordtext;
  10506. n->narg.backquote = backquotelist;
  10507. return n;
  10508. }
  10509. static void
  10510. fixredir(union node *n, const char *text, int err)
  10511. {
  10512. int fd;
  10513. TRACE(("Fix redir %s %d\n", text, err));
  10514. if (!err)
  10515. n->ndup.vname = NULL;
  10516. fd = bb_strtou(text, NULL, 10);
  10517. if (!errno && fd >= 0)
  10518. n->ndup.dupfd = fd;
  10519. else if (LONE_DASH(text))
  10520. n->ndup.dupfd = -1;
  10521. else {
  10522. if (err)
  10523. raise_error_syntax("bad fd number");
  10524. n->ndup.vname = makename();
  10525. }
  10526. }
  10527. static void
  10528. parsefname(void)
  10529. {
  10530. union node *n = redirnode;
  10531. if (n->type == NHERE)
  10532. checkkwd = CHKEOFMARK;
  10533. if (readtoken() != TWORD)
  10534. raise_error_unexpected_syntax(-1);
  10535. if (n->type == NHERE) {
  10536. struct heredoc *here = heredoc;
  10537. struct heredoc *p;
  10538. if (quoteflag == 0)
  10539. n->type = NXHERE;
  10540. TRACE(("Here document %d\n", n->type));
  10541. rmescapes(wordtext, 0, NULL);
  10542. here->eofmark = wordtext;
  10543. here->next = NULL;
  10544. if (heredoclist == NULL)
  10545. heredoclist = here;
  10546. else {
  10547. for (p = heredoclist; p->next; p = p->next)
  10548. continue;
  10549. p->next = here;
  10550. }
  10551. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10552. fixredir(n, wordtext, 0);
  10553. } else {
  10554. n->nfile.fname = makename();
  10555. }
  10556. }
  10557. static union node *
  10558. simplecmd(void)
  10559. {
  10560. union node *args, **app;
  10561. union node *n = NULL;
  10562. union node *vars, **vpp;
  10563. union node **rpp, *redir;
  10564. int savecheckkwd;
  10565. int savelinno;
  10566. #if BASH_TEST2
  10567. smallint double_brackets_flag = 0;
  10568. #endif
  10569. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10570. args = NULL;
  10571. app = &args;
  10572. vars = NULL;
  10573. vpp = &vars;
  10574. redir = NULL;
  10575. rpp = &redir;
  10576. savecheckkwd = CHKALIAS;
  10577. savelinno = g_parsefile->linno;
  10578. for (;;) {
  10579. int t;
  10580. checkkwd = savecheckkwd;
  10581. t = readtoken();
  10582. switch (t) {
  10583. #if BASH_FUNCTION
  10584. case TFUNCTION:
  10585. if (peektoken() != TWORD)
  10586. raise_error_unexpected_syntax(TWORD);
  10587. function_flag = 1;
  10588. break;
  10589. #endif
  10590. #if BASH_TEST2
  10591. case TAND: /* "&&" */
  10592. case TOR: /* "||" */
  10593. if (!double_brackets_flag) {
  10594. tokpushback = 1;
  10595. goto out;
  10596. }
  10597. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10598. #endif
  10599. case TWORD:
  10600. n = stzalloc(sizeof(struct narg));
  10601. n->type = NARG;
  10602. /*n->narg.next = NULL; - stzalloc did it */
  10603. n->narg.text = wordtext;
  10604. #if BASH_TEST2
  10605. if (strcmp("[[", wordtext) == 0)
  10606. double_brackets_flag = 1;
  10607. else if (strcmp("]]", wordtext) == 0)
  10608. double_brackets_flag = 0;
  10609. #endif
  10610. n->narg.backquote = backquotelist;
  10611. if (savecheckkwd && isassignment(wordtext)) {
  10612. *vpp = n;
  10613. vpp = &n->narg.next;
  10614. } else {
  10615. *app = n;
  10616. app = &n->narg.next;
  10617. savecheckkwd = 0;
  10618. }
  10619. #if BASH_FUNCTION
  10620. if (function_flag) {
  10621. checkkwd = CHKNL | CHKKWD;
  10622. switch (peektoken()) {
  10623. case TBEGIN:
  10624. case TIF:
  10625. case TCASE:
  10626. case TUNTIL:
  10627. case TWHILE:
  10628. case TFOR:
  10629. goto do_func;
  10630. case TLP:
  10631. function_flag = 0;
  10632. break;
  10633. # if BASH_TEST2
  10634. case TWORD:
  10635. if (strcmp("[[", wordtext) == 0)
  10636. goto do_func;
  10637. /* fall through */
  10638. # endif
  10639. default:
  10640. raise_error_unexpected_syntax(-1);
  10641. }
  10642. }
  10643. #endif
  10644. break;
  10645. case TREDIR:
  10646. *rpp = n = redirnode;
  10647. rpp = &n->nfile.next;
  10648. parsefname(); /* read name of redirection file */
  10649. break;
  10650. case TLP:
  10651. IF_BASH_FUNCTION(do_func:)
  10652. if (args && app == &args->narg.next
  10653. && !vars && !redir
  10654. ) {
  10655. struct builtincmd *bcmd;
  10656. const char *name;
  10657. /* We have a function */
  10658. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10659. raise_error_unexpected_syntax(TRP);
  10660. name = n->narg.text;
  10661. if (!goodname(name)
  10662. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10663. ) {
  10664. raise_error_syntax("bad function name");
  10665. }
  10666. n->type = NDEFUN;
  10667. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10668. n->ndefun.text = n->narg.text;
  10669. n->ndefun.linno = g_parsefile->linno;
  10670. n->ndefun.body = parse_command();
  10671. return n;
  10672. }
  10673. IF_BASH_FUNCTION(function_flag = 0;)
  10674. /* fall through */
  10675. default:
  10676. tokpushback = 1;
  10677. goto out;
  10678. }
  10679. }
  10680. out:
  10681. *app = NULL;
  10682. *vpp = NULL;
  10683. *rpp = NULL;
  10684. n = stzalloc(sizeof(struct ncmd));
  10685. if (NCMD != 0)
  10686. n->type = NCMD;
  10687. n->ncmd.linno = savelinno;
  10688. n->ncmd.args = args;
  10689. n->ncmd.assign = vars;
  10690. n->ncmd.redirect = redir;
  10691. return n;
  10692. }
  10693. static union node *
  10694. parse_command(void)
  10695. {
  10696. union node *n1, *n2;
  10697. union node *ap, **app;
  10698. union node *cp, **cpp;
  10699. union node *redir, **rpp;
  10700. union node **rpp2;
  10701. int t;
  10702. int savelinno;
  10703. redir = NULL;
  10704. rpp2 = &redir;
  10705. savelinno = g_parsefile->linno;
  10706. switch (readtoken()) {
  10707. default:
  10708. raise_error_unexpected_syntax(-1);
  10709. /* NOTREACHED */
  10710. case TIF:
  10711. n1 = stzalloc(sizeof(struct nif));
  10712. n1->type = NIF;
  10713. n1->nif.test = list(0);
  10714. if (readtoken() != TTHEN)
  10715. raise_error_unexpected_syntax(TTHEN);
  10716. n1->nif.ifpart = list(0);
  10717. n2 = n1;
  10718. while (readtoken() == TELIF) {
  10719. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10720. n2 = n2->nif.elsepart;
  10721. n2->type = NIF;
  10722. n2->nif.test = list(0);
  10723. if (readtoken() != TTHEN)
  10724. raise_error_unexpected_syntax(TTHEN);
  10725. n2->nif.ifpart = list(0);
  10726. }
  10727. if (lasttoken == TELSE)
  10728. n2->nif.elsepart = list(0);
  10729. else {
  10730. n2->nif.elsepart = NULL;
  10731. tokpushback = 1;
  10732. }
  10733. t = TFI;
  10734. break;
  10735. case TWHILE:
  10736. case TUNTIL: {
  10737. int got;
  10738. n1 = stzalloc(sizeof(struct nbinary));
  10739. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10740. n1->nbinary.ch1 = list(0);
  10741. got = readtoken();
  10742. if (got != TDO) {
  10743. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10744. got == TWORD ? wordtext : ""));
  10745. raise_error_unexpected_syntax(TDO);
  10746. }
  10747. n1->nbinary.ch2 = list(0);
  10748. t = TDONE;
  10749. break;
  10750. }
  10751. case TFOR:
  10752. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10753. raise_error_syntax("bad for loop variable");
  10754. n1 = stzalloc(sizeof(struct nfor));
  10755. n1->type = NFOR;
  10756. n1->nfor.linno = savelinno;
  10757. n1->nfor.var = wordtext;
  10758. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10759. if (readtoken() == TIN) {
  10760. app = &ap;
  10761. while (readtoken() == TWORD) {
  10762. n2 = stzalloc(sizeof(struct narg));
  10763. n2->type = NARG;
  10764. /*n2->narg.next = NULL; - stzalloc did it */
  10765. n2->narg.text = wordtext;
  10766. n2->narg.backquote = backquotelist;
  10767. *app = n2;
  10768. app = &n2->narg.next;
  10769. }
  10770. *app = NULL;
  10771. n1->nfor.args = ap;
  10772. if (lasttoken != TNL && lasttoken != TSEMI)
  10773. raise_error_unexpected_syntax(-1);
  10774. } else {
  10775. n2 = stzalloc(sizeof(struct narg));
  10776. n2->type = NARG;
  10777. /*n2->narg.next = NULL; - stzalloc did it */
  10778. n2->narg.text = (char *)dolatstr;
  10779. /*n2->narg.backquote = NULL;*/
  10780. n1->nfor.args = n2;
  10781. /*
  10782. * Newline or semicolon here is optional (but note
  10783. * that the original Bourne shell only allowed NL).
  10784. */
  10785. if (lasttoken != TSEMI)
  10786. tokpushback = 1;
  10787. }
  10788. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10789. if (readtoken() != TDO)
  10790. raise_error_unexpected_syntax(TDO);
  10791. n1->nfor.body = list(0);
  10792. t = TDONE;
  10793. break;
  10794. case TCASE:
  10795. n1 = stzalloc(sizeof(struct ncase));
  10796. n1->type = NCASE;
  10797. n1->ncase.linno = savelinno;
  10798. if (readtoken() != TWORD)
  10799. raise_error_unexpected_syntax(TWORD);
  10800. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10801. n2->type = NARG;
  10802. /*n2->narg.next = NULL; - stzalloc did it */
  10803. n2->narg.text = wordtext;
  10804. n2->narg.backquote = backquotelist;
  10805. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10806. if (readtoken() != TIN)
  10807. raise_error_unexpected_syntax(TIN);
  10808. cpp = &n1->ncase.cases;
  10809. next_case:
  10810. checkkwd = CHKNL | CHKKWD;
  10811. t = readtoken();
  10812. while (t != TESAC) {
  10813. if (lasttoken == TLP)
  10814. readtoken();
  10815. *cpp = cp = stzalloc(sizeof(struct nclist));
  10816. cp->type = NCLIST;
  10817. app = &cp->nclist.pattern;
  10818. for (;;) {
  10819. *app = ap = stzalloc(sizeof(struct narg));
  10820. ap->type = NARG;
  10821. /*ap->narg.next = NULL; - stzalloc did it */
  10822. ap->narg.text = wordtext;
  10823. ap->narg.backquote = backquotelist;
  10824. if (readtoken() != TPIPE)
  10825. break;
  10826. app = &ap->narg.next;
  10827. readtoken();
  10828. }
  10829. //ap->narg.next = NULL;
  10830. if (lasttoken != TRP)
  10831. raise_error_unexpected_syntax(TRP);
  10832. cp->nclist.body = list(2);
  10833. cpp = &cp->nclist.next;
  10834. checkkwd = CHKNL | CHKKWD;
  10835. t = readtoken();
  10836. if (t != TESAC) {
  10837. if (t != TENDCASE)
  10838. raise_error_unexpected_syntax(TENDCASE);
  10839. goto next_case;
  10840. }
  10841. }
  10842. *cpp = NULL;
  10843. goto redir;
  10844. case TLP:
  10845. n1 = stzalloc(sizeof(struct nredir));
  10846. n1->type = NSUBSHELL;
  10847. n1->nredir.linno = savelinno;
  10848. n1->nredir.n = list(0);
  10849. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10850. t = TRP;
  10851. break;
  10852. case TBEGIN:
  10853. n1 = list(0);
  10854. t = TEND;
  10855. break;
  10856. IF_BASH_FUNCTION(case TFUNCTION:)
  10857. case TWORD:
  10858. case TREDIR:
  10859. tokpushback = 1;
  10860. return simplecmd();
  10861. }
  10862. if (readtoken() != t)
  10863. raise_error_unexpected_syntax(t);
  10864. redir:
  10865. /* Now check for redirection which may follow command */
  10866. checkkwd = CHKKWD | CHKALIAS;
  10867. rpp = rpp2;
  10868. while (readtoken() == TREDIR) {
  10869. *rpp = n2 = redirnode;
  10870. rpp = &n2->nfile.next;
  10871. parsefname();
  10872. }
  10873. tokpushback = 1;
  10874. *rpp = NULL;
  10875. if (redir) {
  10876. if (n1->type != NSUBSHELL) {
  10877. n2 = stzalloc(sizeof(struct nredir));
  10878. n2->type = NREDIR;
  10879. n2->nredir.linno = savelinno;
  10880. n2->nredir.n = n1;
  10881. n1 = n2;
  10882. }
  10883. n1->nredir.redirect = redir;
  10884. }
  10885. return n1;
  10886. }
  10887. #if BASH_DOLLAR_SQUOTE
  10888. static int
  10889. decode_dollar_squote(void)
  10890. {
  10891. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10892. int c, cnt;
  10893. char *p;
  10894. char buf[4];
  10895. c = pgetc();
  10896. p = strchr(C_escapes, c);
  10897. if (p) {
  10898. buf[0] = c;
  10899. p = buf;
  10900. cnt = 3;
  10901. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10902. do {
  10903. c = pgetc();
  10904. *++p = c;
  10905. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10906. pungetc();
  10907. } else if (c == 'x') { /* \xHH */
  10908. do {
  10909. c = pgetc();
  10910. *++p = c;
  10911. } while (isxdigit(c) && --cnt);
  10912. pungetc();
  10913. if (cnt == 3) { /* \x but next char is "bad" */
  10914. c = 'x';
  10915. goto unrecognized;
  10916. }
  10917. } else { /* simple seq like \\ or \t */
  10918. p++;
  10919. }
  10920. *p = '\0';
  10921. p = buf;
  10922. c = bb_process_escape_sequence((void*)&p);
  10923. } else { /* unrecognized "\z": print both chars unless ' or " */
  10924. if (c != '\'' && c != '"') {
  10925. unrecognized:
  10926. c |= 0x100; /* "please encode \, then me" */
  10927. }
  10928. }
  10929. return c;
  10930. }
  10931. #endif
  10932. /* Used by expandstr to get here-doc like behaviour. */
  10933. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  10934. static ALWAYS_INLINE int
  10935. realeofmark(const char *eofmark)
  10936. {
  10937. return eofmark && eofmark != FAKEEOFMARK;
  10938. }
  10939. /*
  10940. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10941. * is not NULL, read a here document. In the latter case, eofmark is the
  10942. * word which marks the end of the document and striptabs is true if
  10943. * leading tabs should be stripped from the document. The argument c
  10944. * is the first character of the input token or document.
  10945. *
  10946. * Because C does not have internal subroutines, I have simulated them
  10947. * using goto's to implement the subroutine linkage. The following macros
  10948. * will run code that appears at the end of readtoken1.
  10949. */
  10950. #define CHECKEND() {goto checkend; checkend_return:;}
  10951. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10952. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10953. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10954. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10955. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10956. static int
  10957. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10958. {
  10959. /* NB: syntax parameter fits into smallint */
  10960. /* c parameter is an unsigned char or PEOF or PEOA */
  10961. char *out;
  10962. size_t len;
  10963. struct nodelist *bqlist;
  10964. smallint quotef;
  10965. smallint oldstyle;
  10966. smallint pssyntax; /* we are expanding a prompt string */
  10967. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10968. /* syntax stack */
  10969. struct synstack synbase = { };
  10970. struct synstack *synstack = &synbase;
  10971. #if ENABLE_ASH_EXPAND_PRMT
  10972. pssyntax = (syntax == PSSYNTAX);
  10973. if (pssyntax)
  10974. syntax = DQSYNTAX;
  10975. #else
  10976. pssyntax = 0; /* constant */
  10977. #endif
  10978. synstack->syntax = syntax;
  10979. if (syntax == DQSYNTAX)
  10980. synstack->dblquote = 1;
  10981. quotef = 0;
  10982. bqlist = NULL;
  10983. STARTSTACKSTR(out);
  10984. loop:
  10985. /* For each line, until end of word */
  10986. CHECKEND(); /* set c to PEOF if at end of here document */
  10987. for (;;) { /* until end of line or end of word */
  10988. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10989. switch (SIT(c, synstack->syntax)) {
  10990. case CNL: /* '\n' */
  10991. if (synstack->syntax == BASESYNTAX
  10992. && !synstack->varnest
  10993. ) {
  10994. goto endword; /* exit outer loop */
  10995. }
  10996. USTPUTC(c, out);
  10997. nlprompt();
  10998. c = pgetc();
  10999. goto loop; /* continue outer loop */
  11000. case CWORD:
  11001. USTPUTC(c, out);
  11002. break;
  11003. case CCTL:
  11004. #if BASH_DOLLAR_SQUOTE
  11005. if (c == '\\' && bash_dollar_squote) {
  11006. c = decode_dollar_squote();
  11007. if (c == '\0') {
  11008. /* skip $'\000', $'\x00' (like bash) */
  11009. break;
  11010. }
  11011. if (c & 0x100) {
  11012. /* Unknown escape. Encode as '\z' */
  11013. c = (unsigned char)c;
  11014. if (eofmark == NULL || synstack->dblquote)
  11015. USTPUTC(CTLESC, out);
  11016. USTPUTC('\\', out);
  11017. }
  11018. }
  11019. #endif
  11020. if (!eofmark || synstack->dblquote || synstack->varnest)
  11021. USTPUTC(CTLESC, out);
  11022. USTPUTC(c, out);
  11023. break;
  11024. case CBACK: /* backslash */
  11025. c = pgetc_without_PEOA();
  11026. if (c == PEOF) {
  11027. USTPUTC(CTLESC, out);
  11028. USTPUTC('\\', out);
  11029. pungetc();
  11030. } else if (c == '\n') {
  11031. nlprompt();
  11032. } else {
  11033. if (pssyntax && c == '$') {
  11034. USTPUTC(CTLESC, out);
  11035. USTPUTC('\\', out);
  11036. }
  11037. /* Backslash is retained if we are in "str"
  11038. * and next char isn't dquote-special.
  11039. */
  11040. if (synstack->dblquote
  11041. && c != '\\'
  11042. && c != '`'
  11043. && c != '$'
  11044. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11045. && (c != '}' || !synstack->varnest)
  11046. ) {
  11047. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11048. USTPUTC('\\', out);
  11049. }
  11050. USTPUTC(CTLESC, out);
  11051. USTPUTC(c, out);
  11052. quotef = 1;
  11053. }
  11054. break;
  11055. case CSQUOTE:
  11056. synstack->syntax = SQSYNTAX;
  11057. quotemark:
  11058. if (eofmark == NULL) {
  11059. USTPUTC(CTLQUOTEMARK, out);
  11060. }
  11061. break;
  11062. case CDQUOTE:
  11063. synstack->syntax = DQSYNTAX;
  11064. synstack->dblquote = 1;
  11065. toggledq:
  11066. if (synstack->varnest)
  11067. synstack->innerdq ^= 1;
  11068. goto quotemark;
  11069. case CENDQUOTE:
  11070. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11071. if (eofmark != NULL && synstack->varnest == 0) {
  11072. USTPUTC(c, out);
  11073. break;
  11074. }
  11075. if (synstack->dqvarnest == 0) {
  11076. synstack->syntax = BASESYNTAX;
  11077. synstack->dblquote = 0;
  11078. }
  11079. quotef = 1;
  11080. if (c == '"')
  11081. goto toggledq;
  11082. goto quotemark;
  11083. case CVAR: /* '$' */
  11084. PARSESUB(); /* parse substitution */
  11085. break;
  11086. case CENDVAR: /* '}' */
  11087. if (!synstack->innerdq && synstack->varnest > 0) {
  11088. if (!--synstack->varnest && synstack->varpushed)
  11089. synstack_pop(&synstack);
  11090. else if (synstack->dqvarnest > 0)
  11091. synstack->dqvarnest--;
  11092. c = CTLENDVAR;
  11093. }
  11094. USTPUTC(c, out);
  11095. break;
  11096. #if ENABLE_FEATURE_SH_MATH
  11097. case CLP: /* '(' in arithmetic */
  11098. synstack->parenlevel++;
  11099. USTPUTC(c, out);
  11100. break;
  11101. case CRP: /* ')' in arithmetic */
  11102. if (synstack->parenlevel > 0) {
  11103. synstack->parenlevel--;
  11104. } else {
  11105. if (pgetc_eatbnl() == ')') {
  11106. c = CTLENDARI;
  11107. synstack_pop(&synstack);
  11108. } else {
  11109. /*
  11110. * unbalanced parens
  11111. * (don't 2nd guess - no error)
  11112. */
  11113. pungetc();
  11114. }
  11115. }
  11116. USTPUTC(c, out);
  11117. break;
  11118. #endif
  11119. case CBQUOTE: /* '`' */
  11120. if (checkkwd & CHKEOFMARK) {
  11121. quotef = 1;
  11122. USTPUTC('`', out);
  11123. break;
  11124. }
  11125. PARSEBACKQOLD();
  11126. break;
  11127. case CENDFILE:
  11128. goto endword; /* exit outer loop */
  11129. case CIGN:
  11130. break;
  11131. default:
  11132. if (synstack->varnest == 0) {
  11133. #if BASH_REDIR_OUTPUT
  11134. if (c == '&') {
  11135. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11136. if (pgetc() == '>')
  11137. c = 0x100 + '>'; /* flag &> */
  11138. pungetc();
  11139. }
  11140. #endif
  11141. goto endword; /* exit outer loop */
  11142. }
  11143. IF_ASH_ALIAS(if (c != PEOA))
  11144. USTPUTC(c, out);
  11145. }
  11146. c = pgetc();
  11147. } /* for (;;) */
  11148. endword:
  11149. #if ENABLE_FEATURE_SH_MATH
  11150. if (synstack->syntax == ARISYNTAX)
  11151. raise_error_syntax("missing '))'");
  11152. #endif
  11153. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11154. raise_error_syntax("unterminated quoted string");
  11155. if (synstack->varnest != 0) {
  11156. /* { */
  11157. raise_error_syntax("missing '}'");
  11158. }
  11159. USTPUTC('\0', out);
  11160. len = out - (char *)stackblock();
  11161. out = stackblock();
  11162. if (eofmark == NULL) {
  11163. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11164. && quotef == 0
  11165. ) {
  11166. if (isdigit_str9(out)) {
  11167. PARSEREDIR(); /* passed as params: out, c */
  11168. lasttoken = TREDIR;
  11169. return lasttoken;
  11170. }
  11171. /* else: non-number X seen, interpret it
  11172. * as "NNNX>file" = "NNNX >file" */
  11173. }
  11174. pungetc();
  11175. }
  11176. quoteflag = quotef;
  11177. backquotelist = bqlist;
  11178. grabstackblock(len);
  11179. wordtext = out;
  11180. lasttoken = TWORD;
  11181. return lasttoken;
  11182. /* end of readtoken routine */
  11183. /*
  11184. * Check to see whether we are at the end of the here document. When this
  11185. * is called, c is set to the first character of the next input line. If
  11186. * we are at the end of the here document, this routine sets the c to PEOF.
  11187. */
  11188. checkend: {
  11189. if (realeofmark(eofmark)) {
  11190. int markloc;
  11191. char *p;
  11192. #if ENABLE_ASH_ALIAS
  11193. if (c == PEOA)
  11194. c = pgetc_without_PEOA();
  11195. #endif
  11196. if (striptabs) {
  11197. while (c == '\t') {
  11198. c = pgetc_without_PEOA();
  11199. }
  11200. }
  11201. markloc = out - (char *)stackblock();
  11202. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11203. if (c != *p)
  11204. goto more_heredoc;
  11205. c = pgetc_without_PEOA();
  11206. }
  11207. if (c == '\n' || c == PEOF) {
  11208. c = PEOF;
  11209. g_parsefile->linno++;
  11210. needprompt = doprompt;
  11211. } else {
  11212. int len_here;
  11213. more_heredoc:
  11214. p = (char *)stackblock() + markloc + 1;
  11215. len_here = out - p;
  11216. if (len_here) {
  11217. len_here -= (c >= PEOF);
  11218. c = p[-1];
  11219. if (len_here) {
  11220. char *str;
  11221. str = alloca(len_here + 1);
  11222. *(char *)mempcpy(str, p, len_here) = '\0';
  11223. pushstring(str, NULL);
  11224. }
  11225. }
  11226. }
  11227. STADJUST((char *)stackblock() + markloc - out, out);
  11228. }
  11229. goto checkend_return;
  11230. }
  11231. /*
  11232. * Parse a redirection operator. The variable "out" points to a string
  11233. * specifying the fd to be redirected. The variable "c" contains the
  11234. * first character of the redirection operator.
  11235. */
  11236. parseredir: {
  11237. /* out is already checked to be a valid number or "" */
  11238. int fd = (*out == '\0' ? -1 : atoi(out));
  11239. union node *np;
  11240. np = stzalloc(sizeof(struct nfile));
  11241. if (c == '>') {
  11242. np->nfile.fd = 1;
  11243. c = pgetc_eatbnl();
  11244. if (c == '>')
  11245. np->type = NAPPEND;
  11246. else if (c == '|')
  11247. np->type = NCLOBBER;
  11248. else if (c == '&')
  11249. np->type = NTOFD;
  11250. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11251. else {
  11252. np->type = NTO;
  11253. pungetc();
  11254. }
  11255. }
  11256. #if BASH_REDIR_OUTPUT
  11257. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11258. np->nfile.fd = 1;
  11259. pgetc(); /* this is '>', no need to check */
  11260. np->type = NTO2;
  11261. }
  11262. #endif
  11263. else { /* c == '<' */
  11264. /*np->nfile.fd = 0; - stzalloc did it */
  11265. c = pgetc_eatbnl();
  11266. switch (c) {
  11267. case '<':
  11268. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11269. np = stzalloc(sizeof(struct nhere));
  11270. /*np->nfile.fd = 0; - stzalloc did it */
  11271. }
  11272. np->type = NHERE;
  11273. heredoc = stzalloc(sizeof(struct heredoc));
  11274. heredoc->here = np;
  11275. c = pgetc_eatbnl();
  11276. if (c == '-') {
  11277. heredoc->striptabs = 1;
  11278. } else {
  11279. /*heredoc->striptabs = 0; - stzalloc did it */
  11280. pungetc();
  11281. }
  11282. break;
  11283. case '&':
  11284. np->type = NFROMFD;
  11285. break;
  11286. case '>':
  11287. np->type = NFROMTO;
  11288. break;
  11289. default:
  11290. np->type = NFROM;
  11291. pungetc();
  11292. break;
  11293. }
  11294. }
  11295. if (fd >= 0)
  11296. np->nfile.fd = fd;
  11297. redirnode = np;
  11298. goto parseredir_return;
  11299. }
  11300. /*
  11301. * Parse a substitution. At this point, we have read the dollar sign
  11302. * and nothing else.
  11303. */
  11304. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11305. * (assuming ascii char codes, as the original implementation did) */
  11306. #define is_special(c) \
  11307. (((unsigned)(c) - 33 < 32) \
  11308. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11309. parsesub: {
  11310. unsigned char subtype;
  11311. int typeloc;
  11312. c = pgetc_eatbnl();
  11313. if ((checkkwd & CHKEOFMARK)
  11314. || c > 255 /* PEOA or PEOF */
  11315. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11316. ) {
  11317. #if BASH_DOLLAR_SQUOTE
  11318. if (synstack->syntax != DQSYNTAX && c == '\'')
  11319. bash_dollar_squote = 1;
  11320. else
  11321. #endif
  11322. USTPUTC('$', out);
  11323. pungetc();
  11324. } else if (c == '(') {
  11325. /* $(command) or $((arith)) */
  11326. if (pgetc_eatbnl() == '(') {
  11327. #if ENABLE_FEATURE_SH_MATH
  11328. PARSEARITH();
  11329. #else
  11330. raise_error_syntax("support for $((arith)) is disabled");
  11331. #endif
  11332. } else {
  11333. pungetc();
  11334. PARSEBACKQNEW();
  11335. }
  11336. } else {
  11337. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11338. smalluint newsyn = synstack->syntax;
  11339. USTPUTC(CTLVAR, out);
  11340. typeloc = out - (char *)stackblock();
  11341. STADJUST(1, out);
  11342. subtype = VSNORMAL;
  11343. if (c == '{') {
  11344. c = pgetc_eatbnl();
  11345. subtype = 0;
  11346. }
  11347. varname:
  11348. if (is_name(c)) {
  11349. /* $[{[#]]NAME[}] */
  11350. do {
  11351. STPUTC(c, out);
  11352. c = pgetc_eatbnl();
  11353. } while (is_in_name(c));
  11354. } else if (isdigit(c)) {
  11355. /* $[{[#]]NUM[}] */
  11356. do {
  11357. STPUTC(c, out);
  11358. c = pgetc_eatbnl();
  11359. } while (isdigit(c));
  11360. } else {
  11361. /* $[{[#]]<specialchar>[}] */
  11362. int cc = c;
  11363. c = pgetc_eatbnl();
  11364. if (!subtype && cc == '#') {
  11365. subtype = VSLENGTH;
  11366. if (c == '_' || isalnum(c))
  11367. goto varname;
  11368. cc = c;
  11369. c = pgetc_eatbnl();
  11370. if (cc == '}' || c != '}') {
  11371. pungetc();
  11372. subtype = 0;
  11373. c = cc;
  11374. cc = '#';
  11375. }
  11376. }
  11377. if (!is_special(cc)) {
  11378. if (subtype == VSLENGTH)
  11379. subtype = 0;
  11380. goto badsub;
  11381. }
  11382. USTPUTC(cc, out);
  11383. }
  11384. if (c != '}' && subtype == VSLENGTH) {
  11385. /* ${#VAR didn't end with } */
  11386. goto badsub;
  11387. }
  11388. if (subtype == 0) {
  11389. static const char types[] ALIGN1 = "}-+?=";
  11390. /* ${VAR...} but not $VAR or ${#VAR} */
  11391. /* c == first char after VAR */
  11392. int cc = c;
  11393. switch (c) {
  11394. case ':':
  11395. c = pgetc_eatbnl();
  11396. #if BASH_SUBSTR
  11397. /* This check is only needed to not misinterpret
  11398. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11399. * constructs.
  11400. */
  11401. if (!strchr(types, c)) {
  11402. subtype = VSSUBSTR;
  11403. pungetc();
  11404. break; /* "goto badsub" is bigger (!) */
  11405. }
  11406. #endif
  11407. subtype = VSNUL;
  11408. /*FALLTHROUGH*/
  11409. default: {
  11410. const char *p = strchr(types, c);
  11411. if (p == NULL)
  11412. break;
  11413. subtype |= p - types + VSNORMAL;
  11414. break;
  11415. }
  11416. case '%':
  11417. case '#':
  11418. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11419. c = pgetc_eatbnl();
  11420. if (c == cc)
  11421. subtype++;
  11422. else
  11423. pungetc();
  11424. newsyn = BASESYNTAX;
  11425. break;
  11426. #if BASH_PATTERN_SUBST
  11427. case '/':
  11428. /* ${v/[/]pattern/repl} */
  11429. //TODO: encode pattern and repl separately.
  11430. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11431. // are broken (should print "ONE")
  11432. subtype = VSREPLACE;
  11433. newsyn = BASESYNTAX;
  11434. c = pgetc_eatbnl();
  11435. if (c != '/')
  11436. goto badsub;
  11437. subtype++; /* VSREPLACEALL */
  11438. break;
  11439. #endif
  11440. }
  11441. } else {
  11442. badsub:
  11443. pungetc();
  11444. }
  11445. if (newsyn == ARISYNTAX)
  11446. newsyn = DQSYNTAX;
  11447. if ((newsyn != synstack->syntax || synstack->innerdq)
  11448. && subtype != VSNORMAL
  11449. ) {
  11450. synstack_push(&synstack,
  11451. synstack->prev ?: alloca(sizeof(*synstack)),
  11452. newsyn);
  11453. synstack->varpushed = 1;
  11454. synstack->dblquote = newsyn != BASESYNTAX;
  11455. }
  11456. ((unsigned char *)stackblock())[typeloc] = subtype;
  11457. if (subtype != VSNORMAL) {
  11458. synstack->varnest++;
  11459. if (synstack->dblquote)
  11460. synstack->dqvarnest++;
  11461. }
  11462. STPUTC('=', out);
  11463. }
  11464. goto parsesub_return;
  11465. }
  11466. /*
  11467. * Called to parse command substitutions. Newstyle is set if the command
  11468. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11469. * list of commands (passed by reference), and savelen is the number of
  11470. * characters on the top of the stack which must be preserved.
  11471. */
  11472. parsebackq: {
  11473. struct nodelist **nlpp;
  11474. union node *n;
  11475. char *str;
  11476. size_t savelen;
  11477. smallint saveprompt = 0;
  11478. str = NULL;
  11479. savelen = out - (char *)stackblock();
  11480. if (savelen > 0) {
  11481. /*
  11482. * FIXME: this can allocate very large block on stack and SEGV.
  11483. * Example:
  11484. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11485. * allocates 100kb for every command subst. With about
  11486. * a hundred command substitutions stack overflows.
  11487. * With larger prepended string, SEGV happens sooner.
  11488. */
  11489. str = alloca(savelen);
  11490. memcpy(str, stackblock(), savelen);
  11491. }
  11492. if (oldstyle) {
  11493. /* We must read until the closing backquote, giving special
  11494. * treatment to some slashes, and then push the string and
  11495. * reread it as input, interpreting it normally.
  11496. */
  11497. char *pout;
  11498. size_t psavelen;
  11499. char *pstr;
  11500. STARTSTACKSTR(pout);
  11501. for (;;) {
  11502. int pc;
  11503. setprompt_if(needprompt, 2);
  11504. pc = pgetc_eatbnl();
  11505. switch (pc) {
  11506. case '`':
  11507. goto done;
  11508. case '\\':
  11509. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11510. if (pc != '\\' && pc != '`' && pc != '$'
  11511. && (!synstack->dblquote || pc != '"')
  11512. ) {
  11513. STPUTC('\\', pout);
  11514. }
  11515. if (pc <= 255 /* not PEOA or PEOF */) {
  11516. break;
  11517. }
  11518. /* fall through */
  11519. case PEOF:
  11520. IF_ASH_ALIAS(case PEOA:)
  11521. raise_error_syntax("EOF in backquote substitution");
  11522. case '\n':
  11523. nlnoprompt();
  11524. break;
  11525. default:
  11526. break;
  11527. }
  11528. STPUTC(pc, pout);
  11529. }
  11530. done:
  11531. STPUTC('\0', pout);
  11532. psavelen = pout - (char *)stackblock();
  11533. if (psavelen > 0) {
  11534. pstr = grabstackstr(pout);
  11535. setinputstring(pstr);
  11536. }
  11537. }
  11538. nlpp = &bqlist;
  11539. while (*nlpp)
  11540. nlpp = &(*nlpp)->next;
  11541. *nlpp = stzalloc(sizeof(**nlpp));
  11542. /* (*nlpp)->next = NULL; - stzalloc did it */
  11543. if (oldstyle) {
  11544. saveprompt = doprompt;
  11545. doprompt = 0;
  11546. }
  11547. n = list(2);
  11548. if (oldstyle)
  11549. doprompt = saveprompt;
  11550. else if (readtoken() != TRP)
  11551. raise_error_unexpected_syntax(TRP);
  11552. (*nlpp)->n = n;
  11553. if (oldstyle) {
  11554. /*
  11555. * Start reading from old file again, ignoring any pushed back
  11556. * tokens left from the backquote parsing
  11557. */
  11558. popfile();
  11559. tokpushback = 0;
  11560. }
  11561. while (stackblocksize() <= savelen)
  11562. growstackblock();
  11563. STARTSTACKSTR(out);
  11564. if (str) {
  11565. memcpy(out, str, savelen);
  11566. STADJUST(savelen, out);
  11567. }
  11568. USTPUTC(CTLBACKQ, out);
  11569. if (oldstyle)
  11570. goto parsebackq_oldreturn;
  11571. goto parsebackq_newreturn;
  11572. }
  11573. #if ENABLE_FEATURE_SH_MATH
  11574. /*
  11575. * Parse an arithmetic expansion (indicate start of one and set state)
  11576. */
  11577. parsearith: {
  11578. synstack_push(&synstack,
  11579. synstack->prev ?: alloca(sizeof(*synstack)),
  11580. ARISYNTAX);
  11581. synstack->dblquote = 1;
  11582. USTPUTC(CTLARI, out);
  11583. goto parsearith_return;
  11584. }
  11585. #endif
  11586. } /* end of readtoken */
  11587. /*
  11588. * Read the next input token.
  11589. * If the token is a word, we set backquotelist to the list of cmds in
  11590. * backquotes. We set quoteflag to true if any part of the word was
  11591. * quoted.
  11592. * If the token is TREDIR, then we set redirnode to a structure containing
  11593. * the redirection.
  11594. *
  11595. * [Change comment: here documents and internal procedures]
  11596. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11597. * word parsing code into a separate routine. In this case, readtoken
  11598. * doesn't need to have any internal procedures, but parseword does.
  11599. * We could also make parseoperator in essence the main routine, and
  11600. * have parseword (readtoken1?) handle both words and redirection.]
  11601. */
  11602. #define NEW_xxreadtoken
  11603. #ifdef NEW_xxreadtoken
  11604. /* singles must be first! */
  11605. static const char xxreadtoken_chars[7] ALIGN1 = {
  11606. '\n', '(', ')', /* singles */
  11607. '&', '|', ';', /* doubles */
  11608. 0
  11609. };
  11610. #define xxreadtoken_singles 3
  11611. #define xxreadtoken_doubles 3
  11612. static const char xxreadtoken_tokens[] ALIGN1 = {
  11613. TNL, TLP, TRP, /* only single occurrence allowed */
  11614. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11615. TEOF, /* corresponds to trailing nul */
  11616. TAND, TOR, TENDCASE /* if double occurrence */
  11617. };
  11618. static int
  11619. xxreadtoken(void)
  11620. {
  11621. int c;
  11622. if (tokpushback) {
  11623. tokpushback = 0;
  11624. return lasttoken;
  11625. }
  11626. setprompt_if(needprompt, 2);
  11627. for (;;) { /* until token or start of word found */
  11628. c = pgetc_eatbnl();
  11629. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11630. continue;
  11631. if (c == '#') {
  11632. while ((c = pgetc()) != '\n' && c != PEOF)
  11633. continue;
  11634. pungetc();
  11635. } else if (c == '\\') {
  11636. break; /* return readtoken1(...) */
  11637. } else {
  11638. const char *p;
  11639. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11640. if (c != PEOF) {
  11641. if (c == '\n') {
  11642. nlnoprompt();
  11643. }
  11644. p = strchr(xxreadtoken_chars, c);
  11645. if (p == NULL)
  11646. break; /* return readtoken1(...) */
  11647. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11648. int cc = pgetc_eatbnl();
  11649. if (cc == c) { /* double occurrence? */
  11650. p += xxreadtoken_doubles + 1;
  11651. } else {
  11652. pungetc();
  11653. #if BASH_REDIR_OUTPUT
  11654. if (c == '&' && cc == '>') /* &> */
  11655. break; /* return readtoken1(...) */
  11656. #endif
  11657. }
  11658. }
  11659. }
  11660. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11661. return lasttoken;
  11662. }
  11663. } /* for (;;) */
  11664. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11665. }
  11666. #else /* old xxreadtoken */
  11667. #define RETURN(token) return lasttoken = token
  11668. static int
  11669. xxreadtoken(void)
  11670. {
  11671. int c;
  11672. if (tokpushback) {
  11673. tokpushback = 0;
  11674. return lasttoken;
  11675. }
  11676. setprompt_if(needprompt, 2);
  11677. for (;;) { /* until token or start of word found */
  11678. c = pgetc_eatbnl();
  11679. switch (c) {
  11680. case ' ': case '\t':
  11681. IF_ASH_ALIAS(case PEOA:)
  11682. continue;
  11683. case '#':
  11684. while ((c = pgetc()) != '\n' && c != PEOF)
  11685. continue;
  11686. pungetc();
  11687. continue;
  11688. case '\n':
  11689. nlnoprompt();
  11690. RETURN(TNL);
  11691. case PEOF:
  11692. RETURN(TEOF);
  11693. case '&':
  11694. if (pgetc_eatbnl() == '&')
  11695. RETURN(TAND);
  11696. pungetc();
  11697. RETURN(TBACKGND);
  11698. case '|':
  11699. if (pgetc_eatbnl() == '|')
  11700. RETURN(TOR);
  11701. pungetc();
  11702. RETURN(TPIPE);
  11703. case ';':
  11704. if (pgetc_eatbnl() == ';')
  11705. RETURN(TENDCASE);
  11706. pungetc();
  11707. RETURN(TSEMI);
  11708. case '(':
  11709. RETURN(TLP);
  11710. case ')':
  11711. RETURN(TRP);
  11712. }
  11713. break;
  11714. }
  11715. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11716. #undef RETURN
  11717. }
  11718. #endif /* old xxreadtoken */
  11719. static int
  11720. readtoken(void)
  11721. {
  11722. int t;
  11723. int kwd = checkkwd;
  11724. #if DEBUG
  11725. smallint alreadyseen = tokpushback;
  11726. #endif
  11727. #if ENABLE_ASH_ALIAS
  11728. top:
  11729. #endif
  11730. t = xxreadtoken();
  11731. /*
  11732. * eat newlines
  11733. */
  11734. if (kwd & CHKNL) {
  11735. while (t == TNL) {
  11736. parseheredoc();
  11737. t = xxreadtoken();
  11738. }
  11739. }
  11740. if (t != TWORD || quoteflag) {
  11741. goto out;
  11742. }
  11743. /*
  11744. * check for keywords
  11745. */
  11746. if (kwd & CHKKWD) {
  11747. const char *const *pp;
  11748. pp = findkwd(wordtext);
  11749. if (pp) {
  11750. lasttoken = t = pp - tokname_array;
  11751. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11752. goto out;
  11753. }
  11754. }
  11755. if (checkkwd & CHKALIAS) {
  11756. #if ENABLE_ASH_ALIAS
  11757. struct alias *ap;
  11758. ap = lookupalias(wordtext, 1);
  11759. if (ap != NULL) {
  11760. if (*ap->val) {
  11761. pushstring(ap->val, ap);
  11762. }
  11763. goto top;
  11764. }
  11765. #endif
  11766. }
  11767. out:
  11768. checkkwd = 0;
  11769. #if DEBUG
  11770. if (!alreadyseen)
  11771. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11772. else
  11773. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11774. #endif
  11775. return t;
  11776. }
  11777. static int
  11778. peektoken(void)
  11779. {
  11780. int t;
  11781. t = readtoken();
  11782. tokpushback = 1;
  11783. return t;
  11784. }
  11785. /*
  11786. * Read and parse a command. Returns NODE_EOF on end of file.
  11787. * (NULL is a valid parse tree indicating a blank line.)
  11788. */
  11789. static union node *
  11790. parsecmd(int interact)
  11791. {
  11792. tokpushback = 0;
  11793. checkkwd = 0;
  11794. heredoclist = 0;
  11795. doprompt = interact;
  11796. setprompt_if(doprompt, doprompt);
  11797. needprompt = 0;
  11798. return list(1);
  11799. }
  11800. /*
  11801. * Input any here documents.
  11802. */
  11803. static void
  11804. parseheredoc(void)
  11805. {
  11806. struct heredoc *here;
  11807. union node *n;
  11808. here = heredoclist;
  11809. heredoclist = NULL;
  11810. while (here) {
  11811. setprompt_if(needprompt, 2);
  11812. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11813. here->eofmark, here->striptabs);
  11814. n = stzalloc(sizeof(struct narg));
  11815. n->narg.type = NARG;
  11816. /*n->narg.next = NULL; - stzalloc did it */
  11817. n->narg.text = wordtext;
  11818. n->narg.backquote = backquotelist;
  11819. here->here->nhere.doc = n;
  11820. here = here->next;
  11821. }
  11822. }
  11823. static const char *
  11824. expandstr(const char *ps, int syntax_type)
  11825. {
  11826. union node n;
  11827. int saveprompt;
  11828. /* XXX Fix (char *) cast. */
  11829. setinputstring((char *)ps);
  11830. saveprompt = doprompt;
  11831. doprompt = 0;
  11832. /* readtoken1() might die horribly.
  11833. * Try a prompt with syntactically wrong command:
  11834. * PS1='$(date "+%H:%M:%S) > '
  11835. */
  11836. {
  11837. volatile int saveint;
  11838. struct jmploc *volatile savehandler = exception_handler;
  11839. struct jmploc jmploc;
  11840. SAVE_INT(saveint);
  11841. if (setjmp(jmploc.loc) == 0) {
  11842. exception_handler = &jmploc;
  11843. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11844. }
  11845. exception_handler = savehandler;
  11846. RESTORE_INT(saveint);
  11847. }
  11848. doprompt = saveprompt;
  11849. popfile();
  11850. n.narg.type = NARG;
  11851. n.narg.next = NULL;
  11852. n.narg.text = wordtext;
  11853. n.narg.backquote = backquotelist;
  11854. expandarg(&n, NULL, EXP_QUOTED);
  11855. return stackblock();
  11856. }
  11857. static inline int
  11858. parser_eof(void)
  11859. {
  11860. return tokpushback && lasttoken == TEOF;
  11861. }
  11862. /*
  11863. * Execute a command or commands contained in a string.
  11864. */
  11865. static int
  11866. evalstring(char *s, int flags)
  11867. {
  11868. struct jmploc *volatile savehandler;
  11869. struct jmploc jmploc;
  11870. int ex;
  11871. union node *n;
  11872. struct stackmark smark;
  11873. int status;
  11874. s = sstrdup(s);
  11875. setinputstring(s);
  11876. setstackmark(&smark);
  11877. status = 0;
  11878. /* On exception inside execution loop, we must popfile().
  11879. * Try interactively:
  11880. * readonly a=a
  11881. * command eval "a=b" # throws "is read only" error
  11882. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11883. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11884. */
  11885. savehandler = exception_handler;
  11886. ex = setjmp(jmploc.loc);
  11887. if (ex)
  11888. goto out;
  11889. exception_handler = &jmploc;
  11890. while ((n = parsecmd(0)) != NODE_EOF) {
  11891. int i;
  11892. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11893. if (n)
  11894. status = i;
  11895. popstackmark(&smark);
  11896. if (evalskip)
  11897. break;
  11898. }
  11899. out:
  11900. popstackmark(&smark);
  11901. popfile();
  11902. stunalloc(s);
  11903. exception_handler = savehandler;
  11904. if (ex)
  11905. longjmp(exception_handler->loc, ex);
  11906. return status;
  11907. }
  11908. /*
  11909. * The eval command.
  11910. */
  11911. static int FAST_FUNC
  11912. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11913. {
  11914. char *p;
  11915. char *concat;
  11916. if (argv[1]) {
  11917. p = argv[1];
  11918. argv += 2;
  11919. if (argv[0]) {
  11920. STARTSTACKSTR(concat);
  11921. for (;;) {
  11922. concat = stack_putstr(p, concat);
  11923. p = *argv++;
  11924. if (p == NULL)
  11925. break;
  11926. STPUTC(' ', concat);
  11927. }
  11928. STPUTC('\0', concat);
  11929. p = grabstackstr(concat);
  11930. }
  11931. return evalstring(p, flags & EV_TESTED);
  11932. }
  11933. return 0;
  11934. }
  11935. /*
  11936. * Read and execute commands.
  11937. * "Top" is nonzero for the top level command loop;
  11938. * it turns on prompting if the shell is interactive.
  11939. */
  11940. static int
  11941. cmdloop(int top)
  11942. {
  11943. union node *n;
  11944. struct stackmark smark;
  11945. int inter;
  11946. int status = 0;
  11947. int numeof = 0;
  11948. TRACE(("cmdloop(%d) called\n", top));
  11949. for (;;) {
  11950. int skip;
  11951. setstackmark(&smark);
  11952. #if JOBS
  11953. if (doing_jobctl)
  11954. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11955. #endif
  11956. inter = 0;
  11957. if (iflag && top) {
  11958. inter++;
  11959. chkmail();
  11960. }
  11961. n = parsecmd(inter);
  11962. #if DEBUG
  11963. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11964. showtree(n);
  11965. #endif
  11966. if (n == NODE_EOF) {
  11967. if (!top || numeof >= 50)
  11968. break;
  11969. if (!stoppedjobs()) {
  11970. if (!Iflag)
  11971. break;
  11972. out2str("\nUse \"exit\" to leave shell.\n");
  11973. }
  11974. numeof++;
  11975. } else if (nflag == 0) {
  11976. int i;
  11977. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11978. job_warning >>= 1;
  11979. numeof = 0;
  11980. i = evaltree(n, 0);
  11981. if (n)
  11982. status = i;
  11983. }
  11984. popstackmark(&smark);
  11985. skip = evalskip;
  11986. if (skip) {
  11987. evalskip &= ~SKIPFUNC;
  11988. break;
  11989. }
  11990. }
  11991. return status;
  11992. }
  11993. /*
  11994. * Take commands from a file. To be compatible we should do a path
  11995. * search for the file, which is necessary to find sub-commands.
  11996. */
  11997. static char *
  11998. find_dot_file(char *name)
  11999. {
  12000. char *fullname;
  12001. const char *path = pathval();
  12002. struct stat statb;
  12003. /* don't try this for absolute or relative paths */
  12004. if (strchr(name, '/'))
  12005. return name;
  12006. while ((fullname = path_advance(&path, name)) != NULL) {
  12007. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12008. /*
  12009. * Don't bother freeing here, since it will
  12010. * be freed by the caller.
  12011. */
  12012. return fullname;
  12013. }
  12014. if (fullname != name)
  12015. stunalloc(fullname);
  12016. }
  12017. /* not found in PATH */
  12018. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12019. return name;
  12020. #else
  12021. ash_msg_and_raise_error("%s: not found", name);
  12022. /* NOTREACHED */
  12023. #endif
  12024. }
  12025. static int FAST_FUNC
  12026. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12027. {
  12028. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12029. int status = 0;
  12030. char *fullname;
  12031. char **argv;
  12032. char *args_need_save;
  12033. volatile struct shparam saveparam;
  12034. //???
  12035. // struct strlist *sp;
  12036. // for (sp = cmdenviron; sp; sp = sp->next)
  12037. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12038. nextopt(nullstr); /* handle possible "--" */
  12039. argv = argptr;
  12040. if (!argv[0]) {
  12041. /* bash says: "bash: .: filename argument required" */
  12042. return 2; /* bash compat */
  12043. }
  12044. /* This aborts if file isn't found, which is POSIXly correct.
  12045. * bash returns exitcode 1 instead.
  12046. */
  12047. fullname = find_dot_file(argv[0]);
  12048. argv++;
  12049. args_need_save = argv[0];
  12050. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12051. int argc;
  12052. saveparam = shellparam;
  12053. shellparam.malloced = 0;
  12054. argc = 1;
  12055. while (argv[argc])
  12056. argc++;
  12057. shellparam.nparam = argc;
  12058. shellparam.p = argv;
  12059. };
  12060. /* This aborts if file can't be opened, which is POSIXly correct.
  12061. * bash returns exitcode 1 instead.
  12062. */
  12063. setinputfile(fullname, INPUT_PUSH_FILE);
  12064. commandname = fullname;
  12065. status = cmdloop(0);
  12066. popfile();
  12067. if (args_need_save) {
  12068. freeparam(&shellparam);
  12069. shellparam = saveparam;
  12070. };
  12071. return status;
  12072. }
  12073. static int FAST_FUNC
  12074. exitcmd(int argc UNUSED_PARAM, char **argv)
  12075. {
  12076. if (stoppedjobs())
  12077. return 0;
  12078. if (argv[1])
  12079. exitstatus = number(argv[1]);
  12080. raise_exception(EXEXIT);
  12081. /* NOTREACHED */
  12082. }
  12083. /*
  12084. * Read a file containing shell functions.
  12085. */
  12086. static void
  12087. readcmdfile(char *name)
  12088. {
  12089. setinputfile(name, INPUT_PUSH_FILE);
  12090. cmdloop(0);
  12091. popfile();
  12092. }
  12093. /* ============ find_command inplementation */
  12094. /*
  12095. * Resolve a command name. If you change this routine, you may have to
  12096. * change the shellexec routine as well.
  12097. */
  12098. static void
  12099. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12100. {
  12101. struct tblentry *cmdp;
  12102. int idx;
  12103. int prev;
  12104. char *fullname;
  12105. struct stat statb;
  12106. int e;
  12107. int updatetbl;
  12108. struct builtincmd *bcmd;
  12109. /* If name contains a slash, don't use PATH or hash table */
  12110. if (strchr(name, '/') != NULL) {
  12111. entry->u.index = -1;
  12112. if (act & DO_ABS) {
  12113. while (stat(name, &statb) < 0) {
  12114. #ifdef SYSV
  12115. if (errno == EINTR)
  12116. continue;
  12117. #endif
  12118. entry->cmdtype = CMDUNKNOWN;
  12119. return;
  12120. }
  12121. }
  12122. entry->cmdtype = CMDNORMAL;
  12123. return;
  12124. }
  12125. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12126. updatetbl = (path == pathval());
  12127. if (!updatetbl) {
  12128. act |= DO_ALTPATH;
  12129. if (strstr(path, "%builtin") != NULL)
  12130. act |= DO_ALTBLTIN;
  12131. }
  12132. /* If name is in the table, check answer will be ok */
  12133. cmdp = cmdlookup(name, 0);
  12134. if (cmdp != NULL) {
  12135. int bit;
  12136. switch (cmdp->cmdtype) {
  12137. default:
  12138. #if DEBUG
  12139. abort();
  12140. #endif
  12141. case CMDNORMAL:
  12142. bit = DO_ALTPATH;
  12143. break;
  12144. case CMDFUNCTION:
  12145. bit = DO_NOFUNC;
  12146. break;
  12147. case CMDBUILTIN:
  12148. bit = DO_ALTBLTIN;
  12149. break;
  12150. }
  12151. if (act & bit) {
  12152. updatetbl = 0;
  12153. cmdp = NULL;
  12154. } else if (cmdp->rehash == 0)
  12155. /* if not invalidated by cd, we're done */
  12156. goto success;
  12157. }
  12158. /* If %builtin not in path, check for builtin next */
  12159. bcmd = find_builtin(name);
  12160. if (bcmd) {
  12161. if (IS_BUILTIN_REGULAR(bcmd))
  12162. goto builtin_success;
  12163. if (act & DO_ALTPATH) {
  12164. if (!(act & DO_ALTBLTIN))
  12165. goto builtin_success;
  12166. } else if (builtinloc <= 0) {
  12167. goto builtin_success;
  12168. }
  12169. }
  12170. #if ENABLE_FEATURE_SH_STANDALONE
  12171. {
  12172. int applet_no = find_applet_by_name(name);
  12173. if (applet_no >= 0) {
  12174. entry->cmdtype = CMDNORMAL;
  12175. entry->u.index = -2 - applet_no;
  12176. return;
  12177. }
  12178. }
  12179. #endif
  12180. /* We have to search path. */
  12181. prev = -1; /* where to start */
  12182. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12183. if (cmdp->cmdtype == CMDBUILTIN)
  12184. prev = builtinloc;
  12185. else
  12186. prev = cmdp->param.index;
  12187. }
  12188. e = ENOENT;
  12189. idx = -1;
  12190. loop:
  12191. while ((fullname = path_advance(&path, name)) != NULL) {
  12192. stunalloc(fullname);
  12193. /* NB: code below will still use fullname
  12194. * despite it being "unallocated" */
  12195. idx++;
  12196. if (pathopt) {
  12197. if (prefix(pathopt, "builtin")) {
  12198. if (bcmd)
  12199. goto builtin_success;
  12200. continue;
  12201. }
  12202. if ((act & DO_NOFUNC)
  12203. || !prefix(pathopt, "func")
  12204. ) { /* ignore unimplemented options */
  12205. continue;
  12206. }
  12207. }
  12208. /* if rehash, don't redo absolute path names */
  12209. if (fullname[0] == '/' && idx <= prev) {
  12210. if (idx < prev)
  12211. continue;
  12212. TRACE(("searchexec \"%s\": no change\n", name));
  12213. goto success;
  12214. }
  12215. while (stat(fullname, &statb) < 0) {
  12216. #ifdef SYSV
  12217. if (errno == EINTR)
  12218. continue;
  12219. #endif
  12220. if (errno != ENOENT && errno != ENOTDIR)
  12221. e = errno;
  12222. goto loop;
  12223. }
  12224. e = EACCES; /* if we fail, this will be the error */
  12225. if (!S_ISREG(statb.st_mode))
  12226. continue;
  12227. if (pathopt) { /* this is a %func directory */
  12228. stalloc(strlen(fullname) + 1);
  12229. /* NB: stalloc will return space pointed by fullname
  12230. * (because we don't have any intervening allocations
  12231. * between stunalloc above and this stalloc) */
  12232. readcmdfile(fullname);
  12233. cmdp = cmdlookup(name, 0);
  12234. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12235. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12236. stunalloc(fullname);
  12237. goto success;
  12238. }
  12239. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12240. if (!updatetbl) {
  12241. entry->cmdtype = CMDNORMAL;
  12242. entry->u.index = idx;
  12243. return;
  12244. }
  12245. INT_OFF;
  12246. cmdp = cmdlookup(name, 1);
  12247. cmdp->cmdtype = CMDNORMAL;
  12248. cmdp->param.index = idx;
  12249. INT_ON;
  12250. goto success;
  12251. }
  12252. /* We failed. If there was an entry for this command, delete it */
  12253. if (cmdp && updatetbl)
  12254. delete_cmd_entry();
  12255. if (act & DO_ERR) {
  12256. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12257. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12258. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12259. char *argv[3];
  12260. argv[0] = (char*) "command_not_found_handle";
  12261. argv[1] = name;
  12262. argv[2] = NULL;
  12263. evalfun(hookp->param.func, 2, argv, 0);
  12264. entry->cmdtype = CMDUNKNOWN;
  12265. return;
  12266. }
  12267. #endif
  12268. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12269. }
  12270. entry->cmdtype = CMDUNKNOWN;
  12271. return;
  12272. builtin_success:
  12273. if (!updatetbl) {
  12274. entry->cmdtype = CMDBUILTIN;
  12275. entry->u.cmd = bcmd;
  12276. return;
  12277. }
  12278. INT_OFF;
  12279. cmdp = cmdlookup(name, 1);
  12280. cmdp->cmdtype = CMDBUILTIN;
  12281. cmdp->param.cmd = bcmd;
  12282. INT_ON;
  12283. success:
  12284. cmdp->rehash = 0;
  12285. entry->cmdtype = cmdp->cmdtype;
  12286. entry->u = cmdp->param;
  12287. }
  12288. /*
  12289. * The trap builtin.
  12290. */
  12291. static int FAST_FUNC
  12292. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12293. {
  12294. char *action;
  12295. char **ap;
  12296. int signo, exitcode;
  12297. nextopt(nullstr);
  12298. ap = argptr;
  12299. if (!*ap) {
  12300. for (signo = 0; signo < NSIG; signo++) {
  12301. char *tr = trap_ptr[signo];
  12302. if (tr) {
  12303. /* note: bash adds "SIG", but only if invoked
  12304. * as "bash". If called as "sh", or if set -o posix,
  12305. * then it prints short signal names.
  12306. * We are printing short names: */
  12307. out1fmt("trap -- %s %s\n",
  12308. single_quote(tr),
  12309. get_signame(signo));
  12310. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12311. * In this case, we will exit very soon, no need to free(). */
  12312. /* if (trap_ptr != trap && tp[0]) */
  12313. /* free(tr); */
  12314. }
  12315. }
  12316. /*
  12317. if (trap_ptr != trap) {
  12318. free(trap_ptr);
  12319. trap_ptr = trap;
  12320. }
  12321. */
  12322. return 0;
  12323. }
  12324. /* Why the second check?
  12325. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12326. * In this case, NUM is signal no, not an action.
  12327. */
  12328. action = NULL;
  12329. if (ap[1] && !is_number(ap[0]))
  12330. action = *ap++;
  12331. exitcode = 0;
  12332. while (*ap) {
  12333. signo = get_signum(*ap);
  12334. if (signo < 0) {
  12335. /* Mimic bash message exactly */
  12336. ash_msg("%s: invalid signal specification", *ap);
  12337. exitcode = 1;
  12338. goto next;
  12339. }
  12340. INT_OFF;
  12341. if (action) {
  12342. if (LONE_DASH(action))
  12343. action = NULL;
  12344. else {
  12345. if (action[0]) /* not NULL and not "" and not "-" */
  12346. may_have_traps = 1;
  12347. action = ckstrdup(action);
  12348. }
  12349. }
  12350. free(trap[signo]);
  12351. trap[signo] = action;
  12352. if (signo != 0)
  12353. setsignal(signo);
  12354. INT_ON;
  12355. next:
  12356. ap++;
  12357. }
  12358. return exitcode;
  12359. }
  12360. /* ============ Builtins */
  12361. #if ENABLE_ASH_HELP
  12362. static int FAST_FUNC
  12363. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12364. {
  12365. unsigned col;
  12366. unsigned i;
  12367. out1fmt(
  12368. "Built-in commands:\n"
  12369. "------------------\n");
  12370. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12371. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12372. builtintab[i].name + 1);
  12373. if (col > 60) {
  12374. out1fmt("\n");
  12375. col = 0;
  12376. }
  12377. }
  12378. # if ENABLE_FEATURE_SH_STANDALONE
  12379. {
  12380. const char *a = applet_names;
  12381. while (*a) {
  12382. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12383. if (col > 60) {
  12384. out1fmt("\n");
  12385. col = 0;
  12386. }
  12387. while (*a++ != '\0')
  12388. continue;
  12389. }
  12390. }
  12391. # endif
  12392. newline_and_flush(stdout);
  12393. return EXIT_SUCCESS;
  12394. }
  12395. #endif
  12396. #if MAX_HISTORY
  12397. static int FAST_FUNC
  12398. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12399. {
  12400. show_history(line_input_state);
  12401. return EXIT_SUCCESS;
  12402. }
  12403. #endif
  12404. /*
  12405. * The export and readonly commands.
  12406. */
  12407. static int FAST_FUNC
  12408. exportcmd(int argc UNUSED_PARAM, char **argv)
  12409. {
  12410. struct var *vp;
  12411. char *name;
  12412. const char *p;
  12413. char **aptr;
  12414. char opt;
  12415. int flag;
  12416. int flag_off;
  12417. /* "readonly" in bash accepts, but ignores -n.
  12418. * We do the same: it saves a conditional in nextopt's param.
  12419. */
  12420. flag_off = 0;
  12421. while ((opt = nextopt("np")) != '\0') {
  12422. if (opt == 'n')
  12423. flag_off = VEXPORT;
  12424. }
  12425. flag = VEXPORT;
  12426. if (argv[0][0] == 'r') {
  12427. flag = VREADONLY;
  12428. flag_off = 0; /* readonly ignores -n */
  12429. }
  12430. flag_off = ~flag_off;
  12431. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12432. {
  12433. aptr = argptr;
  12434. name = *aptr;
  12435. if (name) {
  12436. do {
  12437. p = strchr(name, '=');
  12438. if (p != NULL) {
  12439. p++;
  12440. } else {
  12441. vp = *findvar(hashvar(name), name);
  12442. if (vp) {
  12443. vp->flags = ((vp->flags | flag) & flag_off);
  12444. continue;
  12445. }
  12446. }
  12447. setvar(name, p, (flag & flag_off));
  12448. } while ((name = *++aptr) != NULL);
  12449. return 0;
  12450. }
  12451. }
  12452. /* No arguments. Show the list of exported or readonly vars.
  12453. * -n is ignored.
  12454. */
  12455. showvars(argv[0], flag, 0);
  12456. return 0;
  12457. }
  12458. /*
  12459. * Delete a function if it exists.
  12460. */
  12461. static void
  12462. unsetfunc(const char *name)
  12463. {
  12464. struct tblentry *cmdp;
  12465. cmdp = cmdlookup(name, 0);
  12466. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12467. delete_cmd_entry();
  12468. }
  12469. /*
  12470. * The unset builtin command. We unset the function before we unset the
  12471. * variable to allow a function to be unset when there is a readonly variable
  12472. * with the same name.
  12473. */
  12474. static int FAST_FUNC
  12475. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12476. {
  12477. char **ap;
  12478. int i;
  12479. int flag = 0;
  12480. while ((i = nextopt("vf")) != 0) {
  12481. flag = i;
  12482. }
  12483. for (ap = argptr; *ap; ap++) {
  12484. if (flag != 'f') {
  12485. unsetvar(*ap);
  12486. continue;
  12487. }
  12488. if (flag != 'v')
  12489. unsetfunc(*ap);
  12490. }
  12491. return 0;
  12492. }
  12493. static const unsigned char timescmd_str[] ALIGN1 = {
  12494. ' ', offsetof(struct tms, tms_utime),
  12495. '\n', offsetof(struct tms, tms_stime),
  12496. ' ', offsetof(struct tms, tms_cutime),
  12497. '\n', offsetof(struct tms, tms_cstime),
  12498. 0
  12499. };
  12500. static int FAST_FUNC
  12501. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12502. {
  12503. unsigned clk_tck;
  12504. const unsigned char *p;
  12505. struct tms buf;
  12506. clk_tck = bb_clk_tck();
  12507. times(&buf);
  12508. p = timescmd_str;
  12509. do {
  12510. unsigned sec, frac;
  12511. unsigned long t;
  12512. t = *(clock_t *)(((char *) &buf) + p[1]);
  12513. sec = t / clk_tck;
  12514. frac = t % clk_tck;
  12515. out1fmt("%um%u.%03us%c",
  12516. sec / 60, sec % 60,
  12517. (frac * 1000) / clk_tck,
  12518. p[0]);
  12519. p += 2;
  12520. } while (*p);
  12521. return 0;
  12522. }
  12523. #if ENABLE_FEATURE_SH_MATH
  12524. /*
  12525. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12526. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12527. *
  12528. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12529. */
  12530. static int FAST_FUNC
  12531. letcmd(int argc UNUSED_PARAM, char **argv)
  12532. {
  12533. arith_t i;
  12534. argv++;
  12535. if (!*argv)
  12536. ash_msg_and_raise_error("expression expected");
  12537. do {
  12538. i = ash_arith(*argv);
  12539. } while (*++argv);
  12540. return !i;
  12541. }
  12542. #endif
  12543. /*
  12544. * The read builtin. Options:
  12545. * -r Do not interpret '\' specially
  12546. * -s Turn off echo (tty only)
  12547. * -n NCHARS Read NCHARS max
  12548. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12549. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12550. * -u FD Read from given FD instead of fd 0
  12551. * -d DELIM End on DELIM char, not newline
  12552. * This uses unbuffered input, which may be avoidable in some cases.
  12553. * TODO: bash also has:
  12554. * -a ARRAY Read into array[0],[1],etc
  12555. * -e Use line editing (tty only)
  12556. */
  12557. static int FAST_FUNC
  12558. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12559. {
  12560. char *opt_n = NULL;
  12561. char *opt_p = NULL;
  12562. char *opt_t = NULL;
  12563. char *opt_u = NULL;
  12564. char *opt_d = NULL; /* optimized out if !BASH */
  12565. int read_flags = 0;
  12566. const char *r;
  12567. int i;
  12568. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12569. switch (i) {
  12570. case 'p':
  12571. opt_p = optionarg;
  12572. break;
  12573. case 'n':
  12574. opt_n = optionarg;
  12575. break;
  12576. case 's':
  12577. read_flags |= BUILTIN_READ_SILENT;
  12578. break;
  12579. case 't':
  12580. opt_t = optionarg;
  12581. break;
  12582. case 'r':
  12583. read_flags |= BUILTIN_READ_RAW;
  12584. break;
  12585. case 'u':
  12586. opt_u = optionarg;
  12587. break;
  12588. #if BASH_READ_D
  12589. case 'd':
  12590. opt_d = optionarg;
  12591. break;
  12592. #endif
  12593. default:
  12594. break;
  12595. }
  12596. }
  12597. /* "read -s" needs to save/restore termios, can't allow ^C
  12598. * to jump out of it.
  12599. */
  12600. again:
  12601. INT_OFF;
  12602. r = shell_builtin_read(setvar0,
  12603. argptr,
  12604. bltinlookup("IFS"), /* can be NULL */
  12605. read_flags,
  12606. opt_n,
  12607. opt_p,
  12608. opt_t,
  12609. opt_u,
  12610. opt_d
  12611. );
  12612. INT_ON;
  12613. if ((uintptr_t)r == 1 && errno == EINTR) {
  12614. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12615. * Correct behavior is to not exit "read"
  12616. */
  12617. if (pending_sig == 0)
  12618. goto again;
  12619. }
  12620. if ((uintptr_t)r > 1)
  12621. ash_msg_and_raise_error(r);
  12622. return (uintptr_t)r;
  12623. }
  12624. static int FAST_FUNC
  12625. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12626. {
  12627. static const char permuser[3] ALIGN1 = "ogu";
  12628. mode_t mask;
  12629. int symbolic_mode = 0;
  12630. while (nextopt("S") != '\0') {
  12631. symbolic_mode = 1;
  12632. }
  12633. INT_OFF;
  12634. mask = umask(0);
  12635. umask(mask);
  12636. INT_ON;
  12637. if (*argptr == NULL) {
  12638. if (symbolic_mode) {
  12639. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12640. char *p = buf;
  12641. int i;
  12642. i = 2;
  12643. for (;;) {
  12644. *p++ = ',';
  12645. *p++ = permuser[i];
  12646. *p++ = '=';
  12647. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12648. if (!(mask & 0400)) *p++ = 'r';
  12649. if (!(mask & 0200)) *p++ = 'w';
  12650. if (!(mask & 0100)) *p++ = 'x';
  12651. mask <<= 3;
  12652. if (--i < 0)
  12653. break;
  12654. }
  12655. *p = '\0';
  12656. puts(buf + 1);
  12657. } else {
  12658. out1fmt("%04o\n", mask);
  12659. }
  12660. } else {
  12661. char *modestr = *argptr;
  12662. /* numeric umasks are taken as-is */
  12663. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12664. if (!isdigit(modestr[0]))
  12665. mask ^= 0777;
  12666. mask = bb_parse_mode(modestr, mask);
  12667. if ((unsigned)mask > 0777) {
  12668. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12669. }
  12670. if (!isdigit(modestr[0]))
  12671. mask ^= 0777;
  12672. umask(mask);
  12673. }
  12674. return 0;
  12675. }
  12676. static int FAST_FUNC
  12677. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12678. {
  12679. return shell_builtin_ulimit(argv);
  12680. }
  12681. /* ============ main() and helpers */
  12682. /*
  12683. * Called to exit the shell.
  12684. */
  12685. static void
  12686. exitshell(void)
  12687. {
  12688. struct jmploc loc;
  12689. char *p;
  12690. int status;
  12691. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12692. save_history(line_input_state);
  12693. #endif
  12694. status = exitstatus;
  12695. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12696. if (setjmp(loc.loc)) {
  12697. if (exception_type == EXEXIT)
  12698. status = exitstatus;
  12699. goto out;
  12700. }
  12701. exception_handler = &loc;
  12702. p = trap[0];
  12703. if (p) {
  12704. trap[0] = NULL;
  12705. evalskip = 0;
  12706. evalstring(p, 0);
  12707. /*free(p); - we'll exit soon */
  12708. }
  12709. out:
  12710. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12711. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12712. */
  12713. setjobctl(0);
  12714. flush_stdout_stderr();
  12715. _exit(status);
  12716. /* NOTREACHED */
  12717. }
  12718. /* Don't inline: conserve stack of caller from having our locals too */
  12719. static NOINLINE void
  12720. init(void)
  12721. {
  12722. /* we will never free this */
  12723. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12724. basepf.linno = 1;
  12725. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12726. setsignal(SIGCHLD);
  12727. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12728. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12729. */
  12730. signal(SIGHUP, SIG_DFL);
  12731. {
  12732. char **envp;
  12733. const char *p;
  12734. initvar();
  12735. for (envp = environ; envp && *envp; envp++) {
  12736. /* Used to have
  12737. * p = endofname(*envp);
  12738. * if (p != *envp && *p == '=') {
  12739. * here to weed out badly-named variables, but this breaks
  12740. * scenarios where people do want them passed to children:
  12741. * import os
  12742. * os.environ["test-test"]="test"
  12743. * if os.fork() == 0:
  12744. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12745. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12746. */
  12747. if (strchr(*envp, '=')) {
  12748. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12749. }
  12750. }
  12751. setvareq((char*)defoptindvar, VTEXTFIXED);
  12752. setvar0("PPID", utoa(getppid()));
  12753. #if BASH_SHLVL_VAR
  12754. p = lookupvar("SHLVL");
  12755. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12756. #endif
  12757. #if BASH_HOSTNAME_VAR
  12758. if (!lookupvar("HOSTNAME")) {
  12759. struct utsname uts;
  12760. uname(&uts);
  12761. setvar0("HOSTNAME", uts.nodename);
  12762. }
  12763. #endif
  12764. p = lookupvar("PWD");
  12765. if (p) {
  12766. struct stat st1, st2;
  12767. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12768. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12769. ) {
  12770. p = NULL;
  12771. }
  12772. }
  12773. setpwd(p, 0);
  12774. }
  12775. }
  12776. //usage:#define ash_trivial_usage
  12777. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12778. //usage:#define ash_full_usage "\n\n"
  12779. //usage: "Unix shell interpreter"
  12780. /*
  12781. * Process the shell command line arguments.
  12782. */
  12783. static int
  12784. procargs(char **argv)
  12785. {
  12786. int i;
  12787. const char *xminusc;
  12788. char **xargv;
  12789. int login_sh;
  12790. xargv = argv;
  12791. login_sh = xargv[0] && xargv[0][0] == '-';
  12792. arg0 = xargv[0];
  12793. /* if (xargv[0]) - mmm, this is always true! */
  12794. xargv++;
  12795. for (i = 0; i < NOPTS; i++)
  12796. optlist[i] = 2;
  12797. argptr = xargv;
  12798. if (options(/*cmdline:*/ 1, &login_sh)) {
  12799. /* it already printed err message */
  12800. raise_exception(EXERROR);
  12801. }
  12802. xargv = argptr;
  12803. xminusc = minusc;
  12804. if (*xargv == NULL) {
  12805. if (xminusc)
  12806. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12807. sflag = 1;
  12808. }
  12809. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12810. iflag = 1;
  12811. if (mflag == 2)
  12812. mflag = iflag;
  12813. for (i = 0; i < NOPTS; i++)
  12814. if (optlist[i] == 2)
  12815. optlist[i] = 0;
  12816. #if DEBUG == 2
  12817. debug = 1;
  12818. #endif
  12819. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12820. if (xminusc) {
  12821. minusc = *xargv++;
  12822. if (*xargv)
  12823. goto setarg0;
  12824. } else if (!sflag) {
  12825. setinputfile(*xargv, 0);
  12826. setarg0:
  12827. arg0 = *xargv++;
  12828. commandname = arg0;
  12829. }
  12830. shellparam.p = xargv;
  12831. #if ENABLE_ASH_GETOPTS
  12832. shellparam.optind = 1;
  12833. shellparam.optoff = -1;
  12834. #endif
  12835. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12836. while (*xargv) {
  12837. shellparam.nparam++;
  12838. xargv++;
  12839. }
  12840. optschanged();
  12841. return login_sh;
  12842. }
  12843. /*
  12844. * Read /etc/profile, ~/.profile, $ENV.
  12845. */
  12846. static void
  12847. read_profile(const char *name)
  12848. {
  12849. name = expandstr(name, DQSYNTAX);
  12850. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12851. return;
  12852. cmdloop(0);
  12853. popfile();
  12854. }
  12855. /*
  12856. * This routine is called when an error or an interrupt occurs in an
  12857. * interactive shell and control is returned to the main command loop.
  12858. * (In dash, this function is auto-generated by build machinery).
  12859. */
  12860. static void
  12861. reset(void)
  12862. {
  12863. /* from eval.c: */
  12864. evalskip = 0;
  12865. loopnest = 0;
  12866. /* from expand.c: */
  12867. ifsfree();
  12868. /* from input.c: */
  12869. g_parsefile->left_in_buffer = 0;
  12870. g_parsefile->left_in_line = 0; /* clear input buffer */
  12871. popallfiles();
  12872. /* from redir.c: */
  12873. unwindredir(NULL);
  12874. /* from var.c: */
  12875. unwindlocalvars(NULL);
  12876. }
  12877. #if PROFILE
  12878. static short profile_buf[16384];
  12879. extern int etext();
  12880. #endif
  12881. /*
  12882. * Main routine. We initialize things, parse the arguments, execute
  12883. * profiles if we're a login shell, and then call cmdloop to execute
  12884. * commands. The setjmp call sets up the location to jump to when an
  12885. * exception occurs. When an exception occurs the variable "state"
  12886. * is used to figure out how far we had gotten.
  12887. */
  12888. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12889. int ash_main(int argc UNUSED_PARAM, char **argv)
  12890. {
  12891. volatile smallint state;
  12892. struct jmploc jmploc;
  12893. struct stackmark smark;
  12894. int login_sh;
  12895. /* Initialize global data */
  12896. INIT_G_misc();
  12897. INIT_G_memstack();
  12898. INIT_G_var();
  12899. #if ENABLE_ASH_ALIAS
  12900. INIT_G_alias();
  12901. #endif
  12902. INIT_G_cmdtable();
  12903. #if PROFILE
  12904. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12905. #endif
  12906. #if ENABLE_FEATURE_EDITING
  12907. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12908. #endif
  12909. state = 0;
  12910. if (setjmp(jmploc.loc)) {
  12911. smallint e;
  12912. smallint s;
  12913. reset();
  12914. e = exception_type;
  12915. s = state;
  12916. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12917. exitshell();
  12918. }
  12919. if (e == EXINT) {
  12920. newline_and_flush(stderr);
  12921. }
  12922. popstackmark(&smark);
  12923. FORCE_INT_ON; /* enable interrupts */
  12924. if (s == 1)
  12925. goto state1;
  12926. if (s == 2)
  12927. goto state2;
  12928. if (s == 3)
  12929. goto state3;
  12930. goto state4;
  12931. }
  12932. exception_handler = &jmploc;
  12933. rootpid = getpid();
  12934. init();
  12935. setstackmark(&smark);
  12936. login_sh = procargs(argv);
  12937. #if DEBUG
  12938. TRACE(("Shell args: "));
  12939. trace_puts_args(argv);
  12940. #endif
  12941. if (login_sh) {
  12942. const char *hp;
  12943. state = 1;
  12944. read_profile("/etc/profile");
  12945. state1:
  12946. state = 2;
  12947. hp = lookupvar("HOME");
  12948. if (hp)
  12949. read_profile("$HOME/.profile");
  12950. }
  12951. state2:
  12952. state = 3;
  12953. if (
  12954. #ifndef linux
  12955. getuid() == geteuid() && getgid() == getegid() &&
  12956. #endif
  12957. iflag
  12958. ) {
  12959. const char *shinit = lookupvar("ENV");
  12960. if (shinit != NULL && *shinit != '\0')
  12961. read_profile(shinit);
  12962. }
  12963. popstackmark(&smark);
  12964. state3:
  12965. state = 4;
  12966. if (minusc) {
  12967. /* evalstring pushes parsefile stack.
  12968. * Ensure we don't falsely claim that 0 (stdin)
  12969. * is one of stacked source fds.
  12970. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12971. // if (!sflag) g_parsefile->pf_fd = -1;
  12972. // ^^ not necessary since now we special-case fd 0
  12973. // in save_fd_on_redirect()
  12974. evalstring(minusc, sflag ? 0 : EV_EXIT);
  12975. }
  12976. if (sflag || minusc == NULL) {
  12977. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12978. if (iflag) {
  12979. const char *hp = lookupvar("HISTFILE");
  12980. if (!hp) {
  12981. hp = lookupvar("HOME");
  12982. if (hp) {
  12983. INT_OFF;
  12984. hp = concat_path_file(hp, ".ash_history");
  12985. setvar0("HISTFILE", hp);
  12986. free((char*)hp);
  12987. INT_ON;
  12988. hp = lookupvar("HISTFILE");
  12989. }
  12990. }
  12991. if (hp)
  12992. line_input_state->hist_file = hp;
  12993. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12994. hp = lookupvar("HISTFILESIZE");
  12995. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12996. # endif
  12997. }
  12998. #endif
  12999. state4: /* XXX ??? - why isn't this before the "if" statement */
  13000. cmdloop(1);
  13001. }
  13002. #if PROFILE
  13003. monitor(0);
  13004. #endif
  13005. #ifdef GPROF
  13006. {
  13007. extern void _mcleanup(void);
  13008. _mcleanup();
  13009. }
  13010. #endif
  13011. TRACE(("End of main reached\n"));
  13012. exitshell();
  13013. /* NOTREACHED */
  13014. }
  13015. /*-
  13016. * Copyright (c) 1989, 1991, 1993, 1994
  13017. * The Regents of the University of California. All rights reserved.
  13018. *
  13019. * This code is derived from software contributed to Berkeley by
  13020. * Kenneth Almquist.
  13021. *
  13022. * Redistribution and use in source and binary forms, with or without
  13023. * modification, are permitted provided that the following conditions
  13024. * are met:
  13025. * 1. Redistributions of source code must retain the above copyright
  13026. * notice, this list of conditions and the following disclaimer.
  13027. * 2. Redistributions in binary form must reproduce the above copyright
  13028. * notice, this list of conditions and the following disclaimer in the
  13029. * documentation and/or other materials provided with the distribution.
  13030. * 3. Neither the name of the University nor the names of its contributors
  13031. * may be used to endorse or promote products derived from this software
  13032. * without specific prior written permission.
  13033. *
  13034. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13035. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13036. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13037. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13038. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13039. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13040. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13041. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13042. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13043. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13044. * SUCH DAMAGE.
  13045. */