ash.c 325 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461
  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 (78 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. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  179. # include "embedded_scripts.h"
  180. #else
  181. # define NUM_SCRIPTS 0
  182. #endif
  183. /* So far, all bash compat is controlled by one config option */
  184. /* Separate defines document which part of code implements what */
  185. /* function keyword */
  186. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  187. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  188. /* &>file */
  189. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  191. /* $'...' */
  192. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  194. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  195. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  196. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  197. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  198. /* BASH_TEST2: [[ EXPR ]]
  199. * Status of [[ support:
  200. * We replace && and || with -a and -o
  201. * TODO:
  202. * singleword+noglob expansion:
  203. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  204. * [[ /bin/n* ]]; echo 0:$?
  205. * -a/-o are not AND/OR ops! (they are just strings)
  206. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  207. * = is glob match operator, not equality operator: STR = GLOB
  208. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  209. * == same as =
  210. * add =~ regex match operator: STR =~ REGEX
  211. */
  212. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  213. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  214. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  215. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  216. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  217. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  218. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  219. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  220. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  221. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  222. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  223. /* Bionic at least up to version 24 has no glob() */
  224. # undef ENABLE_ASH_INTERNAL_GLOB
  225. # define ENABLE_ASH_INTERNAL_GLOB 1
  226. #endif
  227. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  228. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  229. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  230. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  231. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  232. # error fails to match dirname, subsequently not expanding <pattern> in it.
  233. // Testcase:
  234. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  235. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  236. #endif
  237. #if !ENABLE_ASH_INTERNAL_GLOB
  238. # include <glob.h>
  239. #endif
  240. #include "unicode.h"
  241. #include "shell_common.h"
  242. #if ENABLE_FEATURE_SH_MATH
  243. # include "math.h"
  244. #else
  245. typedef long arith_t;
  246. # define ARITH_FMT "%ld"
  247. #endif
  248. #if ENABLE_ASH_RANDOM_SUPPORT
  249. # include "random.h"
  250. #else
  251. # define CLEAR_RANDOM_T(rnd) ((void)0)
  252. #endif
  253. #include "NUM_APPLETS.h"
  254. #if NUM_APPLETS == 1
  255. /* STANDALONE does not make sense, and won't compile */
  256. # undef CONFIG_FEATURE_SH_STANDALONE
  257. # undef ENABLE_FEATURE_SH_STANDALONE
  258. # undef IF_FEATURE_SH_STANDALONE
  259. # undef IF_NOT_FEATURE_SH_STANDALONE
  260. # define ENABLE_FEATURE_SH_STANDALONE 0
  261. # define IF_FEATURE_SH_STANDALONE(...)
  262. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  263. #endif
  264. #ifndef F_DUPFD_CLOEXEC
  265. # define F_DUPFD_CLOEXEC F_DUPFD
  266. #endif
  267. #ifndef O_CLOEXEC
  268. # define O_CLOEXEC 0
  269. #endif
  270. #ifndef PIPE_BUF
  271. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  272. #endif
  273. #if !BB_MMU
  274. # error "Do not even bother, ash will not run on NOMMU machine"
  275. #endif
  276. /* We use a trick to have more optimized code (fewer pointer reloads):
  277. * ash.c: extern struct globals *const ash_ptr_to_globals;
  278. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  279. * This way, compiler in ash.c knows the pointer can not change.
  280. *
  281. * However, this may break on weird arches or toolchains. In this case,
  282. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  283. * this optimization.
  284. */
  285. #ifndef BB_GLOBAL_CONST
  286. # define BB_GLOBAL_CONST const
  287. #endif
  288. /* ============ Hash table sizes. Configurable. */
  289. #define VTABSIZE 39
  290. #define ATABSIZE 39
  291. #define CMDTABLESIZE 31 /* should be prime */
  292. /* ============ Shell options */
  293. static const char *const optletters_optnames[] = {
  294. "e" "errexit",
  295. "f" "noglob",
  296. "I" "ignoreeof",
  297. /* The below allowed this invocation:
  298. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  299. * to be ^C-ed and get to interactive ash prompt.
  300. * bash does not support such "set -i".
  301. * In our code, this is denoted by empty long name:
  302. */
  303. "i" "",
  304. "m" "monitor",
  305. "n" "noexec",
  306. /* Ditto: bash has no "set -s" */
  307. "s" "",
  308. "c" "",
  309. "x" "xtrace",
  310. "v" "verbose",
  311. "C" "noclobber",
  312. "a" "allexport",
  313. "b" "notify",
  314. "u" "nounset",
  315. "\0" "vi"
  316. #if BASH_PIPEFAIL
  317. ,"\0" "pipefail"
  318. #endif
  319. #if DEBUG
  320. ,"\0" "nolog"
  321. ,"\0" "debug"
  322. #endif
  323. };
  324. //bash 4.4.23 also has these opts (with these defaults):
  325. //braceexpand on
  326. //emacs on
  327. //errtrace off
  328. //functrace off
  329. //hashall on
  330. //histexpand off
  331. //history on
  332. //interactive-comments on
  333. //keyword off
  334. //onecmd off
  335. //physical off
  336. //posix off
  337. //privileged off
  338. #define optletters(n) optletters_optnames[n][0]
  339. #define optnames(n) (optletters_optnames[n] + 1)
  340. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  341. /* ============ Misc data */
  342. #define msg_illnum "Illegal number: %s"
  343. /*
  344. * We enclose jmp_buf in a structure so that we can declare pointers to
  345. * jump locations. The global variable handler contains the location to
  346. * jump to when an exception occurs, and the global variable exception_type
  347. * contains a code identifying the exception. To implement nested
  348. * exception handlers, the user should save the value of handler on entry
  349. * to an inner scope, set handler to point to a jmploc structure for the
  350. * inner scope, and restore handler on exit from the scope.
  351. */
  352. struct jmploc {
  353. jmp_buf loc;
  354. };
  355. struct globals_misc {
  356. uint8_t exitstatus; /* exit status of last command */
  357. uint8_t back_exitstatus;/* exit status of backquoted command */
  358. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  359. int rootpid; /* pid of main shell */
  360. /* shell level: 0 for the main shell, 1 for its children, and so on */
  361. int shlvl;
  362. #define rootshell (!shlvl)
  363. int errlinno;
  364. char *minusc; /* argument to -c option */
  365. char *curdir; // = nullstr; /* current working directory */
  366. char *physdir; // = nullstr; /* physical working directory */
  367. char *arg0; /* value of $0 */
  368. struct jmploc *exception_handler;
  369. volatile int suppress_int; /* counter */
  370. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  371. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  372. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  373. smallint exception_type; /* kind of exception (0..5) */
  374. /* exceptions */
  375. #define EXINT 0 /* SIGINT received */
  376. #define EXERROR 1 /* a generic error */
  377. #define EXEXIT 4 /* exit the shell */
  378. char nullstr[1]; /* zero length string */
  379. char optlist[NOPTS];
  380. #define eflag optlist[0]
  381. #define fflag optlist[1]
  382. #define Iflag optlist[2]
  383. #define iflag optlist[3]
  384. #define mflag optlist[4]
  385. #define nflag optlist[5]
  386. #define sflag optlist[6]
  387. #define cflag optlist[7]
  388. #define xflag optlist[8]
  389. #define vflag optlist[9]
  390. #define Cflag optlist[10]
  391. #define aflag optlist[11]
  392. #define bflag optlist[12]
  393. #define uflag optlist[13]
  394. #define viflag optlist[14]
  395. #if BASH_PIPEFAIL
  396. # define pipefail optlist[15]
  397. #else
  398. # define pipefail 0
  399. #endif
  400. #if DEBUG
  401. # define nolog optlist[15 + BASH_PIPEFAIL]
  402. # define debug optlist[16 + BASH_PIPEFAIL]
  403. #endif
  404. /* trap handler commands */
  405. /*
  406. * Sigmode records the current value of the signal handlers for the various
  407. * modes. A value of zero means that the current handler is not known.
  408. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  409. */
  410. char sigmode[NSIG - 1];
  411. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  412. #define S_CATCH 2 /* signal is caught */
  413. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  414. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  415. /* indicates specified signal received */
  416. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  417. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  418. char *trap[NSIG];
  419. char **trap_ptr; /* used only by "trap hack" */
  420. /* Rarely referenced stuff */
  421. #if ENABLE_ASH_RANDOM_SUPPORT
  422. random_t random_gen;
  423. #endif
  424. pid_t backgndpid; /* pid of last background process */
  425. };
  426. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  427. #define G_misc (*ash_ptr_to_globals_misc)
  428. #define exitstatus (G_misc.exitstatus )
  429. #define back_exitstatus (G_misc.back_exitstatus )
  430. #define job_warning (G_misc.job_warning)
  431. #define rootpid (G_misc.rootpid )
  432. #define shlvl (G_misc.shlvl )
  433. #define errlinno (G_misc.errlinno )
  434. #define minusc (G_misc.minusc )
  435. #define curdir (G_misc.curdir )
  436. #define physdir (G_misc.physdir )
  437. #define arg0 (G_misc.arg0 )
  438. #define exception_handler (G_misc.exception_handler)
  439. #define exception_type (G_misc.exception_type )
  440. #define suppress_int (G_misc.suppress_int )
  441. #define pending_int (G_misc.pending_int )
  442. #define got_sigchld (G_misc.got_sigchld )
  443. #define pending_sig (G_misc.pending_sig )
  444. #define nullstr (G_misc.nullstr )
  445. #define optlist (G_misc.optlist )
  446. #define sigmode (G_misc.sigmode )
  447. #define gotsig (G_misc.gotsig )
  448. #define may_have_traps (G_misc.may_have_traps )
  449. #define trap (G_misc.trap )
  450. #define trap_ptr (G_misc.trap_ptr )
  451. #define random_gen (G_misc.random_gen )
  452. #define backgndpid (G_misc.backgndpid )
  453. #define INIT_G_misc() do { \
  454. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  455. barrier(); \
  456. curdir = nullstr; \
  457. physdir = nullstr; \
  458. trap_ptr = trap; \
  459. } while (0)
  460. /* ============ DEBUG */
  461. #if DEBUG
  462. static void trace_printf(const char *fmt, ...);
  463. static void trace_vprintf(const char *fmt, va_list va);
  464. # define TRACE(param) trace_printf param
  465. # define TRACEV(param) trace_vprintf param
  466. # define close(fd) do { \
  467. int dfd = (fd); \
  468. if (close(dfd) < 0) \
  469. bb_error_msg("bug on %d: closing %d(0x%x)", \
  470. __LINE__, dfd, dfd); \
  471. } while (0)
  472. #else
  473. # define TRACE(param)
  474. # define TRACEV(param)
  475. #endif
  476. /* ============ Utility functions */
  477. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  478. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  479. static int
  480. isdigit_str9(const char *str)
  481. {
  482. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  483. while (--maxlen && isdigit(*str))
  484. str++;
  485. return (*str == '\0');
  486. }
  487. static const char *
  488. var_end(const char *var)
  489. {
  490. while (*var)
  491. if (*var++ == '=')
  492. break;
  493. return var;
  494. }
  495. /* ============ Interrupts / exceptions */
  496. static void exitshell(void) NORETURN;
  497. /*
  498. * These macros allow the user to suspend the handling of interrupt signals
  499. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  500. * much more efficient and portable. (But hacking the kernel is so much
  501. * more fun than worrying about efficiency and portability. :-))
  502. */
  503. #if DEBUG_INTONOFF
  504. # define INT_OFF do { \
  505. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  506. suppress_int++; \
  507. barrier(); \
  508. } while (0)
  509. #else
  510. # define INT_OFF do { \
  511. suppress_int++; \
  512. barrier(); \
  513. } while (0)
  514. #endif
  515. /*
  516. * Called to raise an exception. Since C doesn't include exceptions, we
  517. * just do a longjmp to the exception handler. The type of exception is
  518. * stored in the global variable "exception_type".
  519. */
  520. static void raise_exception(int) NORETURN;
  521. static void
  522. raise_exception(int e)
  523. {
  524. #if DEBUG
  525. if (exception_handler == NULL)
  526. abort();
  527. #endif
  528. INT_OFF;
  529. exception_type = e;
  530. longjmp(exception_handler->loc, 1);
  531. }
  532. #if DEBUG
  533. #define raise_exception(e) do { \
  534. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  535. raise_exception(e); \
  536. } while (0)
  537. #endif
  538. /*
  539. * Called when a SIGINT is received. (If the user specifies
  540. * that SIGINT is to be trapped or ignored using the trap builtin, then
  541. * this routine is not called.) Suppressint is nonzero when interrupts
  542. * are held using the INT_OFF macro. (The test for iflag is just
  543. * defensive programming.)
  544. */
  545. static void raise_interrupt(void) NORETURN;
  546. static void
  547. raise_interrupt(void)
  548. {
  549. pending_int = 0;
  550. /* Signal is not automatically unmasked after it is raised,
  551. * do it ourself - unmask all signals */
  552. sigprocmask_allsigs(SIG_UNBLOCK);
  553. /* pending_sig = 0; - now done in signal_handler() */
  554. if (!(rootshell && iflag)) {
  555. /* Kill ourself with SIGINT */
  556. signal(SIGINT, SIG_DFL);
  557. raise(SIGINT);
  558. }
  559. /* bash: ^C even on empty command line sets $? */
  560. exitstatus = SIGINT + 128;
  561. raise_exception(EXINT);
  562. /* NOTREACHED */
  563. }
  564. #if DEBUG
  565. #define raise_interrupt() do { \
  566. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  567. raise_interrupt(); \
  568. } while (0)
  569. #endif
  570. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  571. int_on(void)
  572. {
  573. barrier();
  574. if (--suppress_int == 0 && pending_int) {
  575. raise_interrupt();
  576. }
  577. }
  578. #if DEBUG_INTONOFF
  579. # define INT_ON do { \
  580. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  581. int_on(); \
  582. } while (0)
  583. #else
  584. # define INT_ON int_on()
  585. #endif
  586. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  587. force_int_on(void)
  588. {
  589. barrier();
  590. suppress_int = 0;
  591. if (pending_int)
  592. raise_interrupt();
  593. }
  594. #define FORCE_INT_ON force_int_on()
  595. #define SAVE_INT(v) ((v) = suppress_int)
  596. #define RESTORE_INT(v) do { \
  597. barrier(); \
  598. suppress_int = (v); \
  599. if (suppress_int == 0 && pending_int) \
  600. raise_interrupt(); \
  601. } while (0)
  602. /* ============ Stdout/stderr output */
  603. static void
  604. outstr(const char *p, FILE *file)
  605. {
  606. INT_OFF;
  607. fputs(p, file);
  608. INT_ON;
  609. }
  610. static void
  611. flush_stdout_stderr(void)
  612. {
  613. INT_OFF;
  614. fflush_all();
  615. INT_ON;
  616. }
  617. /* Was called outcslow(c,FILE*), but c was always '\n' */
  618. static void
  619. newline_and_flush(FILE *dest)
  620. {
  621. INT_OFF;
  622. putc('\n', dest);
  623. fflush(dest);
  624. INT_ON;
  625. }
  626. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  627. static int
  628. out1fmt(const char *fmt, ...)
  629. {
  630. va_list ap;
  631. int r;
  632. INT_OFF;
  633. va_start(ap, fmt);
  634. r = vprintf(fmt, ap);
  635. va_end(ap);
  636. INT_ON;
  637. return r;
  638. }
  639. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  640. static int
  641. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  642. {
  643. va_list ap;
  644. int ret;
  645. INT_OFF;
  646. va_start(ap, fmt);
  647. ret = vsnprintf(outbuf, length, fmt, ap);
  648. va_end(ap);
  649. INT_ON;
  650. return ret;
  651. }
  652. static void
  653. out1str(const char *p)
  654. {
  655. outstr(p, stdout);
  656. }
  657. static void
  658. out2str(const char *p)
  659. {
  660. outstr(p, stderr);
  661. flush_stdout_stderr();
  662. }
  663. /* ============ Parser structures */
  664. /* control characters in argument strings */
  665. #define CTL_FIRST CTLESC
  666. #define CTLESC ((unsigned char)'\201') /* escape next character */
  667. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  668. #define CTLENDVAR ((unsigned char)'\203')
  669. #define CTLBACKQ ((unsigned char)'\204')
  670. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  671. #define CTLENDARI ((unsigned char)'\207')
  672. #define CTLQUOTEMARK ((unsigned char)'\210')
  673. #define CTL_LAST CTLQUOTEMARK
  674. /* variable substitution byte (follows CTLVAR) */
  675. #define VSTYPE 0x0f /* type of variable substitution */
  676. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  677. /* values of VSTYPE field */
  678. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  679. #define VSMINUS 0x2 /* ${var-text} */
  680. #define VSPLUS 0x3 /* ${var+text} */
  681. #define VSQUESTION 0x4 /* ${var?message} */
  682. #define VSASSIGN 0x5 /* ${var=text} */
  683. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  684. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  685. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  686. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  687. #define VSLENGTH 0xa /* ${#var} */
  688. #if BASH_SUBSTR
  689. #define VSSUBSTR 0xc /* ${var:position:length} */
  690. #endif
  691. #if BASH_PATTERN_SUBST
  692. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  693. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  694. #endif
  695. static const char dolatstr[] ALIGN1 = {
  696. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  697. };
  698. #define DOLATSTRLEN 6
  699. #define NCMD 0
  700. #define NPIPE 1
  701. #define NREDIR 2
  702. #define NBACKGND 3
  703. #define NSUBSHELL 4
  704. #define NAND 5
  705. #define NOR 6
  706. #define NSEMI 7
  707. #define NIF 8
  708. #define NWHILE 9
  709. #define NUNTIL 10
  710. #define NFOR 11
  711. #define NCASE 12
  712. #define NCLIST 13
  713. #define NDEFUN 14
  714. #define NARG 15
  715. #define NTO 16
  716. #if BASH_REDIR_OUTPUT
  717. #define NTO2 17
  718. #endif
  719. #define NCLOBBER 18
  720. #define NFROM 19
  721. #define NFROMTO 20
  722. #define NAPPEND 21
  723. #define NTOFD 22
  724. #define NFROMFD 23
  725. #define NHERE 24
  726. #define NXHERE 25
  727. #define NNOT 26
  728. #define N_NUMBER 27
  729. union node;
  730. struct ncmd {
  731. smallint type; /* Nxxxx */
  732. int linno;
  733. union node *assign;
  734. union node *args;
  735. union node *redirect;
  736. };
  737. struct npipe {
  738. smallint type;
  739. smallint pipe_backgnd;
  740. struct nodelist *cmdlist;
  741. };
  742. struct nredir {
  743. smallint type;
  744. int linno;
  745. union node *n;
  746. union node *redirect;
  747. };
  748. struct nbinary {
  749. smallint type;
  750. union node *ch1;
  751. union node *ch2;
  752. };
  753. struct nif {
  754. smallint type;
  755. union node *test;
  756. union node *ifpart;
  757. union node *elsepart;
  758. };
  759. struct nfor {
  760. smallint type;
  761. int linno;
  762. union node *args;
  763. union node *body;
  764. char *var;
  765. };
  766. struct ncase {
  767. smallint type;
  768. int linno;
  769. union node *expr;
  770. union node *cases;
  771. };
  772. struct nclist {
  773. smallint type;
  774. union node *next;
  775. union node *pattern;
  776. union node *body;
  777. };
  778. struct ndefun {
  779. smallint type;
  780. int linno;
  781. char *text;
  782. union node *body;
  783. };
  784. struct narg {
  785. smallint type;
  786. union node *next;
  787. char *text;
  788. struct nodelist *backquote;
  789. };
  790. /* nfile and ndup layout must match!
  791. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  792. * that it is actually NTO2 (>&file), and change its type.
  793. */
  794. struct nfile {
  795. smallint type;
  796. union node *next;
  797. int fd;
  798. int _unused_dupfd;
  799. union node *fname;
  800. char *expfname;
  801. };
  802. struct ndup {
  803. smallint type;
  804. union node *next;
  805. int fd;
  806. int dupfd;
  807. union node *vname;
  808. char *_unused_expfname;
  809. };
  810. struct nhere {
  811. smallint type;
  812. union node *next;
  813. int fd;
  814. union node *doc;
  815. };
  816. struct nnot {
  817. smallint type;
  818. union node *com;
  819. };
  820. union node {
  821. smallint type;
  822. struct ncmd ncmd;
  823. struct npipe npipe;
  824. struct nredir nredir;
  825. struct nbinary nbinary;
  826. struct nif nif;
  827. struct nfor nfor;
  828. struct ncase ncase;
  829. struct nclist nclist;
  830. struct ndefun ndefun;
  831. struct narg narg;
  832. struct nfile nfile;
  833. struct ndup ndup;
  834. struct nhere nhere;
  835. struct nnot nnot;
  836. };
  837. /*
  838. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  839. * It must be distinct from NULL.
  840. */
  841. #define NODE_EOF ((union node *) -1L)
  842. struct nodelist {
  843. struct nodelist *next;
  844. union node *n;
  845. };
  846. struct funcnode {
  847. int count;
  848. union node n;
  849. };
  850. /*
  851. * Free a parse tree.
  852. */
  853. static void
  854. freefunc(struct funcnode *f)
  855. {
  856. if (f && --f->count < 0)
  857. free(f);
  858. }
  859. /* ============ Debugging output */
  860. #if DEBUG
  861. static FILE *tracefile;
  862. static void
  863. trace_printf(const char *fmt, ...)
  864. {
  865. va_list va;
  866. if (debug != 1)
  867. return;
  868. if (DEBUG_TIME)
  869. fprintf(tracefile, "%u ", (int) time(NULL));
  870. if (DEBUG_PID)
  871. fprintf(tracefile, "[%u] ", (int) getpid());
  872. if (DEBUG_SIG)
  873. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  874. va_start(va, fmt);
  875. vfprintf(tracefile, fmt, va);
  876. va_end(va);
  877. }
  878. static void
  879. trace_vprintf(const char *fmt, va_list va)
  880. {
  881. if (debug != 1)
  882. return;
  883. vfprintf(tracefile, fmt, va);
  884. fprintf(tracefile, "\n");
  885. }
  886. static void
  887. trace_puts(const char *s)
  888. {
  889. if (debug != 1)
  890. return;
  891. fputs(s, tracefile);
  892. }
  893. static void
  894. trace_puts_quoted(char *s)
  895. {
  896. char *p;
  897. char c;
  898. if (debug != 1)
  899. return;
  900. putc('"', tracefile);
  901. for (p = s; *p; p++) {
  902. switch ((unsigned char)*p) {
  903. case '\n': c = 'n'; goto backslash;
  904. case '\t': c = 't'; goto backslash;
  905. case '\r': c = 'r'; goto backslash;
  906. case '\"': c = '\"'; goto backslash;
  907. case '\\': c = '\\'; goto backslash;
  908. case CTLESC: c = 'e'; goto backslash;
  909. case CTLVAR: c = 'v'; goto backslash;
  910. case CTLBACKQ: c = 'q'; goto backslash;
  911. backslash:
  912. putc('\\', tracefile);
  913. putc(c, tracefile);
  914. break;
  915. default:
  916. if (*p >= ' ' && *p <= '~')
  917. putc(*p, tracefile);
  918. else {
  919. putc('\\', tracefile);
  920. putc((*p >> 6) & 03, tracefile);
  921. putc((*p >> 3) & 07, tracefile);
  922. putc(*p & 07, tracefile);
  923. }
  924. break;
  925. }
  926. }
  927. putc('"', tracefile);
  928. }
  929. static void
  930. trace_puts_args(char **ap)
  931. {
  932. if (debug != 1)
  933. return;
  934. if (!*ap)
  935. return;
  936. while (1) {
  937. trace_puts_quoted(*ap);
  938. if (!*++ap) {
  939. putc('\n', tracefile);
  940. break;
  941. }
  942. putc(' ', tracefile);
  943. }
  944. }
  945. static void
  946. opentrace(void)
  947. {
  948. char s[100];
  949. #ifdef O_APPEND
  950. int flags;
  951. #endif
  952. if (debug != 1) {
  953. if (tracefile)
  954. fflush(tracefile);
  955. /* leave open because libedit might be using it */
  956. return;
  957. }
  958. strcpy(s, "./trace");
  959. if (tracefile) {
  960. if (!freopen(s, "a", tracefile)) {
  961. fprintf(stderr, "Can't re-open %s\n", s);
  962. debug = 0;
  963. return;
  964. }
  965. } else {
  966. tracefile = fopen(s, "a");
  967. if (tracefile == NULL) {
  968. fprintf(stderr, "Can't open %s\n", s);
  969. debug = 0;
  970. return;
  971. }
  972. }
  973. #ifdef O_APPEND
  974. flags = fcntl(fileno(tracefile), F_GETFL);
  975. if (flags >= 0)
  976. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  977. #endif
  978. setlinebuf(tracefile);
  979. fputs("\nTracing started.\n", tracefile);
  980. }
  981. static void
  982. indent(int amount, char *pfx, FILE *fp)
  983. {
  984. int i;
  985. for (i = 0; i < amount; i++) {
  986. if (pfx && i == amount - 1)
  987. fputs(pfx, fp);
  988. putc('\t', fp);
  989. }
  990. }
  991. /* little circular references here... */
  992. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  993. static void
  994. sharg(union node *arg, FILE *fp)
  995. {
  996. char *p;
  997. struct nodelist *bqlist;
  998. unsigned char subtype;
  999. if (arg->type != NARG) {
  1000. out1fmt("<node type %d>\n", arg->type);
  1001. abort();
  1002. }
  1003. bqlist = arg->narg.backquote;
  1004. for (p = arg->narg.text; *p; p++) {
  1005. switch ((unsigned char)*p) {
  1006. case CTLESC:
  1007. p++;
  1008. putc(*p, fp);
  1009. break;
  1010. case CTLVAR:
  1011. putc('$', fp);
  1012. putc('{', fp);
  1013. subtype = *++p;
  1014. if (subtype == VSLENGTH)
  1015. putc('#', fp);
  1016. while (*p != '=') {
  1017. putc(*p, fp);
  1018. p++;
  1019. }
  1020. if (subtype & VSNUL)
  1021. putc(':', fp);
  1022. switch (subtype & VSTYPE) {
  1023. case VSNORMAL:
  1024. putc('}', fp);
  1025. break;
  1026. case VSMINUS:
  1027. putc('-', fp);
  1028. break;
  1029. case VSPLUS:
  1030. putc('+', fp);
  1031. break;
  1032. case VSQUESTION:
  1033. putc('?', fp);
  1034. break;
  1035. case VSASSIGN:
  1036. putc('=', fp);
  1037. break;
  1038. case VSTRIMLEFT:
  1039. putc('#', fp);
  1040. break;
  1041. case VSTRIMLEFTMAX:
  1042. putc('#', fp);
  1043. putc('#', fp);
  1044. break;
  1045. case VSTRIMRIGHT:
  1046. putc('%', fp);
  1047. break;
  1048. case VSTRIMRIGHTMAX:
  1049. putc('%', fp);
  1050. putc('%', fp);
  1051. break;
  1052. case VSLENGTH:
  1053. break;
  1054. default:
  1055. out1fmt("<subtype %d>", subtype);
  1056. }
  1057. break;
  1058. case CTLENDVAR:
  1059. putc('}', fp);
  1060. break;
  1061. case CTLBACKQ:
  1062. putc('$', fp);
  1063. putc('(', fp);
  1064. shtree(bqlist->n, -1, NULL, fp);
  1065. putc(')', fp);
  1066. break;
  1067. default:
  1068. putc(*p, fp);
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. static void
  1074. shcmd(union node *cmd, FILE *fp)
  1075. {
  1076. union node *np;
  1077. int first;
  1078. const char *s;
  1079. int dftfd;
  1080. first = 1;
  1081. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1082. if (!first)
  1083. putc(' ', fp);
  1084. sharg(np, fp);
  1085. first = 0;
  1086. }
  1087. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1088. if (!first)
  1089. putc(' ', fp);
  1090. dftfd = 0;
  1091. switch (np->nfile.type) {
  1092. case NTO: s = ">>"+1; dftfd = 1; break;
  1093. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1094. case NAPPEND: s = ">>"; dftfd = 1; break;
  1095. #if BASH_REDIR_OUTPUT
  1096. case NTO2:
  1097. #endif
  1098. case NTOFD: s = ">&"; dftfd = 1; break;
  1099. case NFROM: s = "<"; break;
  1100. case NFROMFD: s = "<&"; break;
  1101. case NFROMTO: s = "<>"; break;
  1102. default: s = "*error*"; break;
  1103. }
  1104. if (np->nfile.fd != dftfd)
  1105. fprintf(fp, "%d", np->nfile.fd);
  1106. fputs(s, fp);
  1107. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1108. fprintf(fp, "%d", np->ndup.dupfd);
  1109. } else {
  1110. sharg(np->nfile.fname, fp);
  1111. }
  1112. first = 0;
  1113. }
  1114. }
  1115. static void
  1116. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1117. {
  1118. struct nodelist *lp;
  1119. const char *s;
  1120. if (n == NULL)
  1121. return;
  1122. indent(ind, pfx, fp);
  1123. if (n == NODE_EOF) {
  1124. fputs("<EOF>", fp);
  1125. return;
  1126. }
  1127. switch (n->type) {
  1128. case NSEMI:
  1129. s = "; ";
  1130. goto binop;
  1131. case NAND:
  1132. s = " && ";
  1133. goto binop;
  1134. case NOR:
  1135. s = " || ";
  1136. binop:
  1137. shtree(n->nbinary.ch1, ind, NULL, fp);
  1138. /* if (ind < 0) */
  1139. fputs(s, fp);
  1140. shtree(n->nbinary.ch2, ind, NULL, fp);
  1141. break;
  1142. case NCMD:
  1143. shcmd(n, fp);
  1144. if (ind >= 0)
  1145. putc('\n', fp);
  1146. break;
  1147. case NPIPE:
  1148. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1149. shtree(lp->n, 0, NULL, fp);
  1150. if (lp->next)
  1151. fputs(" | ", fp);
  1152. }
  1153. if (n->npipe.pipe_backgnd)
  1154. fputs(" &", fp);
  1155. if (ind >= 0)
  1156. putc('\n', fp);
  1157. break;
  1158. default:
  1159. fprintf(fp, "<node type %d>", n->type);
  1160. if (ind >= 0)
  1161. putc('\n', fp);
  1162. break;
  1163. }
  1164. }
  1165. static void
  1166. showtree(union node *n)
  1167. {
  1168. trace_puts("showtree called\n");
  1169. shtree(n, 1, NULL, stderr);
  1170. }
  1171. #endif /* DEBUG */
  1172. /* ============ Parser data */
  1173. /*
  1174. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1175. */
  1176. struct strlist {
  1177. struct strlist *next;
  1178. char *text;
  1179. };
  1180. struct alias;
  1181. struct strpush {
  1182. struct strpush *prev; /* preceding string on stack */
  1183. char *prev_string;
  1184. int prev_left_in_line;
  1185. #if ENABLE_ASH_ALIAS
  1186. struct alias *ap; /* if push was associated with an alias */
  1187. #endif
  1188. char *string; /* remember the string since it may change */
  1189. /* Remember last two characters for pungetc. */
  1190. int lastc[2];
  1191. /* Number of outstanding calls to pungetc. */
  1192. int unget;
  1193. };
  1194. /*
  1195. * The parsefile structure pointed to by the global variable parsefile
  1196. * contains information about the current file being read.
  1197. */
  1198. struct parsefile {
  1199. struct parsefile *prev; /* preceding file on stack */
  1200. int linno; /* current line */
  1201. int pf_fd; /* file descriptor (or -1 if string) */
  1202. int left_in_line; /* number of chars left in this line */
  1203. int left_in_buffer; /* number of chars left in this buffer past the line */
  1204. char *next_to_pgetc; /* next char in buffer */
  1205. char *buf; /* input buffer */
  1206. struct strpush *strpush; /* for pushing strings at this level */
  1207. struct strpush basestrpush; /* so pushing one is fast */
  1208. /* Remember last two characters for pungetc. */
  1209. int lastc[2];
  1210. /* Number of outstanding calls to pungetc. */
  1211. int unget;
  1212. };
  1213. static struct parsefile basepf; /* top level input file */
  1214. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1215. static char *commandname; /* currently executing command */
  1216. /* ============ Message printing */
  1217. static void
  1218. ash_vmsg(const char *msg, va_list ap)
  1219. {
  1220. fprintf(stderr, "%s: ", arg0);
  1221. if (commandname) {
  1222. if (strcmp(arg0, commandname))
  1223. fprintf(stderr, "%s: ", commandname);
  1224. if (!iflag || g_parsefile->pf_fd > 0)
  1225. fprintf(stderr, "line %d: ", errlinno);
  1226. }
  1227. vfprintf(stderr, msg, ap);
  1228. newline_and_flush(stderr);
  1229. }
  1230. /*
  1231. * Exverror is called to raise the error exception. If the second argument
  1232. * is not NULL then error prints an error message using printf style
  1233. * formatting. It then raises the error exception.
  1234. */
  1235. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1236. static void
  1237. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1238. {
  1239. #if DEBUG
  1240. if (msg) {
  1241. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1242. TRACEV((msg, ap));
  1243. } else
  1244. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1245. if (msg)
  1246. #endif
  1247. ash_vmsg(msg, ap);
  1248. flush_stdout_stderr();
  1249. raise_exception(cond);
  1250. /* NOTREACHED */
  1251. }
  1252. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1253. static void
  1254. ash_msg_and_raise_error(const char *msg, ...)
  1255. {
  1256. va_list ap;
  1257. exitstatus = 2;
  1258. va_start(ap, msg);
  1259. ash_vmsg_and_raise(EXERROR, msg, ap);
  1260. /* NOTREACHED */
  1261. va_end(ap);
  1262. }
  1263. /*
  1264. * 'fmt' must be a string literal.
  1265. */
  1266. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1267. static void raise_error_syntax(const char *) NORETURN;
  1268. static void
  1269. raise_error_syntax(const char *msg)
  1270. {
  1271. errlinno = g_parsefile->linno;
  1272. ash_msg_and_raise_error("syntax error: %s", msg);
  1273. /* NOTREACHED */
  1274. }
  1275. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1276. static void
  1277. ash_msg_and_raise(int cond, const char *msg, ...)
  1278. {
  1279. va_list ap;
  1280. va_start(ap, msg);
  1281. ash_vmsg_and_raise(cond, msg, ap);
  1282. /* NOTREACHED */
  1283. va_end(ap);
  1284. }
  1285. /*
  1286. * error/warning routines for external builtins
  1287. */
  1288. static void
  1289. ash_msg(const char *fmt, ...)
  1290. {
  1291. va_list ap;
  1292. va_start(ap, fmt);
  1293. ash_vmsg(fmt, ap);
  1294. va_end(ap);
  1295. }
  1296. /*
  1297. * Return a string describing an error. The returned string may be a
  1298. * pointer to a static buffer that will be overwritten on the next call.
  1299. * Action describes the operation that got the error.
  1300. */
  1301. static const char *
  1302. errmsg(int e, const char *em)
  1303. {
  1304. if (e == ENOENT || e == ENOTDIR) {
  1305. return em;
  1306. }
  1307. return strerror(e);
  1308. }
  1309. /* ============ Memory allocation */
  1310. #if 0
  1311. /* I consider these wrappers nearly useless:
  1312. * ok, they return you to nearest exception handler, but
  1313. * how much memory do you leak in the process, making
  1314. * memory starvation worse?
  1315. */
  1316. static void *
  1317. ckrealloc(void * p, size_t nbytes)
  1318. {
  1319. p = realloc(p, nbytes);
  1320. if (!p)
  1321. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1322. return p;
  1323. }
  1324. static void *
  1325. ckmalloc(size_t nbytes)
  1326. {
  1327. return ckrealloc(NULL, nbytes);
  1328. }
  1329. static void *
  1330. ckzalloc(size_t nbytes)
  1331. {
  1332. return memset(ckmalloc(nbytes), 0, nbytes);
  1333. }
  1334. static char *
  1335. ckstrdup(const char *s)
  1336. {
  1337. char *p = strdup(s);
  1338. if (!p)
  1339. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1340. return p;
  1341. }
  1342. #else
  1343. /* Using bbox equivalents. They exit if out of memory */
  1344. # define ckrealloc xrealloc
  1345. # define ckmalloc xmalloc
  1346. # define ckzalloc xzalloc
  1347. # define ckstrdup xstrdup
  1348. #endif
  1349. /*
  1350. * It appears that grabstackstr() will barf with such alignments
  1351. * because stalloc() will return a string allocated in a new stackblock.
  1352. */
  1353. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1354. enum {
  1355. /* Most machines require the value returned from malloc to be aligned
  1356. * in some way. The following macro will get this right
  1357. * on many machines. */
  1358. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1359. /* Minimum size of a block */
  1360. MINSIZE = SHELL_ALIGN(504),
  1361. };
  1362. struct stack_block {
  1363. struct stack_block *prev;
  1364. char space[MINSIZE];
  1365. };
  1366. struct stackmark {
  1367. struct stack_block *stackp;
  1368. char *stacknxt;
  1369. size_t stacknleft;
  1370. };
  1371. struct globals_memstack {
  1372. struct stack_block *g_stackp; // = &stackbase;
  1373. char *g_stacknxt; // = stackbase.space;
  1374. char *sstrend; // = stackbase.space + MINSIZE;
  1375. size_t g_stacknleft; // = MINSIZE;
  1376. struct stack_block stackbase;
  1377. };
  1378. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1379. #define G_memstack (*ash_ptr_to_globals_memstack)
  1380. #define g_stackp (G_memstack.g_stackp )
  1381. #define g_stacknxt (G_memstack.g_stacknxt )
  1382. #define sstrend (G_memstack.sstrend )
  1383. #define g_stacknleft (G_memstack.g_stacknleft)
  1384. #define stackbase (G_memstack.stackbase )
  1385. #define INIT_G_memstack() do { \
  1386. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1387. barrier(); \
  1388. g_stackp = &stackbase; \
  1389. g_stacknxt = stackbase.space; \
  1390. g_stacknleft = MINSIZE; \
  1391. sstrend = stackbase.space + MINSIZE; \
  1392. } while (0)
  1393. #define stackblock() ((void *)g_stacknxt)
  1394. #define stackblocksize() g_stacknleft
  1395. /*
  1396. * Parse trees for commands are allocated in lifo order, so we use a stack
  1397. * to make this more efficient, and also to avoid all sorts of exception
  1398. * handling code to handle interrupts in the middle of a parse.
  1399. *
  1400. * The size 504 was chosen because the Ultrix malloc handles that size
  1401. * well.
  1402. */
  1403. static void *
  1404. stalloc(size_t nbytes)
  1405. {
  1406. char *p;
  1407. size_t aligned;
  1408. aligned = SHELL_ALIGN(nbytes);
  1409. if (aligned > g_stacknleft) {
  1410. size_t len;
  1411. size_t blocksize;
  1412. struct stack_block *sp;
  1413. blocksize = aligned;
  1414. if (blocksize < MINSIZE)
  1415. blocksize = MINSIZE;
  1416. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1417. if (len < blocksize)
  1418. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1419. INT_OFF;
  1420. sp = ckmalloc(len);
  1421. sp->prev = g_stackp;
  1422. g_stacknxt = sp->space;
  1423. g_stacknleft = blocksize;
  1424. sstrend = g_stacknxt + blocksize;
  1425. g_stackp = sp;
  1426. INT_ON;
  1427. }
  1428. p = g_stacknxt;
  1429. g_stacknxt += aligned;
  1430. g_stacknleft -= aligned;
  1431. return p;
  1432. }
  1433. static void *
  1434. stzalloc(size_t nbytes)
  1435. {
  1436. return memset(stalloc(nbytes), 0, nbytes);
  1437. }
  1438. static void
  1439. stunalloc(void *p)
  1440. {
  1441. #if DEBUG
  1442. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1443. write(STDERR_FILENO, "stunalloc\n", 10);
  1444. abort();
  1445. }
  1446. #endif
  1447. g_stacknleft += g_stacknxt - (char *)p;
  1448. g_stacknxt = p;
  1449. }
  1450. /*
  1451. * Like strdup but works with the ash stack.
  1452. */
  1453. static char *
  1454. sstrdup(const char *p)
  1455. {
  1456. size_t len = strlen(p) + 1;
  1457. return memcpy(stalloc(len), p, len);
  1458. }
  1459. static ALWAYS_INLINE void
  1460. grabstackblock(size_t len)
  1461. {
  1462. stalloc(len);
  1463. }
  1464. static void
  1465. pushstackmark(struct stackmark *mark, size_t len)
  1466. {
  1467. mark->stackp = g_stackp;
  1468. mark->stacknxt = g_stacknxt;
  1469. mark->stacknleft = g_stacknleft;
  1470. grabstackblock(len);
  1471. }
  1472. static void
  1473. setstackmark(struct stackmark *mark)
  1474. {
  1475. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1476. }
  1477. static void
  1478. popstackmark(struct stackmark *mark)
  1479. {
  1480. struct stack_block *sp;
  1481. if (!mark->stackp)
  1482. return;
  1483. INT_OFF;
  1484. while (g_stackp != mark->stackp) {
  1485. sp = g_stackp;
  1486. g_stackp = sp->prev;
  1487. free(sp);
  1488. }
  1489. g_stacknxt = mark->stacknxt;
  1490. g_stacknleft = mark->stacknleft;
  1491. sstrend = mark->stacknxt + mark->stacknleft;
  1492. INT_ON;
  1493. }
  1494. /*
  1495. * When the parser reads in a string, it wants to stick the string on the
  1496. * stack and only adjust the stack pointer when it knows how big the
  1497. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1498. * of space on top of the stack and stackblocklen returns the length of
  1499. * this block. Growstackblock will grow this space by at least one byte,
  1500. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1501. * part of the block that has been used.
  1502. */
  1503. static void
  1504. growstackblock(void)
  1505. {
  1506. size_t newlen;
  1507. newlen = g_stacknleft * 2;
  1508. if (newlen < g_stacknleft)
  1509. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1510. if (newlen < 128)
  1511. newlen += 128;
  1512. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1513. struct stack_block *sp;
  1514. struct stack_block *prevstackp;
  1515. size_t grosslen;
  1516. INT_OFF;
  1517. sp = g_stackp;
  1518. prevstackp = sp->prev;
  1519. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1520. sp = ckrealloc(sp, grosslen);
  1521. sp->prev = prevstackp;
  1522. g_stackp = sp;
  1523. g_stacknxt = sp->space;
  1524. g_stacknleft = newlen;
  1525. sstrend = sp->space + newlen;
  1526. INT_ON;
  1527. } else {
  1528. char *oldspace = g_stacknxt;
  1529. size_t oldlen = g_stacknleft;
  1530. char *p = stalloc(newlen);
  1531. /* free the space we just allocated */
  1532. g_stacknxt = memcpy(p, oldspace, oldlen);
  1533. g_stacknleft += newlen;
  1534. }
  1535. }
  1536. /*
  1537. * The following routines are somewhat easier to use than the above.
  1538. * The user declares a variable of type STACKSTR, which may be declared
  1539. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1540. * the user uses the macro STPUTC to add characters to the string. In
  1541. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1542. * grown as necessary. When the user is done, she can just leave the
  1543. * string there and refer to it using stackblock(). Or she can allocate
  1544. * the space for it using grabstackstr(). If it is necessary to allow
  1545. * someone else to use the stack temporarily and then continue to grow
  1546. * the string, the user should use grabstack to allocate the space, and
  1547. * then call ungrabstr(p) to return to the previous mode of operation.
  1548. *
  1549. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1550. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1551. * is space for at least one character.
  1552. */
  1553. static void *
  1554. growstackstr(void)
  1555. {
  1556. size_t len = stackblocksize();
  1557. growstackblock();
  1558. return (char *)stackblock() + len;
  1559. }
  1560. /*
  1561. * Called from CHECKSTRSPACE.
  1562. */
  1563. static char *
  1564. makestrspace(size_t newlen, char *p)
  1565. {
  1566. size_t len = p - g_stacknxt;
  1567. size_t size;
  1568. for (;;) {
  1569. size_t nleft;
  1570. size = stackblocksize();
  1571. nleft = size - len;
  1572. if (nleft >= newlen)
  1573. break;
  1574. growstackblock();
  1575. }
  1576. return (char *)stackblock() + len;
  1577. }
  1578. static char *
  1579. stack_nputstr(const char *s, size_t n, char *p)
  1580. {
  1581. p = makestrspace(n, p);
  1582. p = (char *)mempcpy(p, s, n);
  1583. return p;
  1584. }
  1585. static char *
  1586. stack_putstr(const char *s, char *p)
  1587. {
  1588. return stack_nputstr(s, strlen(s), p);
  1589. }
  1590. static char *
  1591. _STPUTC(int c, char *p)
  1592. {
  1593. if (p == sstrend)
  1594. p = growstackstr();
  1595. *p++ = c;
  1596. return p;
  1597. }
  1598. #define STARTSTACKSTR(p) ((p) = stackblock())
  1599. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1600. #define CHECKSTRSPACE(n, p) do { \
  1601. char *q = (p); \
  1602. size_t l = (n); \
  1603. size_t m = sstrend - q; \
  1604. if (l > m) \
  1605. (p) = makestrspace(l, q); \
  1606. } while (0)
  1607. #define USTPUTC(c, p) (*(p)++ = (c))
  1608. #define STACKSTRNUL(p) do { \
  1609. if ((p) == sstrend) \
  1610. (p) = growstackstr(); \
  1611. *(p) = '\0'; \
  1612. } while (0)
  1613. #define STUNPUTC(p) (--(p))
  1614. #define STTOPC(p) ((p)[-1])
  1615. #define STADJUST(amount, p) ((p) += (amount))
  1616. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1617. #define ungrabstackstr(s, p) stunalloc(s)
  1618. #define stackstrend() ((void *)sstrend)
  1619. /* ============ String helpers */
  1620. /*
  1621. * prefix -- see if pfx is a prefix of string.
  1622. */
  1623. static char *
  1624. prefix(const char *string, const char *pfx)
  1625. {
  1626. while (*pfx) {
  1627. if (*pfx++ != *string++)
  1628. return NULL;
  1629. }
  1630. return (char *) string;
  1631. }
  1632. /*
  1633. * Check for a valid number. This should be elsewhere.
  1634. */
  1635. static int
  1636. is_number(const char *p)
  1637. {
  1638. do {
  1639. if (!isdigit(*p))
  1640. return 0;
  1641. } while (*++p != '\0');
  1642. return 1;
  1643. }
  1644. /*
  1645. * Convert a string of digits to an integer, printing an error message on
  1646. * failure.
  1647. */
  1648. static int
  1649. number(const char *s)
  1650. {
  1651. if (!is_number(s))
  1652. ash_msg_and_raise_error(msg_illnum, s);
  1653. return atoi(s);
  1654. }
  1655. /*
  1656. * Produce a single quoted string suitable as input to the shell.
  1657. * The return string is allocated on the stack.
  1658. */
  1659. static char *
  1660. single_quote(const char *s)
  1661. {
  1662. char *p;
  1663. STARTSTACKSTR(p);
  1664. do {
  1665. char *q;
  1666. size_t len;
  1667. len = strchrnul(s, '\'') - s;
  1668. q = p = makestrspace(len + 3, p);
  1669. *q++ = '\'';
  1670. q = (char *)mempcpy(q, s, len);
  1671. *q++ = '\'';
  1672. s += len;
  1673. STADJUST(q - p, p);
  1674. if (*s != '\'')
  1675. break;
  1676. len = 0;
  1677. do len++; while (*++s == '\'');
  1678. q = p = makestrspace(len + 3, p);
  1679. *q++ = '"';
  1680. q = (char *)mempcpy(q, s - len, len);
  1681. *q++ = '"';
  1682. STADJUST(q - p, p);
  1683. } while (*s);
  1684. USTPUTC('\0', p);
  1685. return stackblock();
  1686. }
  1687. /*
  1688. * Produce a possibly single quoted string suitable as input to the shell.
  1689. * If quoting was done, the return string is allocated on the stack,
  1690. * otherwise a pointer to the original string is returned.
  1691. */
  1692. static const char *
  1693. maybe_single_quote(const char *s)
  1694. {
  1695. const char *p = s;
  1696. while (*p) {
  1697. /* Assuming ACSII */
  1698. /* quote ctrl_chars space !"#$%&'()* */
  1699. if (*p < '+')
  1700. goto need_quoting;
  1701. /* quote ;<=>? */
  1702. if (*p >= ';' && *p <= '?')
  1703. goto need_quoting;
  1704. /* quote `[\ */
  1705. if (*p == '`')
  1706. goto need_quoting;
  1707. if (*p == '[')
  1708. goto need_quoting;
  1709. if (*p == '\\')
  1710. goto need_quoting;
  1711. /* quote {|}~ DEL and high bytes */
  1712. if (*p > 'z')
  1713. goto need_quoting;
  1714. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1715. /* TODO: maybe avoid quoting % */
  1716. p++;
  1717. }
  1718. return s;
  1719. need_quoting:
  1720. return single_quote(s);
  1721. }
  1722. /* ============ nextopt */
  1723. static char **argptr; /* argument list for builtin commands */
  1724. static char *optionarg; /* set by nextopt (like getopt) */
  1725. static char *optptr; /* used by nextopt */
  1726. /*
  1727. * XXX - should get rid of. Have all builtins use getopt(3).
  1728. * The library getopt must have the BSD extension static variable
  1729. * "optreset", otherwise it can't be used within the shell safely.
  1730. *
  1731. * Standard option processing (a la getopt) for builtin routines.
  1732. * The only argument that is passed to nextopt is the option string;
  1733. * the other arguments are unnecessary. It returns the character,
  1734. * or '\0' on end of input.
  1735. */
  1736. static int
  1737. nextopt(const char *optstring)
  1738. {
  1739. char *p;
  1740. const char *q;
  1741. char c;
  1742. p = optptr;
  1743. if (p == NULL || *p == '\0') {
  1744. /* We ate entire "-param", take next one */
  1745. p = *argptr;
  1746. if (p == NULL)
  1747. return '\0';
  1748. if (*p != '-')
  1749. return '\0';
  1750. if (*++p == '\0') /* just "-" ? */
  1751. return '\0';
  1752. argptr++;
  1753. if (LONE_DASH(p)) /* "--" ? */
  1754. return '\0';
  1755. /* p => next "-param" */
  1756. }
  1757. /* p => some option char in the middle of a "-param" */
  1758. c = *p++;
  1759. for (q = optstring; *q != c;) {
  1760. if (*q == '\0')
  1761. ash_msg_and_raise_error("illegal option -%c", c);
  1762. if (*++q == ':')
  1763. q++;
  1764. }
  1765. if (*++q == ':') {
  1766. if (*p == '\0') {
  1767. p = *argptr++;
  1768. if (p == NULL)
  1769. ash_msg_and_raise_error("no arg for -%c option", c);
  1770. }
  1771. optionarg = p;
  1772. p = NULL;
  1773. }
  1774. optptr = p;
  1775. return c;
  1776. }
  1777. /* ============ Shell variables */
  1778. struct shparam {
  1779. int nparam; /* # of positional parameters (without $0) */
  1780. #if ENABLE_ASH_GETOPTS
  1781. int optind; /* next parameter to be processed by getopts */
  1782. int optoff; /* used by getopts */
  1783. #endif
  1784. unsigned char malloced; /* if parameter list dynamically allocated */
  1785. char **p; /* parameter list */
  1786. };
  1787. /*
  1788. * Free the list of positional parameters.
  1789. */
  1790. static void
  1791. freeparam(volatile struct shparam *param)
  1792. {
  1793. if (param->malloced) {
  1794. char **ap, **ap1;
  1795. ap = ap1 = param->p;
  1796. while (*ap)
  1797. free(*ap++);
  1798. free(ap1);
  1799. }
  1800. }
  1801. #if ENABLE_ASH_GETOPTS
  1802. static void FAST_FUNC getoptsreset(const char *value);
  1803. #endif
  1804. struct var {
  1805. struct var *next; /* next entry in hash list */
  1806. int flags; /* flags are defined above */
  1807. const char *var_text; /* name=value */
  1808. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1809. /* the variable gets set/unset */
  1810. };
  1811. struct localvar {
  1812. struct localvar *next; /* next local variable in list */
  1813. struct var *vp; /* the variable that was made local */
  1814. int flags; /* saved flags */
  1815. const char *text; /* saved text */
  1816. };
  1817. /* flags */
  1818. #define VEXPORT 0x01 /* variable is exported */
  1819. #define VREADONLY 0x02 /* variable cannot be modified */
  1820. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1821. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1822. #define VSTACK 0x10 /* text is allocated on the stack */
  1823. #define VUNSET 0x20 /* the variable is not set */
  1824. #define VNOFUNC 0x40 /* don't call the callback function */
  1825. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1826. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1827. #if ENABLE_ASH_RANDOM_SUPPORT
  1828. # define VDYNAMIC 0x200 /* dynamic variable */
  1829. #else
  1830. # define VDYNAMIC 0
  1831. #endif
  1832. /* Need to be before varinit_data[] */
  1833. #if ENABLE_LOCALE_SUPPORT
  1834. static void FAST_FUNC
  1835. change_lc_all(const char *value)
  1836. {
  1837. if (value && *value != '\0')
  1838. setlocale(LC_ALL, value);
  1839. }
  1840. static void FAST_FUNC
  1841. change_lc_ctype(const char *value)
  1842. {
  1843. if (value && *value != '\0')
  1844. setlocale(LC_CTYPE, value);
  1845. }
  1846. #endif
  1847. #if ENABLE_ASH_MAIL
  1848. static void chkmail(void);
  1849. static void changemail(const char *var_value) FAST_FUNC;
  1850. #else
  1851. # define chkmail() ((void)0)
  1852. #endif
  1853. static void changepath(const char *) FAST_FUNC;
  1854. #if ENABLE_ASH_RANDOM_SUPPORT
  1855. static void change_random(const char *) FAST_FUNC;
  1856. #endif
  1857. #if BASH_EPOCH_VARS
  1858. static void change_seconds(const char *) FAST_FUNC;
  1859. static void change_realtime(const char *) FAST_FUNC;
  1860. #endif
  1861. static const struct {
  1862. int flags;
  1863. const char *var_text;
  1864. void (*var_func)(const char *) FAST_FUNC;
  1865. } varinit_data[] = {
  1866. /*
  1867. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1868. * some environment strings may be constant.
  1869. */
  1870. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1871. #if ENABLE_ASH_MAIL
  1872. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1873. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1874. #endif
  1875. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1876. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1877. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1878. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1879. #if ENABLE_ASH_GETOPTS
  1880. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1881. #endif
  1882. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1883. #if ENABLE_ASH_RANDOM_SUPPORT
  1884. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1885. #endif
  1886. #if BASH_EPOCH_VARS
  1887. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1888. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1889. #endif
  1890. #if ENABLE_LOCALE_SUPPORT
  1891. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1892. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1893. #endif
  1894. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1895. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1896. #endif
  1897. };
  1898. struct redirtab;
  1899. struct globals_var {
  1900. struct shparam shellparam; /* $@ current positional parameters */
  1901. struct redirtab *redirlist;
  1902. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1903. struct var *vartab[VTABSIZE];
  1904. struct var varinit[ARRAY_SIZE(varinit_data)];
  1905. int lineno;
  1906. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1907. };
  1908. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1909. #define G_var (*ash_ptr_to_globals_var)
  1910. #define shellparam (G_var.shellparam )
  1911. //#define redirlist (G_var.redirlist )
  1912. #define preverrout_fd (G_var.preverrout_fd)
  1913. #define vartab (G_var.vartab )
  1914. #define varinit (G_var.varinit )
  1915. #define lineno (G_var.lineno )
  1916. #define linenovar (G_var.linenovar )
  1917. #define vifs varinit[0]
  1918. #if ENABLE_ASH_MAIL
  1919. # define vmail varinit[1]
  1920. # define vmpath varinit[2]
  1921. #endif
  1922. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1923. #define vpath varinit[VAR_OFFSET1 + 1]
  1924. #define vps1 varinit[VAR_OFFSET1 + 2]
  1925. #define vps2 varinit[VAR_OFFSET1 + 3]
  1926. #define vps4 varinit[VAR_OFFSET1 + 4]
  1927. #if ENABLE_ASH_GETOPTS
  1928. # define voptind varinit[VAR_OFFSET1 + 5]
  1929. #endif
  1930. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1931. #define vlineno varinit[VAR_OFFSET2 + 5]
  1932. #if ENABLE_ASH_RANDOM_SUPPORT
  1933. # define vrandom varinit[VAR_OFFSET2 + 6]
  1934. #endif
  1935. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1936. #if BASH_EPOCH_VARS
  1937. # define vepochs varinit[VAR_OFFSET3 + 6]
  1938. # define vepochr varinit[VAR_OFFSET3 + 7]
  1939. #endif
  1940. #define INIT_G_var() do { \
  1941. unsigned i; \
  1942. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1943. barrier(); \
  1944. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1945. varinit[i].flags = varinit_data[i].flags; \
  1946. varinit[i].var_text = varinit_data[i].var_text; \
  1947. varinit[i].var_func = varinit_data[i].var_func; \
  1948. } \
  1949. strcpy(linenovar, "LINENO="); \
  1950. vlineno.var_text = linenovar; \
  1951. } while (0)
  1952. /*
  1953. * The following macros access the values of the above variables.
  1954. * They have to skip over the name. They return the null string
  1955. * for unset variables.
  1956. */
  1957. #define ifsval() (vifs.var_text + 4)
  1958. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1959. #if ENABLE_ASH_MAIL
  1960. # define mailval() (vmail.var_text + 5)
  1961. # define mpathval() (vmpath.var_text + 9)
  1962. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1963. #endif
  1964. #define pathval() (vpath.var_text + 5)
  1965. #define ps1val() (vps1.var_text + 4)
  1966. #define ps2val() (vps2.var_text + 4)
  1967. #define ps4val() (vps4.var_text + 4)
  1968. #if ENABLE_ASH_GETOPTS
  1969. # define optindval() (voptind.var_text + 7)
  1970. #endif
  1971. #if ENABLE_ASH_GETOPTS
  1972. static void FAST_FUNC
  1973. getoptsreset(const char *value)
  1974. {
  1975. shellparam.optind = 1;
  1976. if (is_number(value))
  1977. shellparam.optind = number(value) ?: 1;
  1978. shellparam.optoff = -1;
  1979. }
  1980. #endif
  1981. /*
  1982. * Compares two strings up to the first = or '\0'. The first
  1983. * string must be terminated by '='; the second may be terminated by
  1984. * either '=' or '\0'.
  1985. */
  1986. static int
  1987. varcmp(const char *p, const char *q)
  1988. {
  1989. int c, d;
  1990. while ((c = *p) == (d = *q)) {
  1991. if (c == '\0' || c == '=')
  1992. goto out;
  1993. p++;
  1994. q++;
  1995. }
  1996. if (c == '=')
  1997. c = '\0';
  1998. if (d == '=')
  1999. d = '\0';
  2000. out:
  2001. return c - d;
  2002. }
  2003. /*
  2004. * Find the appropriate entry in the hash table from the name.
  2005. */
  2006. static struct var **
  2007. hashvar(const char *p)
  2008. {
  2009. unsigned hashval;
  2010. hashval = ((unsigned char) *p) << 4;
  2011. while (*p && *p != '=')
  2012. hashval += (unsigned char) *p++;
  2013. return &vartab[hashval % VTABSIZE];
  2014. }
  2015. static int
  2016. vpcmp(const void *a, const void *b)
  2017. {
  2018. return varcmp(*(const char **)a, *(const char **)b);
  2019. }
  2020. /*
  2021. * This routine initializes the builtin variables.
  2022. */
  2023. static void
  2024. initvar(void)
  2025. {
  2026. struct var *vp;
  2027. struct var *end;
  2028. struct var **vpp;
  2029. /*
  2030. * PS1 depends on uid
  2031. */
  2032. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2033. vps1.var_text = "PS1=\\w \\$ ";
  2034. #else
  2035. if (!geteuid())
  2036. vps1.var_text = "PS1=# ";
  2037. #endif
  2038. vp = varinit;
  2039. end = vp + ARRAY_SIZE(varinit);
  2040. do {
  2041. vpp = hashvar(vp->var_text);
  2042. vp->next = *vpp;
  2043. *vpp = vp;
  2044. } while (++vp < end);
  2045. }
  2046. static struct var **
  2047. findvar(struct var **vpp, const char *name)
  2048. {
  2049. for (; *vpp; vpp = &(*vpp)->next) {
  2050. if (varcmp((*vpp)->var_text, name) == 0) {
  2051. break;
  2052. }
  2053. }
  2054. return vpp;
  2055. }
  2056. /*
  2057. * Find the value of a variable. Returns NULL if not set.
  2058. */
  2059. static const char* FAST_FUNC
  2060. lookupvar(const char *name)
  2061. {
  2062. struct var *v;
  2063. v = *findvar(hashvar(name), name);
  2064. if (v) {
  2065. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2066. /*
  2067. * Dynamic variables are implemented roughly the same way they are
  2068. * in bash. Namely, they're "special" so long as they aren't unset.
  2069. * As soon as they're unset, they're no longer dynamic, and dynamic
  2070. * lookup will no longer happen at that point. -- PFM.
  2071. */
  2072. if (v->flags & VDYNAMIC)
  2073. v->var_func(NULL);
  2074. #endif
  2075. if (!(v->flags & VUNSET)) {
  2076. if (v == &vlineno && v->var_text == linenovar) {
  2077. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2078. }
  2079. return var_end(v->var_text);
  2080. }
  2081. }
  2082. return NULL;
  2083. }
  2084. #if ENABLE_UNICODE_SUPPORT
  2085. static void
  2086. reinit_unicode_for_ash(void)
  2087. {
  2088. /* Unicode support should be activated even if LANG is set
  2089. * _during_ shell execution, not only if it was set when
  2090. * shell was started. Therefore, re-check LANG every time:
  2091. */
  2092. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2093. || ENABLE_UNICODE_USING_LOCALE
  2094. ) {
  2095. const char *s = lookupvar("LC_ALL");
  2096. if (!s) s = lookupvar("LC_CTYPE");
  2097. if (!s) s = lookupvar("LANG");
  2098. reinit_unicode(s);
  2099. }
  2100. }
  2101. #else
  2102. # define reinit_unicode_for_ash() ((void)0)
  2103. #endif
  2104. /*
  2105. * Search the environment of a builtin command.
  2106. */
  2107. static ALWAYS_INLINE const char *
  2108. bltinlookup(const char *name)
  2109. {
  2110. return lookupvar(name);
  2111. }
  2112. /*
  2113. * Same as setvar except that the variable and value are passed in
  2114. * the first argument as name=value. Since the first argument will
  2115. * be actually stored in the table, it should not be a string that
  2116. * will go away.
  2117. * Called with interrupts off.
  2118. */
  2119. static struct var *
  2120. setvareq(char *s, int flags)
  2121. {
  2122. struct var *vp, **vpp;
  2123. vpp = hashvar(s);
  2124. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2125. vpp = findvar(vpp, s);
  2126. vp = *vpp;
  2127. if (vp) {
  2128. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2129. const char *n;
  2130. if (flags & VNOSAVE)
  2131. free(s);
  2132. n = vp->var_text;
  2133. exitstatus = 1;
  2134. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2135. }
  2136. if (flags & VNOSET)
  2137. goto out;
  2138. if (vp->var_func && !(flags & VNOFUNC))
  2139. vp->var_func(var_end(s));
  2140. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2141. free((char*)vp->var_text);
  2142. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2143. *vpp = vp->next;
  2144. free(vp);
  2145. out_free:
  2146. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2147. free(s);
  2148. goto out;
  2149. }
  2150. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2151. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2152. if (flags & VUNSET)
  2153. flags &= ~VDYNAMIC;
  2154. #endif
  2155. } else {
  2156. /* variable s is not found */
  2157. if (flags & VNOSET)
  2158. goto out;
  2159. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2160. goto out_free;
  2161. vp = ckzalloc(sizeof(*vp));
  2162. vp->next = *vpp;
  2163. /*vp->func = NULL; - ckzalloc did it */
  2164. *vpp = vp;
  2165. }
  2166. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2167. s = ckstrdup(s);
  2168. vp->var_text = s;
  2169. vp->flags = flags;
  2170. out:
  2171. return vp;
  2172. }
  2173. /*
  2174. * Set the value of a variable. The flags argument is ored with the
  2175. * flags of the variable. If val is NULL, the variable is unset.
  2176. */
  2177. static struct var *
  2178. setvar(const char *name, const char *val, int flags)
  2179. {
  2180. const char *q;
  2181. char *p;
  2182. char *nameeq;
  2183. size_t namelen;
  2184. size_t vallen;
  2185. struct var *vp;
  2186. q = endofname(name);
  2187. p = strchrnul(q, '=');
  2188. namelen = p - name;
  2189. if (!namelen || p != q)
  2190. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2191. vallen = 0;
  2192. if (val == NULL) {
  2193. flags |= VUNSET;
  2194. } else {
  2195. vallen = strlen(val);
  2196. }
  2197. INT_OFF;
  2198. nameeq = ckzalloc(namelen + vallen + 2);
  2199. p = mempcpy(nameeq, name, namelen);
  2200. if (val) {
  2201. *p++ = '=';
  2202. memcpy(p, val, vallen);
  2203. }
  2204. vp = setvareq(nameeq, flags | VNOSAVE);
  2205. INT_ON;
  2206. return vp;
  2207. }
  2208. static void FAST_FUNC
  2209. setvar0(const char *name, const char *val)
  2210. {
  2211. setvar(name, val, 0);
  2212. }
  2213. /*
  2214. * Unset the specified variable.
  2215. */
  2216. static void
  2217. unsetvar(const char *s)
  2218. {
  2219. setvar(s, NULL, 0);
  2220. }
  2221. /*
  2222. * Process a linked list of variable assignments.
  2223. */
  2224. static void
  2225. listsetvar(struct strlist *list_set_var, int flags)
  2226. {
  2227. struct strlist *lp = list_set_var;
  2228. if (!lp)
  2229. return;
  2230. INT_OFF;
  2231. do {
  2232. setvareq(lp->text, flags);
  2233. lp = lp->next;
  2234. } while (lp);
  2235. INT_ON;
  2236. }
  2237. /*
  2238. * Generate a list of variables satisfying the given conditions.
  2239. */
  2240. #if !ENABLE_FEATURE_SH_NOFORK
  2241. # define listvars(on, off, lp, end) listvars(on, off, end)
  2242. #endif
  2243. static char **
  2244. listvars(int on, int off, struct strlist *lp, char ***end)
  2245. {
  2246. struct var **vpp;
  2247. struct var *vp;
  2248. char **ep;
  2249. int mask;
  2250. STARTSTACKSTR(ep);
  2251. vpp = vartab;
  2252. mask = on | off;
  2253. do {
  2254. for (vp = *vpp; vp; vp = vp->next) {
  2255. if ((vp->flags & mask) == on) {
  2256. #if ENABLE_FEATURE_SH_NOFORK
  2257. /* If variable with the same name is both
  2258. * exported and temporarily set for a command:
  2259. * export ZVAR=5
  2260. * ZVAR=6 printenv
  2261. * then "ZVAR=6" will be both in vartab and
  2262. * lp lists. Do not pass it twice to printenv.
  2263. */
  2264. struct strlist *lp1 = lp;
  2265. while (lp1) {
  2266. if (strcmp(lp1->text, vp->var_text) == 0)
  2267. goto skip;
  2268. lp1 = lp1->next;
  2269. }
  2270. #endif
  2271. if (ep == stackstrend())
  2272. ep = growstackstr();
  2273. *ep++ = (char*)vp->var_text;
  2274. #if ENABLE_FEATURE_SH_NOFORK
  2275. skip: ;
  2276. #endif
  2277. }
  2278. }
  2279. } while (++vpp < vartab + VTABSIZE);
  2280. #if ENABLE_FEATURE_SH_NOFORK
  2281. while (lp) {
  2282. if (ep == stackstrend())
  2283. ep = growstackstr();
  2284. *ep++ = lp->text;
  2285. lp = lp->next;
  2286. }
  2287. #endif
  2288. if (ep == stackstrend())
  2289. ep = growstackstr();
  2290. if (end)
  2291. *end = ep;
  2292. *ep++ = NULL;
  2293. return grabstackstr(ep);
  2294. }
  2295. /* ============ Path search helper
  2296. *
  2297. * The variable path (passed by reference) should be set to the start
  2298. * of the path before the first call; path_advance will update
  2299. * this value as it proceeds. Successive calls to path_advance will return
  2300. * the possible path expansions in sequence. If an option (indicated by
  2301. * a percent sign) appears in the path entry then the global variable
  2302. * pathopt will be set to point to it; otherwise pathopt will be set to
  2303. * NULL.
  2304. */
  2305. static const char *pathopt; /* set by path_advance */
  2306. static char *
  2307. path_advance(const char **path, const char *name)
  2308. {
  2309. const char *p;
  2310. char *q;
  2311. const char *start;
  2312. size_t len;
  2313. if (*path == NULL)
  2314. return NULL;
  2315. start = *path;
  2316. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2317. continue;
  2318. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2319. while (stackblocksize() < len)
  2320. growstackblock();
  2321. q = stackblock();
  2322. if (p != start) {
  2323. q = mempcpy(q, start, p - start);
  2324. *q++ = '/';
  2325. }
  2326. strcpy(q, name);
  2327. pathopt = NULL;
  2328. if (*p == '%') {
  2329. pathopt = ++p;
  2330. while (*p && *p != ':')
  2331. p++;
  2332. }
  2333. if (*p == ':')
  2334. *path = p + 1;
  2335. else
  2336. *path = NULL;
  2337. return stalloc(len);
  2338. }
  2339. /* ============ Prompt */
  2340. static smallint doprompt; /* if set, prompt the user */
  2341. static smallint needprompt; /* true if interactive and at start of line */
  2342. #if ENABLE_FEATURE_EDITING
  2343. static line_input_t *line_input_state;
  2344. static const char *cmdedit_prompt;
  2345. static void
  2346. putprompt(const char *s)
  2347. {
  2348. if (ENABLE_ASH_EXPAND_PRMT) {
  2349. free((char*)cmdedit_prompt);
  2350. cmdedit_prompt = ckstrdup(s);
  2351. return;
  2352. }
  2353. cmdedit_prompt = s;
  2354. }
  2355. #else
  2356. static void
  2357. putprompt(const char *s)
  2358. {
  2359. out2str(s);
  2360. }
  2361. #endif
  2362. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2363. static const char *expandstr(const char *ps, int syntax_type);
  2364. /* Values for syntax param */
  2365. #define BASESYNTAX 0 /* not in quotes */
  2366. #define DQSYNTAX 1 /* in double quotes */
  2367. #define SQSYNTAX 2 /* in single quotes */
  2368. #define ARISYNTAX 3 /* in arithmetic */
  2369. #if ENABLE_ASH_EXPAND_PRMT
  2370. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2371. #endif
  2372. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2373. /*
  2374. * called by editline -- any expansions to the prompt should be added here.
  2375. */
  2376. static void
  2377. setprompt_if(smallint do_set, int whichprompt)
  2378. {
  2379. const char *prompt;
  2380. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2381. if (!do_set)
  2382. return;
  2383. needprompt = 0;
  2384. switch (whichprompt) {
  2385. case 1:
  2386. prompt = ps1val();
  2387. break;
  2388. case 2:
  2389. prompt = ps2val();
  2390. break;
  2391. default: /* 0 */
  2392. prompt = nullstr;
  2393. }
  2394. #if ENABLE_ASH_EXPAND_PRMT
  2395. pushstackmark(&smark, stackblocksize());
  2396. putprompt(expandstr(prompt, PSSYNTAX));
  2397. popstackmark(&smark);
  2398. #else
  2399. putprompt(prompt);
  2400. #endif
  2401. }
  2402. /* ============ The cd and pwd commands */
  2403. #define CD_PHYSICAL 1
  2404. #define CD_PRINT 2
  2405. static int
  2406. cdopt(void)
  2407. {
  2408. int flags = 0;
  2409. int i, j;
  2410. j = 'L';
  2411. while ((i = nextopt("LP")) != '\0') {
  2412. if (i != j) {
  2413. flags ^= CD_PHYSICAL;
  2414. j = i;
  2415. }
  2416. }
  2417. return flags;
  2418. }
  2419. /*
  2420. * Update curdir (the name of the current directory) in response to a
  2421. * cd command.
  2422. */
  2423. static const char *
  2424. updatepwd(const char *dir)
  2425. {
  2426. char *new;
  2427. char *p;
  2428. char *cdcomppath;
  2429. const char *lim;
  2430. cdcomppath = sstrdup(dir);
  2431. STARTSTACKSTR(new);
  2432. if (*dir != '/') {
  2433. if (curdir == nullstr)
  2434. return 0;
  2435. new = stack_putstr(curdir, new);
  2436. }
  2437. new = makestrspace(strlen(dir) + 2, new);
  2438. lim = (char *)stackblock() + 1;
  2439. if (*dir != '/') {
  2440. if (new[-1] != '/')
  2441. USTPUTC('/', new);
  2442. if (new > lim && *lim == '/')
  2443. lim++;
  2444. } else {
  2445. USTPUTC('/', new);
  2446. cdcomppath++;
  2447. if (dir[1] == '/' && dir[2] != '/') {
  2448. USTPUTC('/', new);
  2449. cdcomppath++;
  2450. lim++;
  2451. }
  2452. }
  2453. p = strtok(cdcomppath, "/");
  2454. while (p) {
  2455. switch (*p) {
  2456. case '.':
  2457. if (p[1] == '.' && p[2] == '\0') {
  2458. while (new > lim) {
  2459. STUNPUTC(new);
  2460. if (new[-1] == '/')
  2461. break;
  2462. }
  2463. break;
  2464. }
  2465. if (p[1] == '\0')
  2466. break;
  2467. /* fall through */
  2468. default:
  2469. new = stack_putstr(p, new);
  2470. USTPUTC('/', new);
  2471. }
  2472. p = strtok(NULL, "/");
  2473. }
  2474. if (new > lim)
  2475. STUNPUTC(new);
  2476. *new = 0;
  2477. return stackblock();
  2478. }
  2479. /*
  2480. * Find out what the current directory is. If we already know the current
  2481. * directory, this routine returns immediately.
  2482. */
  2483. static char *
  2484. getpwd(void)
  2485. {
  2486. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2487. return dir ? dir : nullstr;
  2488. }
  2489. static void
  2490. setpwd(const char *val, int setold)
  2491. {
  2492. char *oldcur, *dir;
  2493. oldcur = dir = curdir;
  2494. if (setold) {
  2495. setvar("OLDPWD", oldcur, VEXPORT);
  2496. }
  2497. INT_OFF;
  2498. if (physdir != nullstr) {
  2499. if (physdir != oldcur)
  2500. free(physdir);
  2501. physdir = nullstr;
  2502. }
  2503. if (oldcur == val || !val) {
  2504. char *s = getpwd();
  2505. physdir = s;
  2506. if (!val)
  2507. dir = s;
  2508. } else
  2509. dir = ckstrdup(val);
  2510. if (oldcur != dir && oldcur != nullstr) {
  2511. free(oldcur);
  2512. }
  2513. curdir = dir;
  2514. INT_ON;
  2515. setvar("PWD", dir, VEXPORT);
  2516. }
  2517. static void hashcd(void);
  2518. /*
  2519. * Actually do the chdir. We also call hashcd to let other routines
  2520. * know that the current directory has changed.
  2521. */
  2522. static int
  2523. docd(const char *dest, int flags)
  2524. {
  2525. const char *dir = NULL;
  2526. int err;
  2527. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2528. INT_OFF;
  2529. if (!(flags & CD_PHYSICAL)) {
  2530. dir = updatepwd(dest);
  2531. if (dir)
  2532. dest = dir;
  2533. }
  2534. err = chdir(dest);
  2535. if (err)
  2536. goto out;
  2537. setpwd(dir, 1);
  2538. hashcd();
  2539. out:
  2540. INT_ON;
  2541. return err;
  2542. }
  2543. static int FAST_FUNC
  2544. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2545. {
  2546. const char *dest;
  2547. const char *path;
  2548. const char *p;
  2549. char c;
  2550. struct stat statb;
  2551. int flags;
  2552. flags = cdopt();
  2553. dest = *argptr;
  2554. if (!dest)
  2555. dest = bltinlookup("HOME");
  2556. else if (LONE_DASH(dest)) {
  2557. dest = bltinlookup("OLDPWD");
  2558. flags |= CD_PRINT;
  2559. }
  2560. if (!dest)
  2561. dest = nullstr;
  2562. if (*dest == '/')
  2563. goto step6;
  2564. if (*dest == '.') {
  2565. c = dest[1];
  2566. dotdot:
  2567. switch (c) {
  2568. case '\0':
  2569. case '/':
  2570. goto step6;
  2571. case '.':
  2572. c = dest[2];
  2573. if (c != '.')
  2574. goto dotdot;
  2575. }
  2576. }
  2577. if (!*dest)
  2578. dest = ".";
  2579. path = bltinlookup("CDPATH");
  2580. while (path) {
  2581. c = *path;
  2582. p = path_advance(&path, dest);
  2583. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2584. if (c && c != ':')
  2585. flags |= CD_PRINT;
  2586. docd:
  2587. if (!docd(p, flags))
  2588. goto out;
  2589. goto err;
  2590. }
  2591. }
  2592. step6:
  2593. p = dest;
  2594. goto docd;
  2595. err:
  2596. ash_msg_and_raise_perror("can't cd to %s", dest);
  2597. /* NOTREACHED */
  2598. out:
  2599. if (flags & CD_PRINT)
  2600. out1fmt("%s\n", curdir);
  2601. return 0;
  2602. }
  2603. static int FAST_FUNC
  2604. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2605. {
  2606. int flags;
  2607. const char *dir = curdir;
  2608. flags = cdopt();
  2609. if (flags) {
  2610. if (physdir == nullstr)
  2611. setpwd(dir, 0);
  2612. dir = physdir;
  2613. }
  2614. out1fmt("%s\n", dir);
  2615. return 0;
  2616. }
  2617. /* ============ ... */
  2618. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2619. /* Syntax classes */
  2620. #define CWORD 0 /* character is nothing special */
  2621. #define CNL 1 /* newline character */
  2622. #define CBACK 2 /* a backslash character */
  2623. #define CSQUOTE 3 /* single quote */
  2624. #define CDQUOTE 4 /* double quote */
  2625. #define CENDQUOTE 5 /* a terminating quote */
  2626. #define CBQUOTE 6 /* backwards single quote */
  2627. #define CVAR 7 /* a dollar sign */
  2628. #define CENDVAR 8 /* a '}' character */
  2629. #define CLP 9 /* a left paren in arithmetic */
  2630. #define CRP 10 /* a right paren in arithmetic */
  2631. #define CENDFILE 11 /* end of file */
  2632. #define CCTL 12 /* like CWORD, except it must be escaped */
  2633. #define CSPCL 13 /* these terminate a word */
  2634. #define CIGN 14 /* character should be ignored */
  2635. #define PEOF 256
  2636. #if ENABLE_ASH_ALIAS
  2637. # define PEOA 257
  2638. #endif
  2639. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2640. #if ENABLE_FEATURE_SH_MATH
  2641. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2642. #else
  2643. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2644. #endif
  2645. static const uint16_t S_I_T[] ALIGN2 = {
  2646. #if ENABLE_ASH_ALIAS
  2647. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2648. #endif
  2649. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2650. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2651. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2652. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2653. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2654. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2655. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2656. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2657. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2658. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2659. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2660. #if !USE_SIT_FUNCTION
  2661. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2662. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2663. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2664. #endif
  2665. #undef SIT_ITEM
  2666. };
  2667. /* Constants below must match table above */
  2668. enum {
  2669. #if ENABLE_ASH_ALIAS
  2670. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2671. #endif
  2672. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2673. CNL_CNL_CNL_CNL , /* 2 */
  2674. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2675. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2676. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2677. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2678. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2679. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2680. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2681. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2682. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2683. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2684. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2685. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2686. };
  2687. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2688. * caller must ensure proper cast on it if c is *char_ptr!
  2689. */
  2690. #if USE_SIT_FUNCTION
  2691. static int
  2692. SIT(int c, int syntax)
  2693. {
  2694. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2695. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2696. /*
  2697. * This causes '/' to be prepended with CTLESC in dquoted string,
  2698. * making "./file"* treated incorrectly because we feed
  2699. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2700. * The "homegrown" glob implementation is okay with that,
  2701. * but glibc one isn't. With '/' always treated as CWORD,
  2702. * both work fine.
  2703. */
  2704. # if ENABLE_ASH_ALIAS
  2705. static const uint8_t syntax_index_table[] ALIGN1 = {
  2706. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2707. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2708. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2709. 11, 3 /* "}~" */
  2710. };
  2711. # else
  2712. static const uint8_t syntax_index_table[] ALIGN1 = {
  2713. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2714. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2715. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2716. 10, 2 /* "}~" */
  2717. };
  2718. # endif
  2719. const char *s;
  2720. int indx;
  2721. if (c == PEOF)
  2722. return CENDFILE;
  2723. # if ENABLE_ASH_ALIAS
  2724. if (c == PEOA)
  2725. indx = 0;
  2726. else
  2727. # endif
  2728. {
  2729. /* Cast is purely for paranoia here,
  2730. * just in case someone passed signed char to us */
  2731. if ((unsigned char)c >= CTL_FIRST
  2732. && (unsigned char)c <= CTL_LAST
  2733. ) {
  2734. return CCTL;
  2735. }
  2736. s = strchrnul(spec_symbls, c);
  2737. if (*s == '\0')
  2738. return CWORD;
  2739. indx = syntax_index_table[s - spec_symbls];
  2740. }
  2741. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2742. }
  2743. #else /* !USE_SIT_FUNCTION */
  2744. static const uint8_t syntax_index_table[] ALIGN1 = {
  2745. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2746. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2756. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2757. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2764. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2767. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2768. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2779. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2780. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2781. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2783. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2785. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2786. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2787. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2788. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2789. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2792. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2793. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2794. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2806. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2807. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2808. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2809. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2810. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2811. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2839. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2840. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2841. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2844. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2872. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2873. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2874. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2877. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2878. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2879. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2880. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2881. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2882. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2883. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2884. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2894. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2895. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2896. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2899. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2900. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2901. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2902. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2903. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2904. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2905. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2906. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3004. # if ENABLE_ASH_ALIAS
  3005. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3006. # endif
  3007. };
  3008. #if 1
  3009. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3010. #else /* debug version, caught one signed char bug */
  3011. # define SIT(c, syntax) \
  3012. ({ \
  3013. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3014. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3015. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3016. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3017. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3018. })
  3019. #endif
  3020. #endif /* !USE_SIT_FUNCTION */
  3021. /* ============ Alias handling */
  3022. #if ENABLE_ASH_ALIAS
  3023. #define ALIASINUSE 1
  3024. #define ALIASDEAD 2
  3025. struct alias {
  3026. struct alias *next;
  3027. char *name;
  3028. char *val;
  3029. int flag;
  3030. };
  3031. static struct alias **atab; // [ATABSIZE];
  3032. #define INIT_G_alias() do { \
  3033. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3034. } while (0)
  3035. static struct alias **
  3036. __lookupalias(const char *name)
  3037. {
  3038. unsigned int hashval;
  3039. struct alias **app;
  3040. const char *p;
  3041. unsigned int ch;
  3042. p = name;
  3043. ch = (unsigned char)*p;
  3044. hashval = ch << 4;
  3045. while (ch) {
  3046. hashval += ch;
  3047. ch = (unsigned char)*++p;
  3048. }
  3049. app = &atab[hashval % ATABSIZE];
  3050. for (; *app; app = &(*app)->next) {
  3051. if (strcmp(name, (*app)->name) == 0) {
  3052. break;
  3053. }
  3054. }
  3055. return app;
  3056. }
  3057. static struct alias *
  3058. lookupalias(const char *name, int check)
  3059. {
  3060. struct alias *ap = *__lookupalias(name);
  3061. if (check && ap && (ap->flag & ALIASINUSE))
  3062. return NULL;
  3063. return ap;
  3064. }
  3065. static struct alias *
  3066. freealias(struct alias *ap)
  3067. {
  3068. struct alias *next;
  3069. if (ap->flag & ALIASINUSE) {
  3070. ap->flag |= ALIASDEAD;
  3071. return ap;
  3072. }
  3073. next = ap->next;
  3074. free(ap->name);
  3075. free(ap->val);
  3076. free(ap);
  3077. return next;
  3078. }
  3079. static void
  3080. setalias(const char *name, const char *val)
  3081. {
  3082. struct alias *ap, **app;
  3083. app = __lookupalias(name);
  3084. ap = *app;
  3085. INT_OFF;
  3086. if (ap) {
  3087. if (!(ap->flag & ALIASINUSE)) {
  3088. free(ap->val);
  3089. }
  3090. ap->val = ckstrdup(val);
  3091. ap->flag &= ~ALIASDEAD;
  3092. } else {
  3093. /* not found */
  3094. ap = ckzalloc(sizeof(struct alias));
  3095. ap->name = ckstrdup(name);
  3096. ap->val = ckstrdup(val);
  3097. /*ap->flag = 0; - ckzalloc did it */
  3098. /*ap->next = NULL;*/
  3099. *app = ap;
  3100. }
  3101. INT_ON;
  3102. }
  3103. static int
  3104. unalias(const char *name)
  3105. {
  3106. struct alias **app;
  3107. app = __lookupalias(name);
  3108. if (*app) {
  3109. INT_OFF;
  3110. *app = freealias(*app);
  3111. INT_ON;
  3112. return 0;
  3113. }
  3114. return 1;
  3115. }
  3116. static void
  3117. rmaliases(void)
  3118. {
  3119. struct alias *ap, **app;
  3120. int i;
  3121. INT_OFF;
  3122. for (i = 0; i < ATABSIZE; i++) {
  3123. app = &atab[i];
  3124. for (ap = *app; ap; ap = *app) {
  3125. *app = freealias(*app);
  3126. if (ap == *app) {
  3127. app = &ap->next;
  3128. }
  3129. }
  3130. }
  3131. INT_ON;
  3132. }
  3133. static void
  3134. printalias(const struct alias *ap)
  3135. {
  3136. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3137. }
  3138. /*
  3139. * TODO - sort output
  3140. */
  3141. static int FAST_FUNC
  3142. aliascmd(int argc UNUSED_PARAM, char **argv)
  3143. {
  3144. char *n, *v;
  3145. int ret = 0;
  3146. struct alias *ap;
  3147. if (!argv[1]) {
  3148. int i;
  3149. for (i = 0; i < ATABSIZE; i++) {
  3150. for (ap = atab[i]; ap; ap = ap->next) {
  3151. printalias(ap);
  3152. }
  3153. }
  3154. return 0;
  3155. }
  3156. while ((n = *++argv) != NULL) {
  3157. v = strchr(n+1, '=');
  3158. if (v == NULL) { /* n+1: funny ksh stuff */
  3159. ap = *__lookupalias(n);
  3160. if (ap == NULL) {
  3161. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3162. ret = 1;
  3163. } else
  3164. printalias(ap);
  3165. } else {
  3166. *v++ = '\0';
  3167. setalias(n, v);
  3168. }
  3169. }
  3170. return ret;
  3171. }
  3172. static int FAST_FUNC
  3173. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3174. {
  3175. int i;
  3176. while (nextopt("a") != '\0') {
  3177. rmaliases();
  3178. return 0;
  3179. }
  3180. for (i = 0; *argptr; argptr++) {
  3181. if (unalias(*argptr)) {
  3182. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3183. i = 1;
  3184. }
  3185. }
  3186. return i;
  3187. }
  3188. #endif /* ASH_ALIAS */
  3189. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3190. #define FORK_FG 0
  3191. #define FORK_BG 1
  3192. #define FORK_NOJOB 2
  3193. /* mode flags for showjob(s) */
  3194. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3195. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3196. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3197. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3198. /*
  3199. * A job structure contains information about a job. A job is either a
  3200. * single process or a set of processes contained in a pipeline. In the
  3201. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3202. * array of pids.
  3203. */
  3204. struct procstat {
  3205. pid_t ps_pid; /* process id */
  3206. int ps_status; /* last process status from wait() */
  3207. char *ps_cmd; /* text of command being run */
  3208. };
  3209. struct job {
  3210. struct procstat ps0; /* status of process */
  3211. struct procstat *ps; /* status of processes when more than one */
  3212. #if JOBS
  3213. int stopstatus; /* status of a stopped job */
  3214. #endif
  3215. unsigned nprocs; /* number of processes */
  3216. #define JOBRUNNING 0 /* at least one proc running */
  3217. #define JOBSTOPPED 1 /* all procs are stopped */
  3218. #define JOBDONE 2 /* all procs are completed */
  3219. unsigned
  3220. state: 8,
  3221. #if JOBS
  3222. sigint: 1, /* job was killed by SIGINT */
  3223. jobctl: 1, /* job running under job control */
  3224. #endif
  3225. waited: 1, /* true if this entry has been waited for */
  3226. used: 1, /* true if this entry is in used */
  3227. changed: 1; /* true if status has changed */
  3228. struct job *prev_job; /* previous job */
  3229. };
  3230. static struct job *makejob(/*union node *,*/ int);
  3231. static int forkshell(struct job *, union node *, int);
  3232. static int waitforjob(struct job *);
  3233. #if !JOBS
  3234. enum { doing_jobctl = 0 };
  3235. #define setjobctl(on) do {} while (0)
  3236. #else
  3237. static smallint doing_jobctl; //references:8
  3238. static void setjobctl(int);
  3239. #endif
  3240. /*
  3241. * Ignore a signal.
  3242. */
  3243. static void
  3244. ignoresig(int signo)
  3245. {
  3246. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3247. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3248. /* No, need to do it */
  3249. signal(signo, SIG_IGN);
  3250. }
  3251. sigmode[signo - 1] = S_HARD_IGN;
  3252. }
  3253. /*
  3254. * Only one usage site - in setsignal()
  3255. */
  3256. static void
  3257. signal_handler(int signo)
  3258. {
  3259. if (signo == SIGCHLD) {
  3260. got_sigchld = 1;
  3261. if (!trap[SIGCHLD])
  3262. return;
  3263. }
  3264. gotsig[signo - 1] = 1;
  3265. pending_sig = signo;
  3266. if (signo == SIGINT && !trap[SIGINT]) {
  3267. if (!suppress_int) {
  3268. pending_sig = 0;
  3269. raise_interrupt(); /* does not return */
  3270. }
  3271. pending_int = 1;
  3272. }
  3273. }
  3274. /*
  3275. * Set the signal handler for the specified signal. The routine figures
  3276. * out what it should be set to.
  3277. */
  3278. static void
  3279. setsignal(int signo)
  3280. {
  3281. char *t;
  3282. char cur_act, new_act;
  3283. struct sigaction act;
  3284. t = trap[signo];
  3285. new_act = S_DFL;
  3286. if (t != NULL) { /* trap for this sig is set */
  3287. new_act = S_CATCH;
  3288. if (t[0] == '\0') /* trap is "": ignore this sig */
  3289. new_act = S_IGN;
  3290. }
  3291. if (rootshell && new_act == S_DFL) {
  3292. switch (signo) {
  3293. case SIGINT:
  3294. if (iflag || minusc || sflag == 0)
  3295. new_act = S_CATCH;
  3296. break;
  3297. case SIGQUIT:
  3298. #if DEBUG
  3299. if (debug)
  3300. break;
  3301. #endif
  3302. /* man bash:
  3303. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3304. * commands run by bash have signal handlers
  3305. * set to the values inherited by the shell
  3306. * from its parent". */
  3307. new_act = S_IGN;
  3308. break;
  3309. case SIGTERM:
  3310. if (iflag)
  3311. new_act = S_IGN;
  3312. break;
  3313. #if JOBS
  3314. case SIGTSTP:
  3315. case SIGTTOU:
  3316. if (mflag)
  3317. new_act = S_IGN;
  3318. break;
  3319. #endif
  3320. }
  3321. }
  3322. /* if !rootshell, we reset SIGQUIT to DFL,
  3323. * whereas we have to restore it to what shell got on entry.
  3324. * This is handled by the fact that if signal was IGNored on entry,
  3325. * then cur_act is S_HARD_IGN and we never change its sigaction
  3326. * (see code below).
  3327. */
  3328. if (signo == SIGCHLD)
  3329. new_act = S_CATCH;
  3330. t = &sigmode[signo - 1];
  3331. cur_act = *t;
  3332. if (cur_act == 0) {
  3333. /* current setting is not yet known */
  3334. if (sigaction(signo, NULL, &act)) {
  3335. /* pretend it worked; maybe we should give a warning,
  3336. * but other shells don't. We don't alter sigmode,
  3337. * so we retry every time.
  3338. * btw, in Linux it never fails. --vda */
  3339. return;
  3340. }
  3341. if (act.sa_handler == SIG_IGN) {
  3342. cur_act = S_HARD_IGN;
  3343. if (mflag
  3344. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3345. ) {
  3346. cur_act = S_IGN; /* don't hard ignore these */
  3347. }
  3348. }
  3349. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3350. /* installing SIG_DFL over SIG_DFL is a no-op */
  3351. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3352. *t = S_DFL;
  3353. return;
  3354. }
  3355. }
  3356. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3357. return;
  3358. *t = new_act;
  3359. act.sa_handler = SIG_DFL;
  3360. switch (new_act) {
  3361. case S_CATCH:
  3362. act.sa_handler = signal_handler;
  3363. break;
  3364. case S_IGN:
  3365. act.sa_handler = SIG_IGN;
  3366. break;
  3367. }
  3368. /* flags and mask matter only if !DFL and !IGN, but we do it
  3369. * for all cases for more deterministic behavior:
  3370. */
  3371. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3372. sigfillset(&act.sa_mask);
  3373. sigaction_set(signo, &act);
  3374. }
  3375. /* mode flags for set_curjob */
  3376. #define CUR_DELETE 2
  3377. #define CUR_RUNNING 1
  3378. #define CUR_STOPPED 0
  3379. #if JOBS
  3380. /* pgrp of shell on invocation */
  3381. static int initialpgrp; //references:2
  3382. static int ttyfd = -1; //5
  3383. #endif
  3384. /* array of jobs */
  3385. static struct job *jobtab; //5
  3386. /* size of array */
  3387. static unsigned njobs; //4
  3388. /* current job */
  3389. static struct job *curjob; //lots
  3390. /* number of presumed living untracked jobs */
  3391. static int jobless; //4
  3392. #if 0
  3393. /* Bash has a feature: it restores termios after a successful wait for
  3394. * a foreground job which had at least one stopped or sigkilled member.
  3395. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3396. * properly restoring tty state. Should we do this too?
  3397. * A reproducer: ^Z an interactive python:
  3398. *
  3399. * # python
  3400. * Python 2.7.12 (...)
  3401. * >>> ^Z
  3402. * { python leaves tty in -icanon -echo state. We do survive that... }
  3403. * [1]+ Stopped python
  3404. * { ...however, next program (python #2) does not survive it well: }
  3405. * # python
  3406. * Python 2.7.12 (...)
  3407. * >>> Traceback (most recent call last):
  3408. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3409. * File "<stdin>", line 1, in <module>
  3410. * NameError: name 'qwerty' is not defined
  3411. *
  3412. * The implementation below is modeled on bash code and seems to work.
  3413. * However, I'm not sure we should do this. For one: what if I'd fg
  3414. * the stopped python instead? It'll be confused by "restored" tty state.
  3415. */
  3416. static struct termios shell_tty_info;
  3417. static void
  3418. get_tty_state(void)
  3419. {
  3420. if (rootshell && ttyfd >= 0)
  3421. tcgetattr(ttyfd, &shell_tty_info);
  3422. }
  3423. static void
  3424. set_tty_state(void)
  3425. {
  3426. /* if (rootshell) - caller ensures this */
  3427. if (ttyfd >= 0)
  3428. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3429. }
  3430. static int
  3431. job_signal_status(struct job *jp)
  3432. {
  3433. int status;
  3434. unsigned i;
  3435. struct procstat *ps = jp->ps;
  3436. for (i = 0; i < jp->nprocs; i++) {
  3437. status = ps[i].ps_status;
  3438. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3439. return status;
  3440. }
  3441. return 0;
  3442. }
  3443. static void
  3444. restore_tty_if_stopped_or_signaled(struct job *jp)
  3445. {
  3446. //TODO: check what happens if we come from waitforjob() in expbackq()
  3447. if (rootshell) {
  3448. int s = job_signal_status(jp);
  3449. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3450. set_tty_state();
  3451. }
  3452. }
  3453. #else
  3454. # define get_tty_state() ((void)0)
  3455. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3456. #endif
  3457. static void
  3458. set_curjob(struct job *jp, unsigned mode)
  3459. {
  3460. struct job *jp1;
  3461. struct job **jpp, **curp;
  3462. /* first remove from list */
  3463. jpp = curp = &curjob;
  3464. while (1) {
  3465. jp1 = *jpp;
  3466. if (jp1 == jp)
  3467. break;
  3468. jpp = &jp1->prev_job;
  3469. }
  3470. *jpp = jp1->prev_job;
  3471. /* Then re-insert in correct position */
  3472. jpp = curp;
  3473. switch (mode) {
  3474. default:
  3475. #if DEBUG
  3476. abort();
  3477. #endif
  3478. case CUR_DELETE:
  3479. /* job being deleted */
  3480. break;
  3481. case CUR_RUNNING:
  3482. /* newly created job or backgrounded job,
  3483. * put after all stopped jobs.
  3484. */
  3485. while (1) {
  3486. jp1 = *jpp;
  3487. #if JOBS
  3488. if (!jp1 || jp1->state != JOBSTOPPED)
  3489. #endif
  3490. break;
  3491. jpp = &jp1->prev_job;
  3492. }
  3493. /* FALLTHROUGH */
  3494. #if JOBS
  3495. case CUR_STOPPED:
  3496. #endif
  3497. /* newly stopped job - becomes curjob */
  3498. jp->prev_job = *jpp;
  3499. *jpp = jp;
  3500. break;
  3501. }
  3502. }
  3503. #if JOBS || DEBUG
  3504. static int
  3505. jobno(const struct job *jp)
  3506. {
  3507. return jp - jobtab + 1;
  3508. }
  3509. #endif
  3510. /*
  3511. * Convert a job name to a job structure.
  3512. */
  3513. #if !JOBS
  3514. #define getjob(name, getctl) getjob(name)
  3515. #endif
  3516. static struct job *
  3517. getjob(const char *name, int getctl)
  3518. {
  3519. struct job *jp;
  3520. struct job *found;
  3521. const char *err_msg = "%s: no such job";
  3522. unsigned num;
  3523. int c;
  3524. const char *p;
  3525. char *(*match)(const char *, const char *);
  3526. jp = curjob;
  3527. p = name;
  3528. if (!p)
  3529. goto currentjob;
  3530. if (*p != '%')
  3531. goto err;
  3532. c = *++p;
  3533. if (!c)
  3534. goto currentjob;
  3535. if (!p[1]) {
  3536. if (c == '+' || c == '%') {
  3537. currentjob:
  3538. err_msg = "No current job";
  3539. goto check;
  3540. }
  3541. if (c == '-') {
  3542. if (jp)
  3543. jp = jp->prev_job;
  3544. err_msg = "No previous job";
  3545. check:
  3546. if (!jp)
  3547. goto err;
  3548. goto gotit;
  3549. }
  3550. }
  3551. if (is_number(p)) {
  3552. num = atoi(p);
  3553. if (num > 0 && num <= njobs) {
  3554. jp = jobtab + num - 1;
  3555. if (jp->used)
  3556. goto gotit;
  3557. goto err;
  3558. }
  3559. }
  3560. match = prefix;
  3561. if (*p == '?') {
  3562. match = strstr;
  3563. p++;
  3564. }
  3565. found = NULL;
  3566. while (jp) {
  3567. if (match(jp->ps[0].ps_cmd, p)) {
  3568. if (found)
  3569. goto err;
  3570. found = jp;
  3571. err_msg = "%s: ambiguous";
  3572. }
  3573. jp = jp->prev_job;
  3574. }
  3575. if (!found)
  3576. goto err;
  3577. jp = found;
  3578. gotit:
  3579. #if JOBS
  3580. err_msg = "job %s not created under job control";
  3581. if (getctl && jp->jobctl == 0)
  3582. goto err;
  3583. #endif
  3584. return jp;
  3585. err:
  3586. ash_msg_and_raise_error(err_msg, name);
  3587. }
  3588. /*
  3589. * Mark a job structure as unused.
  3590. */
  3591. static void
  3592. freejob(struct job *jp)
  3593. {
  3594. struct procstat *ps;
  3595. int i;
  3596. INT_OFF;
  3597. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3598. if (ps->ps_cmd != nullstr)
  3599. free(ps->ps_cmd);
  3600. }
  3601. if (jp->ps != &jp->ps0)
  3602. free(jp->ps);
  3603. jp->used = 0;
  3604. set_curjob(jp, CUR_DELETE);
  3605. INT_ON;
  3606. }
  3607. #if JOBS
  3608. static void
  3609. xtcsetpgrp(int fd, pid_t pgrp)
  3610. {
  3611. if (tcsetpgrp(fd, pgrp))
  3612. ash_msg_and_raise_perror("can't set tty process group");
  3613. }
  3614. /*
  3615. * Turn job control on and off.
  3616. *
  3617. * Note: This code assumes that the third arg to ioctl is a character
  3618. * pointer, which is true on Berkeley systems but not System V. Since
  3619. * System V doesn't have job control yet, this isn't a problem now.
  3620. *
  3621. * Called with interrupts off.
  3622. */
  3623. static void
  3624. setjobctl(int on)
  3625. {
  3626. int fd;
  3627. int pgrp;
  3628. if (on == doing_jobctl || rootshell == 0)
  3629. return;
  3630. if (on) {
  3631. int ofd;
  3632. ofd = fd = open(_PATH_TTY, O_RDWR);
  3633. if (fd < 0) {
  3634. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3635. * That sometimes helps to acquire controlling tty.
  3636. * Obviously, a workaround for bugs when someone
  3637. * failed to provide a controlling tty to bash! :) */
  3638. fd = 2;
  3639. while (!isatty(fd))
  3640. if (--fd < 0)
  3641. goto out;
  3642. }
  3643. /* fd is a tty at this point */
  3644. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3645. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3646. close(ofd);
  3647. if (fd < 0)
  3648. goto out; /* F_DUPFD failed */
  3649. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3650. close_on_exec_on(fd);
  3651. while (1) { /* while we are in the background */
  3652. pgrp = tcgetpgrp(fd);
  3653. if (pgrp < 0) {
  3654. out:
  3655. ash_msg("can't access tty; job control turned off");
  3656. mflag = on = 0;
  3657. goto close;
  3658. }
  3659. if (pgrp == getpgrp())
  3660. break;
  3661. killpg(0, SIGTTIN);
  3662. }
  3663. initialpgrp = pgrp;
  3664. setsignal(SIGTSTP);
  3665. setsignal(SIGTTOU);
  3666. setsignal(SIGTTIN);
  3667. pgrp = rootpid;
  3668. setpgid(0, pgrp);
  3669. xtcsetpgrp(fd, pgrp);
  3670. } else {
  3671. /* turning job control off */
  3672. fd = ttyfd;
  3673. pgrp = initialpgrp;
  3674. /* was xtcsetpgrp, but this can make exiting ash
  3675. * loop forever if pty is already deleted */
  3676. tcsetpgrp(fd, pgrp);
  3677. setpgid(0, pgrp);
  3678. setsignal(SIGTSTP);
  3679. setsignal(SIGTTOU);
  3680. setsignal(SIGTTIN);
  3681. close:
  3682. if (fd >= 0)
  3683. close(fd);
  3684. fd = -1;
  3685. }
  3686. ttyfd = fd;
  3687. doing_jobctl = on;
  3688. }
  3689. static int FAST_FUNC
  3690. killcmd(int argc, char **argv)
  3691. {
  3692. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3693. int i = 1;
  3694. do {
  3695. if (argv[i][0] == '%') {
  3696. /*
  3697. * "kill %N" - job kill
  3698. * Converting to pgrp / pid kill
  3699. */
  3700. struct job *jp;
  3701. char *dst;
  3702. int j, n;
  3703. jp = getjob(argv[i], 0);
  3704. /*
  3705. * In jobs started under job control, we signal
  3706. * entire process group by kill -PGRP_ID.
  3707. * This happens, f.e., in interactive shell.
  3708. *
  3709. * Otherwise, we signal each child via
  3710. * kill PID1 PID2 PID3.
  3711. * Testcases:
  3712. * sh -c 'sleep 1|sleep 1 & kill %1'
  3713. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3714. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3715. */
  3716. n = jp->nprocs; /* can't be 0 (I hope) */
  3717. if (jp->jobctl)
  3718. n = 1;
  3719. dst = alloca(n * sizeof(int)*4);
  3720. argv[i] = dst;
  3721. for (j = 0; j < n; j++) {
  3722. struct procstat *ps = &jp->ps[j];
  3723. /* Skip non-running and not-stopped members
  3724. * (i.e. dead members) of the job
  3725. */
  3726. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3727. continue;
  3728. /*
  3729. * kill_main has matching code to expect
  3730. * leading space. Needed to not confuse
  3731. * negative pids with "kill -SIGNAL_NO" syntax
  3732. */
  3733. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3734. }
  3735. *dst = '\0';
  3736. }
  3737. } while (argv[++i]);
  3738. }
  3739. return kill_main(argc, argv);
  3740. }
  3741. static void
  3742. showpipe(struct job *jp /*, FILE *out*/)
  3743. {
  3744. struct procstat *ps;
  3745. struct procstat *psend;
  3746. psend = jp->ps + jp->nprocs;
  3747. for (ps = jp->ps + 1; ps < psend; ps++)
  3748. printf(" | %s", ps->ps_cmd);
  3749. newline_and_flush(stdout);
  3750. flush_stdout_stderr();
  3751. }
  3752. static int
  3753. restartjob(struct job *jp, int mode)
  3754. {
  3755. struct procstat *ps;
  3756. int i;
  3757. int status;
  3758. pid_t pgid;
  3759. INT_OFF;
  3760. if (jp->state == JOBDONE)
  3761. goto out;
  3762. jp->state = JOBRUNNING;
  3763. pgid = jp->ps[0].ps_pid;
  3764. if (mode == FORK_FG) {
  3765. get_tty_state();
  3766. xtcsetpgrp(ttyfd, pgid);
  3767. }
  3768. killpg(pgid, SIGCONT);
  3769. ps = jp->ps;
  3770. i = jp->nprocs;
  3771. do {
  3772. if (WIFSTOPPED(ps->ps_status)) {
  3773. ps->ps_status = -1;
  3774. }
  3775. ps++;
  3776. } while (--i);
  3777. out:
  3778. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3779. INT_ON;
  3780. return status;
  3781. }
  3782. static int FAST_FUNC
  3783. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3784. {
  3785. struct job *jp;
  3786. int mode;
  3787. int retval;
  3788. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3789. nextopt(nullstr);
  3790. argv = argptr;
  3791. do {
  3792. jp = getjob(*argv, 1);
  3793. if (mode == FORK_BG) {
  3794. set_curjob(jp, CUR_RUNNING);
  3795. printf("[%d] ", jobno(jp));
  3796. }
  3797. out1str(jp->ps[0].ps_cmd);
  3798. showpipe(jp /*, stdout*/);
  3799. retval = restartjob(jp, mode);
  3800. } while (*argv && *++argv);
  3801. return retval;
  3802. }
  3803. #endif
  3804. static int
  3805. sprint_status48(char *s, int status, int sigonly)
  3806. {
  3807. int col;
  3808. int st;
  3809. col = 0;
  3810. if (!WIFEXITED(status)) {
  3811. #if JOBS
  3812. if (WIFSTOPPED(status))
  3813. st = WSTOPSIG(status);
  3814. else
  3815. #endif
  3816. st = WTERMSIG(status);
  3817. if (sigonly) {
  3818. if (st == SIGINT || st == SIGPIPE)
  3819. goto out;
  3820. #if JOBS
  3821. if (WIFSTOPPED(status))
  3822. goto out;
  3823. #endif
  3824. }
  3825. st &= 0x7f;
  3826. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3827. col = fmtstr(s, 32, strsignal(st));
  3828. if (WCOREDUMP(status)) {
  3829. strcpy(s + col, " (core dumped)");
  3830. col += sizeof(" (core dumped)")-1;
  3831. }
  3832. } else if (!sigonly) {
  3833. st = WEXITSTATUS(status);
  3834. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3835. }
  3836. out:
  3837. return col;
  3838. }
  3839. static int
  3840. wait_block_or_sig(int *status)
  3841. {
  3842. int pid;
  3843. do {
  3844. sigset_t mask;
  3845. /* Poll all children for changes in their state */
  3846. got_sigchld = 0;
  3847. /* if job control is active, accept stopped processes too */
  3848. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3849. if (pid != 0)
  3850. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3851. /* Children exist, but none are ready. Sleep until interesting signal */
  3852. #if 1
  3853. sigfillset(&mask);
  3854. sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
  3855. while (!got_sigchld && !pending_sig)
  3856. sigsuspend(&mask);
  3857. sigprocmask(SIG_SETMASK, &mask, NULL);
  3858. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3859. while (!got_sigchld && !pending_sig)
  3860. pause();
  3861. #endif
  3862. /* If it was SIGCHLD, poll children again */
  3863. } while (got_sigchld);
  3864. return pid;
  3865. }
  3866. #define DOWAIT_NONBLOCK 0
  3867. #define DOWAIT_BLOCK 1
  3868. #define DOWAIT_BLOCK_OR_SIG 2
  3869. #if BASH_WAIT_N
  3870. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3871. #endif
  3872. static int
  3873. dowait(int block, struct job *job)
  3874. {
  3875. int pid;
  3876. int status;
  3877. struct job *jp;
  3878. struct job *thisjob;
  3879. #if BASH_WAIT_N
  3880. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3881. block = (block & ~DOWAIT_JOBSTATUS);
  3882. #endif
  3883. TRACE(("dowait(0x%x) called\n", block));
  3884. /* It's wrong to call waitpid() outside of INT_OFF region:
  3885. * signal can arrive just after syscall return and handler can
  3886. * longjmp away, losing stop/exit notification processing.
  3887. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3888. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3889. *
  3890. * However, for "wait" builtin it is wrong to simply call waitpid()
  3891. * in INT_OFF region: "wait" needs to wait for any running job
  3892. * to change state, but should exit on any trap too.
  3893. * In INT_OFF region, a signal just before syscall entry can set
  3894. * pending_sig variables, but we can't check them, and we would
  3895. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3896. *
  3897. * Because of this, we run inside INT_OFF, but use a special routine
  3898. * which combines waitpid() and sigsuspend().
  3899. * This is the reason why we need to have a handler for SIGCHLD:
  3900. * SIG_DFL handler does not wake sigsuspend().
  3901. */
  3902. INT_OFF;
  3903. if (block == DOWAIT_BLOCK_OR_SIG) {
  3904. pid = wait_block_or_sig(&status);
  3905. } else {
  3906. int wait_flags = 0;
  3907. if (block == DOWAIT_NONBLOCK)
  3908. wait_flags = WNOHANG;
  3909. /* if job control is active, accept stopped processes too */
  3910. if (doing_jobctl)
  3911. wait_flags |= WUNTRACED;
  3912. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3913. pid = waitpid(-1, &status, wait_flags);
  3914. }
  3915. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3916. pid, status, errno, strerror(errno)));
  3917. thisjob = NULL;
  3918. if (pid <= 0)
  3919. goto out;
  3920. for (jp = curjob; jp; jp = jp->prev_job) {
  3921. int jobstate;
  3922. struct procstat *ps;
  3923. struct procstat *psend;
  3924. if (jp->state == JOBDONE)
  3925. continue;
  3926. jobstate = JOBDONE;
  3927. ps = jp->ps;
  3928. psend = ps + jp->nprocs;
  3929. do {
  3930. if (ps->ps_pid == pid) {
  3931. TRACE(("Job %d: changing status of proc %d "
  3932. "from 0x%x to 0x%x\n",
  3933. jobno(jp), pid, ps->ps_status, status));
  3934. ps->ps_status = status;
  3935. thisjob = jp;
  3936. }
  3937. if (ps->ps_status == -1)
  3938. jobstate = JOBRUNNING;
  3939. #if JOBS
  3940. if (jobstate == JOBRUNNING)
  3941. continue;
  3942. if (WIFSTOPPED(ps->ps_status)) {
  3943. jp->stopstatus = ps->ps_status;
  3944. jobstate = JOBSTOPPED;
  3945. }
  3946. #endif
  3947. } while (++ps < psend);
  3948. if (!thisjob)
  3949. continue;
  3950. /* Found the job where one of its processes changed its state.
  3951. * Is there at least one live and running process in this job? */
  3952. if (jobstate != JOBRUNNING) {
  3953. /* No. All live processes in the job are stopped
  3954. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3955. */
  3956. thisjob->changed = 1;
  3957. if (thisjob->state != jobstate) {
  3958. TRACE(("Job %d: changing state from %d to %d\n",
  3959. jobno(thisjob), thisjob->state, jobstate));
  3960. thisjob->state = jobstate;
  3961. #if JOBS
  3962. if (jobstate == JOBSTOPPED)
  3963. set_curjob(thisjob, CUR_STOPPED);
  3964. #endif
  3965. }
  3966. }
  3967. goto out;
  3968. }
  3969. /* The process wasn't found in job list */
  3970. #if JOBS
  3971. if (!WIFSTOPPED(status))
  3972. jobless--;
  3973. #endif
  3974. out:
  3975. INT_ON;
  3976. #if BASH_WAIT_N
  3977. if (want_jobexitstatus) {
  3978. pid = -1;
  3979. if (thisjob && thisjob->state == JOBDONE)
  3980. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  3981. }
  3982. #endif
  3983. if (thisjob && thisjob == job) {
  3984. char s[48 + 1];
  3985. int len;
  3986. len = sprint_status48(s, status, 1);
  3987. if (len) {
  3988. s[len] = '\n';
  3989. s[len + 1] = '\0';
  3990. out2str(s);
  3991. }
  3992. }
  3993. return pid;
  3994. }
  3995. #if JOBS
  3996. static void
  3997. showjob(struct job *jp, int mode)
  3998. {
  3999. struct procstat *ps;
  4000. struct procstat *psend;
  4001. int col;
  4002. int indent_col;
  4003. char s[16 + 16 + 48];
  4004. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4005. ps = jp->ps;
  4006. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4007. /* just output process (group) id of pipeline */
  4008. fprintf(out, "%d\n", ps->ps_pid);
  4009. return;
  4010. }
  4011. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4012. indent_col = col;
  4013. if (jp == curjob)
  4014. s[col - 3] = '+';
  4015. else if (curjob && jp == curjob->prev_job)
  4016. s[col - 3] = '-';
  4017. if (mode & SHOW_PIDS)
  4018. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4019. psend = ps + jp->nprocs;
  4020. if (jp->state == JOBRUNNING) {
  4021. strcpy(s + col, "Running");
  4022. col += sizeof("Running") - 1;
  4023. } else {
  4024. int status = psend[-1].ps_status;
  4025. if (jp->state == JOBSTOPPED)
  4026. status = jp->stopstatus;
  4027. col += sprint_status48(s + col, status, 0);
  4028. }
  4029. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4030. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4031. * or prints several "PID | <cmdN>" lines,
  4032. * depending on SHOW_PIDS bit.
  4033. * We do not print status of individual processes
  4034. * between PID and <cmdN>. bash does it, but not very well:
  4035. * first line shows overall job status, not process status,
  4036. * making it impossible to know 1st process status.
  4037. */
  4038. goto start;
  4039. do {
  4040. /* for each process */
  4041. s[0] = '\0';
  4042. col = 33;
  4043. if (mode & SHOW_PIDS)
  4044. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4045. start:
  4046. fprintf(out, "%s%*c%s%s",
  4047. s,
  4048. 33 - col >= 0 ? 33 - col : 0, ' ',
  4049. ps == jp->ps ? "" : "| ",
  4050. ps->ps_cmd
  4051. );
  4052. } while (++ps != psend);
  4053. newline_and_flush(out);
  4054. jp->changed = 0;
  4055. if (jp->state == JOBDONE) {
  4056. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4057. freejob(jp);
  4058. }
  4059. }
  4060. /*
  4061. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4062. * statuses have changed since the last call to showjobs.
  4063. */
  4064. static void
  4065. showjobs(int mode)
  4066. {
  4067. struct job *jp;
  4068. TRACE(("showjobs(0x%x) called\n", mode));
  4069. /* Handle all finished jobs */
  4070. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4071. continue;
  4072. for (jp = curjob; jp; jp = jp->prev_job) {
  4073. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4074. showjob(jp, mode);
  4075. }
  4076. }
  4077. }
  4078. static int FAST_FUNC
  4079. jobscmd(int argc UNUSED_PARAM, char **argv)
  4080. {
  4081. int mode, m;
  4082. mode = 0;
  4083. while ((m = nextopt("lp")) != '\0') {
  4084. if (m == 'l')
  4085. mode |= SHOW_PIDS;
  4086. else
  4087. mode |= SHOW_ONLY_PGID;
  4088. }
  4089. argv = argptr;
  4090. if (*argv) {
  4091. do
  4092. showjob(getjob(*argv, 0), mode);
  4093. while (*++argv);
  4094. } else {
  4095. showjobs(mode);
  4096. }
  4097. return 0;
  4098. }
  4099. #endif /* JOBS */
  4100. /* Called only on finished or stopped jobs (no members are running) */
  4101. static int
  4102. getstatus(struct job *job)
  4103. {
  4104. int status;
  4105. int retval;
  4106. struct procstat *ps;
  4107. /* Fetch last member's status */
  4108. ps = job->ps + job->nprocs - 1;
  4109. status = ps->ps_status;
  4110. if (pipefail) {
  4111. /* "set -o pipefail" mode: use last _nonzero_ status */
  4112. while (status == 0 && --ps >= job->ps)
  4113. status = ps->ps_status;
  4114. }
  4115. retval = WEXITSTATUS(status);
  4116. if (!WIFEXITED(status)) {
  4117. #if JOBS
  4118. retval = WSTOPSIG(status);
  4119. if (!WIFSTOPPED(status))
  4120. #endif
  4121. {
  4122. /* XXX: limits number of signals */
  4123. retval = WTERMSIG(status);
  4124. #if JOBS
  4125. if (retval == SIGINT)
  4126. job->sigint = 1;
  4127. #endif
  4128. }
  4129. retval += 128;
  4130. }
  4131. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4132. jobno(job), job->nprocs, status, retval));
  4133. return retval;
  4134. }
  4135. static int FAST_FUNC
  4136. waitcmd(int argc UNUSED_PARAM, char **argv)
  4137. {
  4138. struct job *job;
  4139. int retval;
  4140. struct job *jp;
  4141. #if BASH_WAIT_N
  4142. int status;
  4143. char one = nextopt("n");
  4144. #else
  4145. nextopt(nullstr);
  4146. #endif
  4147. retval = 0;
  4148. argv = argptr;
  4149. if (!argv[0]) {
  4150. /* wait for all jobs / one job if -n */
  4151. for (;;) {
  4152. jp = curjob;
  4153. #if BASH_WAIT_N
  4154. if (one && !jp)
  4155. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4156. retval = 127;
  4157. #endif
  4158. while (1) {
  4159. if (!jp) /* no running procs */
  4160. goto ret;
  4161. if (jp->state == JOBRUNNING)
  4162. break;
  4163. jp->waited = 1;
  4164. jp = jp->prev_job;
  4165. }
  4166. /* man bash:
  4167. * "When bash is waiting for an asynchronous command via
  4168. * the wait builtin, the reception of a signal for which a trap
  4169. * has been set will cause the wait builtin to return immediately
  4170. * with an exit status greater than 128, immediately after which
  4171. * the trap is executed."
  4172. */
  4173. #if BASH_WAIT_N
  4174. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4175. #else
  4176. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4177. #endif
  4178. /* if child sends us a signal *and immediately exits*,
  4179. * dowait() returns pid > 0. Check this case,
  4180. * not "if (dowait() < 0)"!
  4181. */
  4182. if (pending_sig)
  4183. goto sigout;
  4184. #if BASH_WAIT_N
  4185. if (one) {
  4186. /* wait -n waits for one _job_, not one _process_.
  4187. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4188. * should wait for 2 seconds. Not 1 or 3.
  4189. */
  4190. if (status != -1 && !WIFSTOPPED(status)) {
  4191. retval = WEXITSTATUS(status);
  4192. if (WIFSIGNALED(status))
  4193. retval = WTERMSIG(status) + 128;
  4194. goto ret;
  4195. }
  4196. }
  4197. #endif
  4198. }
  4199. }
  4200. retval = 127;
  4201. do {
  4202. if (**argv != '%') {
  4203. pid_t pid = number(*argv);
  4204. job = curjob;
  4205. while (1) {
  4206. if (!job)
  4207. goto repeat;
  4208. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4209. break;
  4210. job = job->prev_job;
  4211. }
  4212. } else {
  4213. job = getjob(*argv, 0);
  4214. }
  4215. /* loop until process terminated or stopped */
  4216. while (job->state == JOBRUNNING) {
  4217. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4218. if (pending_sig)
  4219. goto sigout;
  4220. }
  4221. job->waited = 1;
  4222. retval = getstatus(job);
  4223. repeat: ;
  4224. } while (*++argv);
  4225. ret:
  4226. return retval;
  4227. sigout:
  4228. retval = 128 + pending_sig;
  4229. return retval;
  4230. }
  4231. static struct job *
  4232. growjobtab(void)
  4233. {
  4234. size_t len;
  4235. ptrdiff_t offset;
  4236. struct job *jp, *jq;
  4237. len = njobs * sizeof(*jp);
  4238. jq = jobtab;
  4239. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4240. offset = (char *)jp - (char *)jq;
  4241. if (offset) {
  4242. /* Relocate pointers */
  4243. size_t l = len;
  4244. jq = (struct job *)((char *)jq + l);
  4245. while (l) {
  4246. l -= sizeof(*jp);
  4247. jq--;
  4248. #define joff(p) ((struct job *)((char *)(p) + l))
  4249. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4250. if (joff(jp)->ps == &jq->ps0)
  4251. jmove(joff(jp)->ps);
  4252. if (joff(jp)->prev_job)
  4253. jmove(joff(jp)->prev_job);
  4254. }
  4255. if (curjob)
  4256. jmove(curjob);
  4257. #undef joff
  4258. #undef jmove
  4259. }
  4260. njobs += 4;
  4261. jobtab = jp;
  4262. jp = (struct job *)((char *)jp + len);
  4263. jq = jp + 3;
  4264. do {
  4265. jq->used = 0;
  4266. } while (--jq >= jp);
  4267. return jp;
  4268. }
  4269. /*
  4270. * Return a new job structure.
  4271. * Called with interrupts off.
  4272. */
  4273. static struct job *
  4274. makejob(/*union node *node,*/ int nprocs)
  4275. {
  4276. int i;
  4277. struct job *jp;
  4278. for (i = njobs, jp = jobtab; ; jp++) {
  4279. if (--i < 0) {
  4280. jp = growjobtab();
  4281. break;
  4282. }
  4283. if (jp->used == 0)
  4284. break;
  4285. if (jp->state != JOBDONE || !jp->waited)
  4286. continue;
  4287. #if JOBS
  4288. if (doing_jobctl)
  4289. continue;
  4290. #endif
  4291. freejob(jp);
  4292. break;
  4293. }
  4294. memset(jp, 0, sizeof(*jp));
  4295. #if JOBS
  4296. /* jp->jobctl is a bitfield.
  4297. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4298. if (doing_jobctl)
  4299. jp->jobctl = 1;
  4300. #endif
  4301. jp->prev_job = curjob;
  4302. curjob = jp;
  4303. jp->used = 1;
  4304. jp->ps = &jp->ps0;
  4305. if (nprocs > 1) {
  4306. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4307. }
  4308. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4309. jobno(jp)));
  4310. return jp;
  4311. }
  4312. #if JOBS
  4313. /*
  4314. * Return a string identifying a command (to be printed by the
  4315. * jobs command).
  4316. */
  4317. static char *cmdnextc;
  4318. static void
  4319. cmdputs(const char *s)
  4320. {
  4321. static const char vstype[VSTYPE + 1][3] = {
  4322. "", "}", "-", "+", "?", "=",
  4323. "%", "%%", "#", "##"
  4324. IF_BASH_SUBSTR(, ":")
  4325. IF_BASH_PATTERN_SUBST(, "/", "//")
  4326. };
  4327. const char *p, *str;
  4328. char cc[2];
  4329. char *nextc;
  4330. unsigned char c;
  4331. unsigned char subtype = 0;
  4332. int quoted = 0;
  4333. cc[1] = '\0';
  4334. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4335. p = s;
  4336. while ((c = *p++) != '\0') {
  4337. str = NULL;
  4338. switch (c) {
  4339. case CTLESC:
  4340. c = *p++;
  4341. break;
  4342. case CTLVAR:
  4343. subtype = *p++;
  4344. if ((subtype & VSTYPE) == VSLENGTH)
  4345. str = "${#";
  4346. else
  4347. str = "${";
  4348. goto dostr;
  4349. case CTLENDVAR:
  4350. str = "\"}" + !(quoted & 1);
  4351. quoted >>= 1;
  4352. subtype = 0;
  4353. goto dostr;
  4354. case CTLBACKQ:
  4355. str = "$(...)";
  4356. goto dostr;
  4357. #if ENABLE_FEATURE_SH_MATH
  4358. case CTLARI:
  4359. str = "$((";
  4360. goto dostr;
  4361. case CTLENDARI:
  4362. str = "))";
  4363. goto dostr;
  4364. #endif
  4365. case CTLQUOTEMARK:
  4366. quoted ^= 1;
  4367. c = '"';
  4368. break;
  4369. case '=':
  4370. if (subtype == 0)
  4371. break;
  4372. if ((subtype & VSTYPE) != VSNORMAL)
  4373. quoted <<= 1;
  4374. str = vstype[subtype & VSTYPE];
  4375. if (subtype & VSNUL)
  4376. c = ':';
  4377. else
  4378. goto checkstr;
  4379. break;
  4380. case '\'':
  4381. case '\\':
  4382. case '"':
  4383. case '$':
  4384. /* These can only happen inside quotes */
  4385. cc[0] = c;
  4386. str = cc;
  4387. //FIXME:
  4388. // $ true $$ &
  4389. // $ <cr>
  4390. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4391. c = '\\';
  4392. break;
  4393. default:
  4394. break;
  4395. }
  4396. USTPUTC(c, nextc);
  4397. checkstr:
  4398. if (!str)
  4399. continue;
  4400. dostr:
  4401. while ((c = *str++) != '\0') {
  4402. USTPUTC(c, nextc);
  4403. }
  4404. } /* while *p++ not NUL */
  4405. if (quoted & 1) {
  4406. USTPUTC('"', nextc);
  4407. }
  4408. *nextc = 0;
  4409. cmdnextc = nextc;
  4410. }
  4411. /* cmdtxt() and cmdlist() call each other */
  4412. static void cmdtxt(union node *n);
  4413. static void
  4414. cmdlist(union node *np, int sep)
  4415. {
  4416. for (; np; np = np->narg.next) {
  4417. if (!sep)
  4418. cmdputs(" ");
  4419. cmdtxt(np);
  4420. if (sep && np->narg.next)
  4421. cmdputs(" ");
  4422. }
  4423. }
  4424. static void
  4425. cmdtxt(union node *n)
  4426. {
  4427. union node *np;
  4428. struct nodelist *lp;
  4429. const char *p;
  4430. if (!n)
  4431. return;
  4432. switch (n->type) {
  4433. default:
  4434. #if DEBUG
  4435. abort();
  4436. #endif
  4437. case NPIPE:
  4438. lp = n->npipe.cmdlist;
  4439. for (;;) {
  4440. cmdtxt(lp->n);
  4441. lp = lp->next;
  4442. if (!lp)
  4443. break;
  4444. cmdputs(" | ");
  4445. }
  4446. break;
  4447. case NSEMI:
  4448. p = "; ";
  4449. goto binop;
  4450. case NAND:
  4451. p = " && ";
  4452. goto binop;
  4453. case NOR:
  4454. p = " || ";
  4455. binop:
  4456. cmdtxt(n->nbinary.ch1);
  4457. cmdputs(p);
  4458. n = n->nbinary.ch2;
  4459. goto donode;
  4460. case NREDIR:
  4461. case NBACKGND:
  4462. n = n->nredir.n;
  4463. goto donode;
  4464. case NNOT:
  4465. cmdputs("!");
  4466. n = n->nnot.com;
  4467. donode:
  4468. cmdtxt(n);
  4469. break;
  4470. case NIF:
  4471. cmdputs("if ");
  4472. cmdtxt(n->nif.test);
  4473. cmdputs("; then ");
  4474. if (n->nif.elsepart) {
  4475. cmdtxt(n->nif.ifpart);
  4476. cmdputs("; else ");
  4477. n = n->nif.elsepart;
  4478. } else {
  4479. n = n->nif.ifpart;
  4480. }
  4481. p = "; fi";
  4482. goto dotail;
  4483. case NSUBSHELL:
  4484. cmdputs("(");
  4485. n = n->nredir.n;
  4486. p = ")";
  4487. goto dotail;
  4488. case NWHILE:
  4489. p = "while ";
  4490. goto until;
  4491. case NUNTIL:
  4492. p = "until ";
  4493. until:
  4494. cmdputs(p);
  4495. cmdtxt(n->nbinary.ch1);
  4496. n = n->nbinary.ch2;
  4497. p = "; done";
  4498. dodo:
  4499. cmdputs("; do ");
  4500. dotail:
  4501. cmdtxt(n);
  4502. goto dotail2;
  4503. case NFOR:
  4504. cmdputs("for ");
  4505. cmdputs(n->nfor.var);
  4506. cmdputs(" in ");
  4507. cmdlist(n->nfor.args, 1);
  4508. n = n->nfor.body;
  4509. p = "; done";
  4510. goto dodo;
  4511. case NDEFUN:
  4512. cmdputs(n->ndefun.text);
  4513. p = "() { ... }";
  4514. goto dotail2;
  4515. case NCMD:
  4516. cmdlist(n->ncmd.args, 1);
  4517. cmdlist(n->ncmd.redirect, 0);
  4518. break;
  4519. case NARG:
  4520. p = n->narg.text;
  4521. dotail2:
  4522. cmdputs(p);
  4523. break;
  4524. case NHERE:
  4525. case NXHERE:
  4526. p = "<<...";
  4527. goto dotail2;
  4528. case NCASE:
  4529. cmdputs("case ");
  4530. cmdputs(n->ncase.expr->narg.text);
  4531. cmdputs(" in ");
  4532. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4533. cmdtxt(np->nclist.pattern);
  4534. cmdputs(") ");
  4535. cmdtxt(np->nclist.body);
  4536. cmdputs(";; ");
  4537. }
  4538. p = "esac";
  4539. goto dotail2;
  4540. case NTO:
  4541. p = ">";
  4542. goto redir;
  4543. case NCLOBBER:
  4544. p = ">|";
  4545. goto redir;
  4546. case NAPPEND:
  4547. p = ">>";
  4548. goto redir;
  4549. #if BASH_REDIR_OUTPUT
  4550. case NTO2:
  4551. #endif
  4552. case NTOFD:
  4553. p = ">&";
  4554. goto redir;
  4555. case NFROM:
  4556. p = "<";
  4557. goto redir;
  4558. case NFROMFD:
  4559. p = "<&";
  4560. goto redir;
  4561. case NFROMTO:
  4562. p = "<>";
  4563. redir:
  4564. cmdputs(utoa(n->nfile.fd));
  4565. cmdputs(p);
  4566. if (n->type == NTOFD || n->type == NFROMFD) {
  4567. if (n->ndup.dupfd >= 0)
  4568. cmdputs(utoa(n->ndup.dupfd));
  4569. else
  4570. cmdputs("-");
  4571. break;
  4572. }
  4573. n = n->nfile.fname;
  4574. goto donode;
  4575. }
  4576. }
  4577. static char *
  4578. commandtext(union node *n)
  4579. {
  4580. char *name;
  4581. STARTSTACKSTR(cmdnextc);
  4582. cmdtxt(n);
  4583. name = stackblock();
  4584. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4585. return ckstrdup(name);
  4586. }
  4587. #endif /* JOBS */
  4588. /*
  4589. * Fork off a subshell. If we are doing job control, give the subshell its
  4590. * own process group. Jp is a job structure that the job is to be added to.
  4591. * N is the command that will be evaluated by the child. Both jp and n may
  4592. * be NULL. The mode parameter can be one of the following:
  4593. * FORK_FG - Fork off a foreground process.
  4594. * FORK_BG - Fork off a background process.
  4595. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4596. * process group even if job control is on.
  4597. *
  4598. * When job control is turned off, background processes have their standard
  4599. * input redirected to /dev/null (except for the second and later processes
  4600. * in a pipeline).
  4601. *
  4602. * Called with interrupts off.
  4603. */
  4604. /*
  4605. * Clear traps on a fork.
  4606. */
  4607. static void
  4608. clear_traps(void)
  4609. {
  4610. char **tp;
  4611. INT_OFF;
  4612. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4613. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4614. if (trap_ptr == trap)
  4615. free(*tp);
  4616. /* else: it "belongs" to trap_ptr vector, don't free */
  4617. *tp = NULL;
  4618. if ((tp - trap) != 0)
  4619. setsignal(tp - trap);
  4620. }
  4621. }
  4622. may_have_traps = 0;
  4623. INT_ON;
  4624. }
  4625. /* Lives far away from here, needed for forkchild */
  4626. static void closescript(void);
  4627. /* Called after fork(), in child */
  4628. /* jp and n are NULL when called by openhere() for heredoc support */
  4629. static NOINLINE void
  4630. forkchild(struct job *jp, union node *n, int mode)
  4631. {
  4632. int oldlvl;
  4633. TRACE(("Child shell %d\n", getpid()));
  4634. oldlvl = shlvl;
  4635. shlvl++;
  4636. /* man bash: "Non-builtin commands run by bash have signal handlers
  4637. * set to the values inherited by the shell from its parent".
  4638. * Do we do it correctly? */
  4639. closescript();
  4640. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4641. && n && n->type == NCMD /* is it single cmd? */
  4642. /* && n->ncmd.args->type == NARG - always true? */
  4643. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4644. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4645. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4646. ) {
  4647. TRACE(("Trap hack\n"));
  4648. /* Awful hack for `trap` or $(trap).
  4649. *
  4650. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4651. * contains an example where "trap" is executed in a subshell:
  4652. *
  4653. * save_traps=$(trap)
  4654. * ...
  4655. * eval "$save_traps"
  4656. *
  4657. * Standard does not say that "trap" in subshell shall print
  4658. * parent shell's traps. It only says that its output
  4659. * must have suitable form, but then, in the above example
  4660. * (which is not supposed to be normative), it implies that.
  4661. *
  4662. * bash (and probably other shell) does implement it
  4663. * (traps are reset to defaults, but "trap" still shows them),
  4664. * but as a result, "trap" logic is hopelessly messed up:
  4665. *
  4666. * # trap
  4667. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4668. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4669. * # true | trap <--- trap is in subshell - no output (ditto)
  4670. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4671. * trap -- 'echo Ho' SIGWINCH
  4672. * # echo `(trap)` <--- in subshell in subshell - output
  4673. * trap -- 'echo Ho' SIGWINCH
  4674. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4675. * trap -- 'echo Ho' SIGWINCH
  4676. *
  4677. * The rules when to forget and when to not forget traps
  4678. * get really complex and nonsensical.
  4679. *
  4680. * Our solution: ONLY bare $(trap) or `trap` is special.
  4681. */
  4682. /* Save trap handler strings for trap builtin to print */
  4683. trap_ptr = xmemdup(trap, sizeof(trap));
  4684. /* Fall through into clearing traps */
  4685. }
  4686. clear_traps();
  4687. #if JOBS
  4688. /* do job control only in root shell */
  4689. doing_jobctl = 0;
  4690. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4691. pid_t pgrp;
  4692. if (jp->nprocs == 0)
  4693. pgrp = getpid();
  4694. else
  4695. pgrp = jp->ps[0].ps_pid;
  4696. /* this can fail because we are doing it in the parent also */
  4697. setpgid(0, pgrp);
  4698. if (mode == FORK_FG)
  4699. xtcsetpgrp(ttyfd, pgrp);
  4700. setsignal(SIGTSTP);
  4701. setsignal(SIGTTOU);
  4702. } else
  4703. #endif
  4704. if (mode == FORK_BG) {
  4705. /* man bash: "When job control is not in effect,
  4706. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4707. ignoresig(SIGINT);
  4708. ignoresig(SIGQUIT);
  4709. if (jp->nprocs == 0) {
  4710. close(0);
  4711. if (open(bb_dev_null, O_RDONLY) != 0)
  4712. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4713. }
  4714. }
  4715. if (oldlvl == 0) {
  4716. if (iflag) { /* why if iflag only? */
  4717. setsignal(SIGINT);
  4718. setsignal(SIGTERM);
  4719. }
  4720. /* man bash:
  4721. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4722. * commands run by bash have signal handlers
  4723. * set to the values inherited by the shell
  4724. * from its parent".
  4725. * Take care of the second rule: */
  4726. setsignal(SIGQUIT);
  4727. }
  4728. #if JOBS
  4729. if (n && n->type == NCMD
  4730. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4731. ) {
  4732. TRACE(("Job hack\n"));
  4733. /* "jobs": we do not want to clear job list for it,
  4734. * instead we remove only _its_ own_ job from job list.
  4735. * This makes "jobs .... | cat" more useful.
  4736. */
  4737. freejob(curjob);
  4738. return;
  4739. }
  4740. #endif
  4741. for (jp = curjob; jp; jp = jp->prev_job)
  4742. freejob(jp);
  4743. jobless = 0;
  4744. }
  4745. /* Called after fork(), in parent */
  4746. #if !JOBS
  4747. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4748. #endif
  4749. static void
  4750. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4751. {
  4752. TRACE(("In parent shell: child = %d\n", pid));
  4753. if (!jp) {
  4754. /* jp is NULL when called by openhere() for heredoc support */
  4755. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4756. continue;
  4757. jobless++;
  4758. return;
  4759. }
  4760. #if JOBS
  4761. if (mode != FORK_NOJOB && jp->jobctl) {
  4762. int pgrp;
  4763. if (jp->nprocs == 0)
  4764. pgrp = pid;
  4765. else
  4766. pgrp = jp->ps[0].ps_pid;
  4767. /* This can fail because we are doing it in the child also */
  4768. setpgid(pid, pgrp);
  4769. }
  4770. #endif
  4771. if (mode == FORK_BG) {
  4772. backgndpid = pid; /* set $! */
  4773. set_curjob(jp, CUR_RUNNING);
  4774. }
  4775. if (jp) {
  4776. struct procstat *ps = &jp->ps[jp->nprocs++];
  4777. ps->ps_pid = pid;
  4778. ps->ps_status = -1;
  4779. ps->ps_cmd = nullstr;
  4780. #if JOBS
  4781. if (doing_jobctl && n)
  4782. ps->ps_cmd = commandtext(n);
  4783. #endif
  4784. }
  4785. }
  4786. /* jp and n are NULL when called by openhere() for heredoc support */
  4787. static int
  4788. forkshell(struct job *jp, union node *n, int mode)
  4789. {
  4790. int pid;
  4791. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4792. pid = fork();
  4793. if (pid < 0) {
  4794. TRACE(("Fork failed, errno=%d", errno));
  4795. if (jp)
  4796. freejob(jp);
  4797. ash_msg_and_raise_perror("can't fork");
  4798. }
  4799. if (pid == 0) {
  4800. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4801. forkchild(jp, n, mode);
  4802. } else {
  4803. forkparent(jp, n, mode, pid);
  4804. }
  4805. return pid;
  4806. }
  4807. /*
  4808. * Wait for job to finish.
  4809. *
  4810. * Under job control we have the problem that while a child process
  4811. * is running interrupts generated by the user are sent to the child
  4812. * but not to the shell. This means that an infinite loop started by
  4813. * an interactive user may be hard to kill. With job control turned off,
  4814. * an interactive user may place an interactive program inside a loop.
  4815. * If the interactive program catches interrupts, the user doesn't want
  4816. * these interrupts to also abort the loop. The approach we take here
  4817. * is to have the shell ignore interrupt signals while waiting for a
  4818. * foreground process to terminate, and then send itself an interrupt
  4819. * signal if the child process was terminated by an interrupt signal.
  4820. * Unfortunately, some programs want to do a bit of cleanup and then
  4821. * exit on interrupt; unless these processes terminate themselves by
  4822. * sending a signal to themselves (instead of calling exit) they will
  4823. * confuse this approach.
  4824. *
  4825. * Called with interrupts off.
  4826. */
  4827. static int
  4828. waitforjob(struct job *jp)
  4829. {
  4830. int st;
  4831. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4832. INT_OFF;
  4833. while (jp->state == JOBRUNNING) {
  4834. /* In non-interactive shells, we _can_ get
  4835. * a keyboard signal here and be EINTRed,
  4836. * but we just loop back, waiting for command to complete.
  4837. *
  4838. * man bash:
  4839. * "If bash is waiting for a command to complete and receives
  4840. * a signal for which a trap has been set, the trap
  4841. * will not be executed until the command completes."
  4842. *
  4843. * Reality is that even if trap is not set, bash
  4844. * will not act on the signal until command completes.
  4845. * Try this. sleep5intoff.c:
  4846. * #include <signal.h>
  4847. * #include <unistd.h>
  4848. * int main() {
  4849. * sigset_t set;
  4850. * sigemptyset(&set);
  4851. * sigaddset(&set, SIGINT);
  4852. * sigaddset(&set, SIGQUIT);
  4853. * sigprocmask(SIG_BLOCK, &set, NULL);
  4854. * sleep(5);
  4855. * return 0;
  4856. * }
  4857. * $ bash -c './sleep5intoff; echo hi'
  4858. * ^C^C^C^C <--- pressing ^C once a second
  4859. * $ _
  4860. * $ bash -c './sleep5intoff; echo hi'
  4861. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4862. * $ _
  4863. */
  4864. dowait(DOWAIT_BLOCK, jp);
  4865. }
  4866. INT_ON;
  4867. st = getstatus(jp);
  4868. #if JOBS
  4869. if (jp->jobctl) {
  4870. xtcsetpgrp(ttyfd, rootpid);
  4871. restore_tty_if_stopped_or_signaled(jp);
  4872. /*
  4873. * This is truly gross.
  4874. * If we're doing job control, then we did a TIOCSPGRP which
  4875. * caused us (the shell) to no longer be in the controlling
  4876. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4877. * intuit from the subprocess exit status whether a SIGINT
  4878. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4879. */
  4880. if (jp->sigint) /* TODO: do the same with all signals */
  4881. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4882. }
  4883. if (jp->state == JOBDONE)
  4884. #endif
  4885. freejob(jp);
  4886. return st;
  4887. }
  4888. /*
  4889. * return 1 if there are stopped jobs, otherwise 0
  4890. */
  4891. static int
  4892. stoppedjobs(void)
  4893. {
  4894. struct job *jp;
  4895. int retval;
  4896. retval = 0;
  4897. if (job_warning)
  4898. goto out;
  4899. jp = curjob;
  4900. if (jp && jp->state == JOBSTOPPED) {
  4901. out2str("You have stopped jobs.\n");
  4902. job_warning = 2;
  4903. retval++;
  4904. }
  4905. out:
  4906. return retval;
  4907. }
  4908. /*
  4909. * Code for dealing with input/output redirection.
  4910. */
  4911. #undef EMPTY
  4912. #undef CLOSED
  4913. #define EMPTY -2 /* marks an unused slot in redirtab */
  4914. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4915. /*
  4916. * Handle here documents. Normally we fork off a process to write the
  4917. * data to a pipe. If the document is short, we can stuff the data in
  4918. * the pipe without forking.
  4919. */
  4920. /* openhere needs this forward reference */
  4921. static void expandhere(union node *arg, int fd);
  4922. static int
  4923. openhere(union node *redir)
  4924. {
  4925. int pip[2];
  4926. size_t len = 0;
  4927. if (pipe(pip) < 0)
  4928. ash_msg_and_raise_perror("can't create pipe");
  4929. if (redir->type == NHERE) {
  4930. len = strlen(redir->nhere.doc->narg.text);
  4931. if (len <= PIPE_BUF) {
  4932. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4933. goto out;
  4934. }
  4935. }
  4936. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4937. /* child */
  4938. close(pip[0]);
  4939. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4940. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4941. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4942. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4943. signal(SIGPIPE, SIG_DFL);
  4944. if (redir->type == NHERE)
  4945. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4946. else /* NXHERE */
  4947. expandhere(redir->nhere.doc, pip[1]);
  4948. _exit(EXIT_SUCCESS);
  4949. }
  4950. out:
  4951. close(pip[1]);
  4952. return pip[0];
  4953. }
  4954. static int
  4955. openredirect(union node *redir)
  4956. {
  4957. struct stat sb;
  4958. char *fname;
  4959. int f;
  4960. switch (redir->nfile.type) {
  4961. /* Can't happen, our single caller does this itself */
  4962. // case NTOFD:
  4963. // case NFROMFD:
  4964. // return -1;
  4965. case NHERE:
  4966. case NXHERE:
  4967. return openhere(redir);
  4968. }
  4969. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4970. * allocated space. Do it only when we know it is safe.
  4971. */
  4972. fname = redir->nfile.expfname;
  4973. switch (redir->nfile.type) {
  4974. default:
  4975. #if DEBUG
  4976. abort();
  4977. #endif
  4978. case NFROM:
  4979. f = open(fname, O_RDONLY);
  4980. if (f < 0)
  4981. goto eopen;
  4982. break;
  4983. case NFROMTO:
  4984. f = open(fname, O_RDWR|O_CREAT, 0666);
  4985. if (f < 0)
  4986. goto ecreate;
  4987. break;
  4988. case NTO:
  4989. #if BASH_REDIR_OUTPUT
  4990. case NTO2:
  4991. #endif
  4992. /* Take care of noclobber mode. */
  4993. if (Cflag) {
  4994. if (stat(fname, &sb) < 0) {
  4995. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4996. if (f < 0)
  4997. goto ecreate;
  4998. } else if (!S_ISREG(sb.st_mode)) {
  4999. f = open(fname, O_WRONLY, 0666);
  5000. if (f < 0)
  5001. goto ecreate;
  5002. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5003. close(f);
  5004. errno = EEXIST;
  5005. goto ecreate;
  5006. }
  5007. } else {
  5008. errno = EEXIST;
  5009. goto ecreate;
  5010. }
  5011. break;
  5012. }
  5013. /* FALLTHROUGH */
  5014. case NCLOBBER:
  5015. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5016. if (f < 0)
  5017. goto ecreate;
  5018. break;
  5019. case NAPPEND:
  5020. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5021. if (f < 0)
  5022. goto ecreate;
  5023. break;
  5024. }
  5025. return f;
  5026. ecreate:
  5027. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5028. eopen:
  5029. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5030. }
  5031. /*
  5032. * Copy a file descriptor to be >= 10. Throws exception on error.
  5033. */
  5034. static int
  5035. savefd(int from)
  5036. {
  5037. int newfd;
  5038. int err;
  5039. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5040. err = newfd < 0 ? errno : 0;
  5041. if (err != EBADF) {
  5042. if (err)
  5043. ash_msg_and_raise_perror("%d", from);
  5044. close(from);
  5045. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5046. close_on_exec_on(newfd);
  5047. }
  5048. return newfd;
  5049. }
  5050. static int
  5051. dup2_or_raise(int from, int to)
  5052. {
  5053. int newfd;
  5054. newfd = (from != to) ? dup2(from, to) : to;
  5055. if (newfd < 0) {
  5056. /* Happens when source fd is not open: try "echo >&99" */
  5057. ash_msg_and_raise_perror("%d", from);
  5058. }
  5059. return newfd;
  5060. }
  5061. static int
  5062. dup_CLOEXEC(int fd, int avoid_fd)
  5063. {
  5064. int newfd;
  5065. repeat:
  5066. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5067. if (newfd >= 0) {
  5068. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5069. close_on_exec_on(newfd);
  5070. } else { /* newfd < 0 */
  5071. if (errno == EBUSY)
  5072. goto repeat;
  5073. if (errno == EINTR)
  5074. goto repeat;
  5075. }
  5076. return newfd;
  5077. }
  5078. static int
  5079. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5080. {
  5081. int newfd;
  5082. repeat:
  5083. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5084. if (newfd < 0) {
  5085. if (errno == EBUSY)
  5086. goto repeat;
  5087. if (errno == EINTR)
  5088. goto repeat;
  5089. /* fd was not open? */
  5090. if (errno == EBADF)
  5091. return fd;
  5092. ash_msg_and_raise_perror("%d", newfd);
  5093. }
  5094. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5095. close_on_exec_on(newfd);
  5096. close(fd);
  5097. return newfd;
  5098. }
  5099. /* Struct def and variable are moved down to the first usage site */
  5100. struct squirrel {
  5101. int orig_fd;
  5102. int moved_to;
  5103. };
  5104. struct redirtab {
  5105. struct redirtab *next;
  5106. int pair_count;
  5107. struct squirrel two_fd[];
  5108. };
  5109. #define redirlist (G_var.redirlist)
  5110. static void
  5111. add_squirrel_closed(struct redirtab *sq, int fd)
  5112. {
  5113. int i;
  5114. if (!sq)
  5115. return;
  5116. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5117. /* If we collide with an already moved fd... */
  5118. if (fd == sq->two_fd[i].orig_fd) {
  5119. /* Examples:
  5120. * "echo 3>FILE 3>&- 3>FILE"
  5121. * "echo 3>&- 3>FILE"
  5122. * No need for last redirect to insert
  5123. * another "need to close 3" indicator.
  5124. */
  5125. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5126. return;
  5127. }
  5128. }
  5129. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5130. sq->two_fd[i].orig_fd = fd;
  5131. sq->two_fd[i].moved_to = CLOSED;
  5132. }
  5133. static int
  5134. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5135. {
  5136. int i, new_fd;
  5137. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5138. avoid_fd = 9;
  5139. #if JOBS
  5140. if (fd == ttyfd) {
  5141. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5142. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5143. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5144. return 1; /* "we closed fd" */
  5145. }
  5146. #endif
  5147. /* Are we called from redirect(0)? E.g. redirect
  5148. * in a forked child. No need to save fds,
  5149. * we aren't going to use them anymore, ok to trash.
  5150. */
  5151. if (!sq)
  5152. return 0;
  5153. /* If this one of script's fds? */
  5154. if (fd != 0) {
  5155. struct parsefile *pf = g_parsefile;
  5156. while (pf) {
  5157. /* We skip fd == 0 case because of the following:
  5158. * $ ash # running ash interactively
  5159. * $ . ./script.sh
  5160. * and in script.sh: "exec 9>&0".
  5161. * Even though top-level pf_fd _is_ 0,
  5162. * it's still ok to use it: "read" builtin uses it,
  5163. * why should we cripple "exec" builtin?
  5164. */
  5165. if (fd == pf->pf_fd) {
  5166. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5167. return 1; /* "we closed fd" */
  5168. }
  5169. pf = pf->prev;
  5170. }
  5171. }
  5172. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5173. /* First: do we collide with some already moved fds? */
  5174. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5175. /* If we collide with an already moved fd... */
  5176. if (fd == sq->two_fd[i].moved_to) {
  5177. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5178. sq->two_fd[i].moved_to = new_fd;
  5179. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5180. if (new_fd < 0) /* what? */
  5181. xfunc_die();
  5182. return 0; /* "we did not close fd" */
  5183. }
  5184. if (fd == sq->two_fd[i].orig_fd) {
  5185. /* Example: echo Hello >/dev/null 1>&2 */
  5186. TRACE(("redirect_fd %d: already moved\n", fd));
  5187. return 0; /* "we did not close fd" */
  5188. }
  5189. }
  5190. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5191. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5192. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5193. if (new_fd < 0) {
  5194. if (errno != EBADF)
  5195. xfunc_die();
  5196. /* new_fd = CLOSED; - already is -1 */
  5197. }
  5198. sq->two_fd[i].moved_to = new_fd;
  5199. sq->two_fd[i].orig_fd = fd;
  5200. /* if we move stderr, let "set -x" code know */
  5201. if (fd == preverrout_fd)
  5202. preverrout_fd = new_fd;
  5203. return 0; /* "we did not close fd" */
  5204. }
  5205. static int
  5206. internally_opened_fd(int fd, struct redirtab *sq)
  5207. {
  5208. int i;
  5209. #if JOBS
  5210. if (fd == ttyfd)
  5211. return 1;
  5212. #endif
  5213. /* If this one of script's fds? */
  5214. if (fd != 0) {
  5215. struct parsefile *pf = g_parsefile;
  5216. while (pf) {
  5217. if (fd == pf->pf_fd)
  5218. return 1;
  5219. pf = pf->prev;
  5220. }
  5221. }
  5222. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5223. if (fd == sq->two_fd[i].moved_to)
  5224. return 1;
  5225. }
  5226. return 0;
  5227. }
  5228. /*
  5229. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5230. * old file descriptors are stashed away so that the redirection can be
  5231. * undone by calling popredir.
  5232. */
  5233. /* flags passed to redirect */
  5234. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5235. static void
  5236. redirect(union node *redir, int flags)
  5237. {
  5238. struct redirtab *sv;
  5239. if (!redir)
  5240. return;
  5241. sv = NULL;
  5242. INT_OFF;
  5243. if (flags & REDIR_PUSH)
  5244. sv = redirlist;
  5245. do {
  5246. int fd;
  5247. int newfd;
  5248. int close_fd;
  5249. int closed;
  5250. fd = redir->nfile.fd;
  5251. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5252. //bb_error_msg("doing %d > %d", fd, newfd);
  5253. newfd = redir->ndup.dupfd;
  5254. close_fd = -1;
  5255. } else {
  5256. newfd = openredirect(redir); /* always >= 0 */
  5257. if (fd == newfd) {
  5258. /* open() gave us precisely the fd we wanted.
  5259. * This means that this fd was not busy
  5260. * (not opened to anywhere).
  5261. * Remember to close it on restore:
  5262. */
  5263. add_squirrel_closed(sv, fd);
  5264. continue;
  5265. }
  5266. close_fd = newfd;
  5267. }
  5268. if (fd == newfd)
  5269. continue;
  5270. /* if "N>FILE": move newfd to fd */
  5271. /* if "N>&M": dup newfd to fd */
  5272. /* if "N>&-": close fd (newfd is -1) */
  5273. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5274. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5275. if (newfd == -1) {
  5276. /* "N>&-" means "close me" */
  5277. if (!closed) {
  5278. /* ^^^ optimization: saving may already
  5279. * have closed it. If not... */
  5280. close(fd);
  5281. }
  5282. } else {
  5283. /* if newfd is a script fd or saved fd, simulate EBADF */
  5284. if (internally_opened_fd(newfd, sv)) {
  5285. errno = EBADF;
  5286. ash_msg_and_raise_perror("%d", newfd);
  5287. }
  5288. dup2_or_raise(newfd, fd);
  5289. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5290. close(close_fd);
  5291. #if BASH_REDIR_OUTPUT
  5292. if (redir->nfile.type == NTO2 && fd == 1) {
  5293. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5294. fd = 2;
  5295. newfd = 1;
  5296. close_fd = -1;
  5297. goto redirect_more;
  5298. }
  5299. #endif
  5300. }
  5301. } while ((redir = redir->nfile.next) != NULL);
  5302. INT_ON;
  5303. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5304. #define REDIR_SAVEFD2 0
  5305. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5306. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5307. // not only for calls with flags containing REDIR_SAVEFD2.
  5308. // We do this unconditionally (see save_fd_on_redirect()).
  5309. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5310. // preverrout_fd = copied_fd2;
  5311. }
  5312. static int
  5313. redirectsafe(union node *redir, int flags)
  5314. {
  5315. int err;
  5316. volatile int saveint;
  5317. struct jmploc *volatile savehandler = exception_handler;
  5318. struct jmploc jmploc;
  5319. SAVE_INT(saveint);
  5320. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5321. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5322. if (!err) {
  5323. exception_handler = &jmploc;
  5324. redirect(redir, flags);
  5325. }
  5326. exception_handler = savehandler;
  5327. if (err && exception_type != EXERROR)
  5328. longjmp(exception_handler->loc, 1);
  5329. RESTORE_INT(saveint);
  5330. return err;
  5331. }
  5332. static struct redirtab*
  5333. pushredir(union node *redir)
  5334. {
  5335. struct redirtab *sv;
  5336. int i;
  5337. if (!redir)
  5338. return redirlist;
  5339. i = 0;
  5340. do {
  5341. i++;
  5342. #if BASH_REDIR_OUTPUT
  5343. if (redir->nfile.type == NTO2)
  5344. i++;
  5345. #endif
  5346. redir = redir->nfile.next;
  5347. } while (redir);
  5348. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5349. sv->pair_count = i;
  5350. while (--i >= 0)
  5351. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5352. sv->next = redirlist;
  5353. redirlist = sv;
  5354. return sv->next;
  5355. }
  5356. /*
  5357. * Undo the effects of the last redirection.
  5358. */
  5359. static void
  5360. popredir(int drop)
  5361. {
  5362. struct redirtab *rp;
  5363. int i;
  5364. if (redirlist == NULL)
  5365. return;
  5366. INT_OFF;
  5367. rp = redirlist;
  5368. for (i = 0; i < rp->pair_count; i++) {
  5369. int fd = rp->two_fd[i].orig_fd;
  5370. int copy = rp->two_fd[i].moved_to;
  5371. if (copy == CLOSED) {
  5372. if (!drop)
  5373. close(fd);
  5374. continue;
  5375. }
  5376. if (copy != EMPTY) {
  5377. if (!drop) {
  5378. /*close(fd);*/
  5379. dup2_or_raise(copy, fd);
  5380. }
  5381. close(copy);
  5382. }
  5383. }
  5384. redirlist = rp->next;
  5385. free(rp);
  5386. INT_ON;
  5387. }
  5388. static void
  5389. unwindredir(struct redirtab *stop)
  5390. {
  5391. while (redirlist != stop)
  5392. popredir(/*drop:*/ 0);
  5393. }
  5394. /* ============ Routines to expand arguments to commands
  5395. *
  5396. * We have to deal with backquotes, shell variables, and file metacharacters.
  5397. */
  5398. #if ENABLE_FEATURE_SH_MATH
  5399. static arith_t
  5400. ash_arith(const char *s)
  5401. {
  5402. arith_state_t math_state;
  5403. arith_t result;
  5404. math_state.lookupvar = lookupvar;
  5405. math_state.setvar = setvar0;
  5406. //math_state.endofname = endofname;
  5407. INT_OFF;
  5408. result = arith(&math_state, s);
  5409. if (math_state.errmsg)
  5410. ash_msg_and_raise_error(math_state.errmsg);
  5411. INT_ON;
  5412. return result;
  5413. }
  5414. #endif
  5415. #if BASH_SUBSTR
  5416. # if ENABLE_FEATURE_SH_MATH
  5417. static int substr_atoi(const char *s)
  5418. {
  5419. arith_t t = ash_arith(s);
  5420. if (sizeof(t) > sizeof(int)) {
  5421. /* clamp very large or very large negative nums for ${v:N:M}:
  5422. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5423. */
  5424. if (t > INT_MAX)
  5425. t = INT_MAX;
  5426. if (t < INT_MIN)
  5427. t = INT_MIN;
  5428. }
  5429. return t;
  5430. }
  5431. # else
  5432. # define substr_atoi(s) number(s)
  5433. # endif
  5434. #endif
  5435. /*
  5436. * expandarg flags
  5437. */
  5438. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5439. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5440. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5441. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5442. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5443. * POSIX says for this case:
  5444. * Pathname expansion shall not be performed on the word by a
  5445. * non-interactive shell; an interactive shell may perform it, but shall
  5446. * do so only when the expansion would result in one word.
  5447. * Currently, our code complies to the above rule by never globbing
  5448. * redirection filenames.
  5449. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5450. * (this means that on a typical Linux distro, bash almost always
  5451. * performs globbing, and thus diverges from what we do).
  5452. */
  5453. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5454. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5455. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5456. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5457. /*
  5458. * rmescape() flags
  5459. */
  5460. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5461. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5462. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5463. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5464. /* Add CTLESC when necessary. */
  5465. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5466. /* Do not skip NUL characters. */
  5467. #define QUOTES_KEEPNUL EXP_TILDE
  5468. /*
  5469. * Structure specifying which parts of the string should be searched
  5470. * for IFS characters.
  5471. */
  5472. struct ifsregion {
  5473. struct ifsregion *next; /* next region in list */
  5474. int begoff; /* offset of start of region */
  5475. int endoff; /* offset of end of region */
  5476. int nulonly; /* search for nul bytes only */
  5477. };
  5478. struct arglist {
  5479. struct strlist *list;
  5480. struct strlist **lastp;
  5481. };
  5482. /* output of current string */
  5483. static char *expdest;
  5484. /* list of back quote expressions */
  5485. static struct nodelist *argbackq;
  5486. /* first struct in list of ifs regions */
  5487. static struct ifsregion ifsfirst;
  5488. /* last struct in list */
  5489. static struct ifsregion *ifslastp;
  5490. /* holds expanded arg list */
  5491. static struct arglist exparg;
  5492. /*
  5493. * Our own itoa().
  5494. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5495. */
  5496. static int
  5497. cvtnum(arith_t num)
  5498. {
  5499. int len;
  5500. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5501. len = sizeof(arith_t) * 3;
  5502. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5503. if (sizeof(arith_t) < 4) len += 2;
  5504. expdest = makestrspace(len, expdest);
  5505. len = fmtstr(expdest, len, ARITH_FMT, num);
  5506. STADJUST(len, expdest);
  5507. return len;
  5508. }
  5509. /*
  5510. * Break the argument string into pieces based upon IFS and add the
  5511. * strings to the argument list. The regions of the string to be
  5512. * searched for IFS characters have been stored by recordregion.
  5513. */
  5514. static void
  5515. ifsbreakup(char *string, struct arglist *arglist)
  5516. {
  5517. struct ifsregion *ifsp;
  5518. struct strlist *sp;
  5519. char *start;
  5520. char *p;
  5521. char *q;
  5522. const char *ifs, *realifs;
  5523. int ifsspc;
  5524. int nulonly;
  5525. start = string;
  5526. if (ifslastp != NULL) {
  5527. ifsspc = 0;
  5528. nulonly = 0;
  5529. realifs = ifsset() ? ifsval() : defifs;
  5530. ifsp = &ifsfirst;
  5531. do {
  5532. int afternul;
  5533. p = string + ifsp->begoff;
  5534. afternul = nulonly;
  5535. nulonly = ifsp->nulonly;
  5536. ifs = nulonly ? nullstr : realifs;
  5537. ifsspc = 0;
  5538. while (p < string + ifsp->endoff) {
  5539. q = p;
  5540. if ((unsigned char)*p == CTLESC)
  5541. p++;
  5542. if (!strchr(ifs, *p)) {
  5543. p++;
  5544. continue;
  5545. }
  5546. if (!(afternul || nulonly))
  5547. ifsspc = (strchr(defifs, *p) != NULL);
  5548. /* Ignore IFS whitespace at start */
  5549. if (q == start && ifsspc) {
  5550. p++;
  5551. start = p;
  5552. continue;
  5553. }
  5554. *q = '\0';
  5555. sp = stzalloc(sizeof(*sp));
  5556. sp->text = start;
  5557. *arglist->lastp = sp;
  5558. arglist->lastp = &sp->next;
  5559. p++;
  5560. if (!nulonly) {
  5561. for (;;) {
  5562. if (p >= string + ifsp->endoff) {
  5563. break;
  5564. }
  5565. q = p;
  5566. if ((unsigned char)*p == CTLESC)
  5567. p++;
  5568. if (strchr(ifs, *p) == NULL) {
  5569. p = q;
  5570. break;
  5571. }
  5572. if (strchr(defifs, *p) == NULL) {
  5573. if (ifsspc) {
  5574. p++;
  5575. ifsspc = 0;
  5576. } else {
  5577. p = q;
  5578. break;
  5579. }
  5580. } else
  5581. p++;
  5582. }
  5583. }
  5584. start = p;
  5585. } /* while */
  5586. ifsp = ifsp->next;
  5587. } while (ifsp != NULL);
  5588. if (nulonly)
  5589. goto add;
  5590. }
  5591. if (!*start)
  5592. return;
  5593. add:
  5594. sp = stzalloc(sizeof(*sp));
  5595. sp->text = start;
  5596. *arglist->lastp = sp;
  5597. arglist->lastp = &sp->next;
  5598. }
  5599. static void
  5600. ifsfree(void)
  5601. {
  5602. struct ifsregion *p = ifsfirst.next;
  5603. if (!p)
  5604. goto out;
  5605. INT_OFF;
  5606. do {
  5607. struct ifsregion *ifsp;
  5608. ifsp = p->next;
  5609. free(p);
  5610. p = ifsp;
  5611. } while (p);
  5612. ifsfirst.next = NULL;
  5613. INT_ON;
  5614. out:
  5615. ifslastp = NULL;
  5616. }
  5617. static size_t
  5618. esclen(const char *start, const char *p)
  5619. {
  5620. size_t esc = 0;
  5621. while (p > start && (unsigned char)*--p == CTLESC) {
  5622. esc++;
  5623. }
  5624. return esc;
  5625. }
  5626. /*
  5627. * Remove any CTLESC characters from a string.
  5628. */
  5629. #if !BASH_PATTERN_SUBST
  5630. #define rmescapes(str, flag, slash_position) \
  5631. rmescapes(str, flag)
  5632. #endif
  5633. static char *
  5634. rmescapes(char *str, int flag, int *slash_position)
  5635. {
  5636. static const char qchars[] ALIGN1 = {
  5637. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5638. char *p, *q, *r;
  5639. unsigned protect_against_glob;
  5640. unsigned globbing;
  5641. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5642. if (!p)
  5643. return str;
  5644. q = p;
  5645. r = str;
  5646. if (flag & RMESCAPE_ALLOC) {
  5647. size_t len = p - str;
  5648. size_t fulllen = len + strlen(p) + 1;
  5649. if (flag & RMESCAPE_GROW) {
  5650. int strloc = str - (char *)stackblock();
  5651. r = makestrspace(fulllen, expdest);
  5652. /* p and str may be invalidated by makestrspace */
  5653. str = (char *)stackblock() + strloc;
  5654. p = str + len;
  5655. } else if (flag & RMESCAPE_HEAP) {
  5656. r = ckmalloc(fulllen);
  5657. } else {
  5658. r = stalloc(fulllen);
  5659. }
  5660. q = r;
  5661. if (len > 0) {
  5662. q = (char *)mempcpy(q, str, len);
  5663. }
  5664. }
  5665. globbing = flag & RMESCAPE_GLOB;
  5666. protect_against_glob = globbing;
  5667. while (*p) {
  5668. if ((unsigned char)*p == CTLQUOTEMARK) {
  5669. // Note: protect_against_glob only affect whether
  5670. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5671. p++;
  5672. protect_against_glob = globbing;
  5673. continue;
  5674. }
  5675. if (*p == '\\') {
  5676. /* naked back slash */
  5677. protect_against_glob = 0;
  5678. goto copy;
  5679. }
  5680. if ((unsigned char)*p == CTLESC) {
  5681. p++;
  5682. #if DEBUG
  5683. if (*p == '\0')
  5684. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5685. #endif
  5686. if (protect_against_glob) {
  5687. /*
  5688. * We used to trust glob() and fnmatch() to eat
  5689. * superfluous escapes (\z where z has no
  5690. * special meaning anyway). But this causes
  5691. * bugs such as string of one greek letter rho
  5692. * (unicode-encoded as two bytes "cf,81")
  5693. * getting encoded as "cf,CTLESC,81"
  5694. * and here, converted to "cf,\,81" -
  5695. * which does not go well with some flavors
  5696. * of fnmatch() in unicode locales
  5697. * (for example, glibc <= 2.22).
  5698. *
  5699. * Lets add "\" only on the chars which need it.
  5700. * Testcases for less obvious chars are shown.
  5701. */
  5702. if (*p == '*'
  5703. || *p == '?'
  5704. || *p == '['
  5705. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5706. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5707. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5708. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5709. /* Some libc support [^negate], that's why "^" also needs love */
  5710. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5711. ) {
  5712. *q++ = '\\';
  5713. }
  5714. }
  5715. }
  5716. #if BASH_PATTERN_SUBST
  5717. else if (slash_position && p == str + *slash_position) {
  5718. /* stop handling globbing */
  5719. globbing = 0;
  5720. *slash_position = q - r;
  5721. slash_position = NULL;
  5722. }
  5723. #endif
  5724. protect_against_glob = globbing;
  5725. copy:
  5726. *q++ = *p++;
  5727. }
  5728. *q = '\0';
  5729. if (flag & RMESCAPE_GROW) {
  5730. expdest = r;
  5731. STADJUST(q - r + 1, expdest);
  5732. }
  5733. return r;
  5734. }
  5735. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5736. /*
  5737. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5738. *
  5739. * Returns an stalloced string.
  5740. */
  5741. static char *
  5742. preglob(const char *pattern, int flag)
  5743. {
  5744. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5745. }
  5746. /*
  5747. * Put a string on the stack.
  5748. */
  5749. static void
  5750. memtodest(const char *p, size_t len, int syntax, int quotes)
  5751. {
  5752. char *q;
  5753. if (!len)
  5754. return;
  5755. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5756. do {
  5757. unsigned char c = *p++;
  5758. if (c) {
  5759. if (quotes & QUOTES_ESC) {
  5760. int n = SIT(c, syntax);
  5761. if (n == CCTL
  5762. || (syntax != BASESYNTAX && n == CBACK)
  5763. ) {
  5764. USTPUTC(CTLESC, q);
  5765. }
  5766. }
  5767. } else if (!(quotes & QUOTES_KEEPNUL))
  5768. continue;
  5769. USTPUTC(c, q);
  5770. } while (--len);
  5771. expdest = q;
  5772. }
  5773. static size_t
  5774. strtodest(const char *p, int syntax, int quotes)
  5775. {
  5776. size_t len = strlen(p);
  5777. memtodest(p, len, syntax, quotes);
  5778. return len;
  5779. }
  5780. /*
  5781. * Record the fact that we have to scan this region of the
  5782. * string for IFS characters.
  5783. */
  5784. static void
  5785. recordregion(int start, int end, int nulonly)
  5786. {
  5787. struct ifsregion *ifsp;
  5788. if (ifslastp == NULL) {
  5789. ifsp = &ifsfirst;
  5790. } else {
  5791. INT_OFF;
  5792. ifsp = ckzalloc(sizeof(*ifsp));
  5793. /*ifsp->next = NULL; - ckzalloc did it */
  5794. ifslastp->next = ifsp;
  5795. INT_ON;
  5796. }
  5797. ifslastp = ifsp;
  5798. ifslastp->begoff = start;
  5799. ifslastp->endoff = end;
  5800. ifslastp->nulonly = nulonly;
  5801. }
  5802. static void
  5803. removerecordregions(int endoff)
  5804. {
  5805. if (ifslastp == NULL)
  5806. return;
  5807. if (ifsfirst.endoff > endoff) {
  5808. while (ifsfirst.next) {
  5809. struct ifsregion *ifsp;
  5810. INT_OFF;
  5811. ifsp = ifsfirst.next->next;
  5812. free(ifsfirst.next);
  5813. ifsfirst.next = ifsp;
  5814. INT_ON;
  5815. }
  5816. if (ifsfirst.begoff > endoff) {
  5817. ifslastp = NULL;
  5818. } else {
  5819. ifslastp = &ifsfirst;
  5820. ifsfirst.endoff = endoff;
  5821. }
  5822. return;
  5823. }
  5824. ifslastp = &ifsfirst;
  5825. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5826. ifslastp = ifslastp->next;
  5827. while (ifslastp->next) {
  5828. struct ifsregion *ifsp;
  5829. INT_OFF;
  5830. ifsp = ifslastp->next->next;
  5831. free(ifslastp->next);
  5832. ifslastp->next = ifsp;
  5833. INT_ON;
  5834. }
  5835. if (ifslastp->endoff > endoff)
  5836. ifslastp->endoff = endoff;
  5837. }
  5838. static char *
  5839. exptilde(char *startp, char *p, int flags)
  5840. {
  5841. unsigned char c;
  5842. char *name;
  5843. struct passwd *pw;
  5844. const char *home;
  5845. int quotes = flags & QUOTES_ESC;
  5846. name = p + 1;
  5847. while ((c = *++p) != '\0') {
  5848. switch (c) {
  5849. case CTLESC:
  5850. return startp;
  5851. case CTLQUOTEMARK:
  5852. return startp;
  5853. case ':':
  5854. if (flags & EXP_VARTILDE)
  5855. goto done;
  5856. break;
  5857. case '/':
  5858. case CTLENDVAR:
  5859. goto done;
  5860. }
  5861. }
  5862. done:
  5863. *p = '\0';
  5864. if (*name == '\0') {
  5865. home = lookupvar("HOME");
  5866. } else {
  5867. pw = getpwnam(name);
  5868. if (pw == NULL)
  5869. goto lose;
  5870. home = pw->pw_dir;
  5871. }
  5872. if (!home || !*home)
  5873. goto lose;
  5874. *p = c;
  5875. strtodest(home, SQSYNTAX, quotes);
  5876. return p;
  5877. lose:
  5878. *p = c;
  5879. return startp;
  5880. }
  5881. /*
  5882. * Execute a command inside back quotes. If it's a builtin command, we
  5883. * want to save its output in a block obtained from malloc. Otherwise
  5884. * we fork off a subprocess and get the output of the command via a pipe.
  5885. * Should be called with interrupts off.
  5886. */
  5887. struct backcmd { /* result of evalbackcmd */
  5888. int fd; /* file descriptor to read from */
  5889. int nleft; /* number of chars in buffer */
  5890. char *buf; /* buffer */
  5891. struct job *jp; /* job structure for command */
  5892. };
  5893. /* These forward decls are needed to use "eval" code for backticks handling: */
  5894. /* flags in argument to evaltree */
  5895. #define EV_EXIT 01 /* exit after evaluating tree */
  5896. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5897. static int evaltree(union node *, int);
  5898. /* An evaltree() which is known to never return.
  5899. * Used to use an alias:
  5900. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5901. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5902. */
  5903. static ALWAYS_INLINE NORETURN void
  5904. evaltreenr(union node *n, int flags)
  5905. {
  5906. evaltree(n, flags);
  5907. bb_unreachable(abort());
  5908. /* NOTREACHED */
  5909. }
  5910. static void FAST_FUNC
  5911. evalbackcmd(union node *n, struct backcmd *result)
  5912. {
  5913. int pip[2];
  5914. struct job *jp;
  5915. result->fd = -1;
  5916. result->buf = NULL;
  5917. result->nleft = 0;
  5918. result->jp = NULL;
  5919. if (n == NULL) {
  5920. goto out;
  5921. }
  5922. if (pipe(pip) < 0)
  5923. ash_msg_and_raise_perror("can't create pipe");
  5924. jp = makejob(/*n,*/ 1);
  5925. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5926. /* child */
  5927. FORCE_INT_ON;
  5928. close(pip[0]);
  5929. if (pip[1] != 1) {
  5930. /*close(1);*/
  5931. dup2_or_raise(pip[1], 1);
  5932. close(pip[1]);
  5933. }
  5934. /* TODO: eflag clearing makes the following not abort:
  5935. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5936. * which is what bash does (unless it is in POSIX mode).
  5937. * dash deleted "eflag = 0" line in the commit
  5938. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5939. * [EVAL] Don't clear eflag in evalbackcmd
  5940. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5941. */
  5942. eflag = 0;
  5943. ifsfree();
  5944. evaltreenr(n, EV_EXIT);
  5945. /* NOTREACHED */
  5946. }
  5947. /* parent */
  5948. close(pip[1]);
  5949. result->fd = pip[0];
  5950. result->jp = jp;
  5951. out:
  5952. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5953. result->fd, result->buf, result->nleft, result->jp));
  5954. }
  5955. /*
  5956. * Expand stuff in backwards quotes.
  5957. */
  5958. static void
  5959. expbackq(union node *cmd, int flag)
  5960. {
  5961. struct backcmd in;
  5962. int i;
  5963. char buf[128];
  5964. char *p;
  5965. char *dest;
  5966. int startloc;
  5967. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5968. struct stackmark smark;
  5969. INT_OFF;
  5970. startloc = expdest - (char *)stackblock();
  5971. pushstackmark(&smark, startloc);
  5972. evalbackcmd(cmd, &in);
  5973. popstackmark(&smark);
  5974. p = in.buf;
  5975. i = in.nleft;
  5976. if (i == 0)
  5977. goto read;
  5978. for (;;) {
  5979. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5980. read:
  5981. if (in.fd < 0)
  5982. break;
  5983. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5984. TRACE(("expbackq: read returns %d\n", i));
  5985. if (i <= 0)
  5986. break;
  5987. p = buf;
  5988. }
  5989. free(in.buf);
  5990. if (in.fd >= 0) {
  5991. close(in.fd);
  5992. back_exitstatus = waitforjob(in.jp);
  5993. }
  5994. INT_ON;
  5995. /* Eat all trailing newlines */
  5996. dest = expdest;
  5997. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5998. STUNPUTC(dest);
  5999. expdest = dest;
  6000. if (!(flag & EXP_QUOTED))
  6001. recordregion(startloc, dest - (char *)stackblock(), 0);
  6002. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6003. (int)((dest - (char *)stackblock()) - startloc),
  6004. (int)((dest - (char *)stackblock()) - startloc),
  6005. stackblock() + startloc));
  6006. }
  6007. #if ENABLE_FEATURE_SH_MATH
  6008. /*
  6009. * Expand arithmetic expression. Backup to start of expression,
  6010. * evaluate, place result in (backed up) result, adjust string position.
  6011. */
  6012. static void
  6013. expari(int flag)
  6014. {
  6015. char *p, *start;
  6016. int begoff;
  6017. int len;
  6018. /* ifsfree(); */
  6019. /*
  6020. * This routine is slightly over-complicated for
  6021. * efficiency. Next we scan backwards looking for the
  6022. * start of arithmetic.
  6023. */
  6024. start = stackblock();
  6025. p = expdest - 1;
  6026. *p = '\0';
  6027. p--;
  6028. while (1) {
  6029. int esc;
  6030. while ((unsigned char)*p != CTLARI) {
  6031. p--;
  6032. #if DEBUG
  6033. if (p < start) {
  6034. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  6035. }
  6036. #endif
  6037. }
  6038. esc = esclen(start, p);
  6039. if (!(esc % 2)) {
  6040. break;
  6041. }
  6042. p -= esc + 1;
  6043. }
  6044. begoff = p - start;
  6045. removerecordregions(begoff);
  6046. expdest = p;
  6047. if (flag & QUOTES_ESC)
  6048. rmescapes(p + 1, 0, NULL);
  6049. len = cvtnum(ash_arith(p + 1));
  6050. if (!(flag & EXP_QUOTED))
  6051. recordregion(begoff, begoff + len, 0);
  6052. }
  6053. #endif
  6054. /* argstr needs it */
  6055. static char *evalvar(char *p, int flags);
  6056. /*
  6057. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6058. * characters to allow for further processing. Otherwise treat
  6059. * $@ like $* since no splitting will be performed.
  6060. */
  6061. static void
  6062. argstr(char *p, int flags)
  6063. {
  6064. static const char spclchars[] ALIGN1 = {
  6065. '=',
  6066. ':',
  6067. CTLQUOTEMARK,
  6068. CTLENDVAR,
  6069. CTLESC,
  6070. CTLVAR,
  6071. CTLBACKQ,
  6072. #if ENABLE_FEATURE_SH_MATH
  6073. CTLENDARI,
  6074. #endif
  6075. '\0'
  6076. };
  6077. const char *reject = spclchars;
  6078. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6079. int inquotes;
  6080. size_t length;
  6081. int startloc;
  6082. if (!(flags & EXP_VARTILDE)) {
  6083. reject += 2;
  6084. } else if (flags & EXP_VARTILDE2) {
  6085. reject++;
  6086. }
  6087. inquotes = 0;
  6088. length = 0;
  6089. if (flags & EXP_TILDE) {
  6090. char *q;
  6091. flags &= ~EXP_TILDE;
  6092. tilde:
  6093. q = p;
  6094. if (*q == '~')
  6095. p = exptilde(p, q, flags);
  6096. }
  6097. start:
  6098. startloc = expdest - (char *)stackblock();
  6099. for (;;) {
  6100. unsigned char c;
  6101. length += strcspn(p + length, reject);
  6102. c = p[length];
  6103. if (c) {
  6104. if (!(c & 0x80)
  6105. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6106. ) {
  6107. /* c == '=' || c == ':' || c == CTLENDARI */
  6108. length++;
  6109. }
  6110. }
  6111. if (length > 0) {
  6112. int newloc;
  6113. expdest = stack_nputstr(p, length, expdest);
  6114. newloc = expdest - (char *)stackblock();
  6115. if (breakall && !inquotes && newloc > startloc) {
  6116. recordregion(startloc, newloc, 0);
  6117. }
  6118. startloc = newloc;
  6119. }
  6120. p += length + 1;
  6121. length = 0;
  6122. switch (c) {
  6123. case '\0':
  6124. goto breakloop;
  6125. case '=':
  6126. if (flags & EXP_VARTILDE2) {
  6127. p--;
  6128. continue;
  6129. }
  6130. flags |= EXP_VARTILDE2;
  6131. reject++;
  6132. /* fall through */
  6133. case ':':
  6134. /*
  6135. * sort of a hack - expand tildes in variable
  6136. * assignments (after the first '=' and after ':'s).
  6137. */
  6138. if (*--p == '~') {
  6139. goto tilde;
  6140. }
  6141. continue;
  6142. }
  6143. switch (c) {
  6144. case CTLENDVAR: /* ??? */
  6145. goto breakloop;
  6146. case CTLQUOTEMARK:
  6147. /* "$@" syntax adherence hack */
  6148. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6149. p = evalvar(p + 1, flags | EXP_QUOTED) + 1;
  6150. goto start;
  6151. }
  6152. inquotes ^= EXP_QUOTED;
  6153. addquote:
  6154. if (flags & QUOTES_ESC) {
  6155. p--;
  6156. length++;
  6157. startloc++;
  6158. }
  6159. break;
  6160. case CTLESC:
  6161. startloc++;
  6162. length++;
  6163. goto addquote;
  6164. case CTLVAR:
  6165. TRACE(("argstr: evalvar('%s')\n", p));
  6166. p = evalvar(p, flags | inquotes);
  6167. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6168. goto start;
  6169. case CTLBACKQ:
  6170. expbackq(argbackq->n, flags | inquotes);
  6171. argbackq = argbackq->next;
  6172. goto start;
  6173. #if ENABLE_FEATURE_SH_MATH
  6174. case CTLENDARI:
  6175. p--;
  6176. expari(flags | inquotes);
  6177. goto start;
  6178. #endif
  6179. }
  6180. }
  6181. breakloop: ;
  6182. }
  6183. static char *
  6184. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6185. char *pattern, int quotes, int zero)
  6186. {
  6187. char *loc, *loc2;
  6188. char c;
  6189. loc = startp;
  6190. loc2 = rmesc;
  6191. do {
  6192. int match;
  6193. const char *s = loc2;
  6194. c = *loc2;
  6195. if (zero) {
  6196. *loc2 = '\0';
  6197. s = rmesc;
  6198. }
  6199. match = pmatch(pattern, s);
  6200. *loc2 = c;
  6201. if (match)
  6202. return loc;
  6203. if (quotes && (unsigned char)*loc == CTLESC)
  6204. loc++;
  6205. loc++;
  6206. loc2++;
  6207. } while (c);
  6208. return NULL;
  6209. }
  6210. static char *
  6211. scanright(char *startp, char *rmesc, char *rmescend,
  6212. char *pattern, int quotes, int match_at_start)
  6213. {
  6214. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6215. int try2optimize = match_at_start;
  6216. #endif
  6217. int esc = 0;
  6218. char *loc;
  6219. char *loc2;
  6220. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6221. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6222. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6223. * Logic:
  6224. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6225. * and on each iteration they go back two/one char until they reach the beginning.
  6226. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6227. */
  6228. /* TODO: document in what other circumstances we are called. */
  6229. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6230. int match;
  6231. char c = *loc2;
  6232. const char *s = loc2;
  6233. if (match_at_start) {
  6234. *loc2 = '\0';
  6235. s = rmesc;
  6236. }
  6237. match = pmatch(pattern, s);
  6238. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6239. *loc2 = c;
  6240. if (match)
  6241. return loc;
  6242. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6243. if (try2optimize) {
  6244. /* Maybe we can optimize this:
  6245. * if pattern ends with unescaped *, we can avoid checking
  6246. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6247. * it won't match truncated "raw_value_of_" strings too.
  6248. */
  6249. unsigned plen = strlen(pattern);
  6250. /* Does it end with "*"? */
  6251. if (plen != 0 && pattern[--plen] == '*') {
  6252. /* "xxxx*" is not escaped */
  6253. /* "xxx\*" is escaped */
  6254. /* "xx\\*" is not escaped */
  6255. /* "x\\\*" is escaped */
  6256. int slashes = 0;
  6257. while (plen != 0 && pattern[--plen] == '\\')
  6258. slashes++;
  6259. if (!(slashes & 1))
  6260. break; /* ends with unescaped "*" */
  6261. }
  6262. try2optimize = 0;
  6263. }
  6264. #endif
  6265. loc--;
  6266. if (quotes) {
  6267. if (--esc < 0) {
  6268. esc = esclen(startp, loc);
  6269. }
  6270. if (esc % 2) {
  6271. esc--;
  6272. loc--;
  6273. }
  6274. }
  6275. }
  6276. return NULL;
  6277. }
  6278. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6279. static void
  6280. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6281. {
  6282. const char *msg;
  6283. const char *tail;
  6284. tail = nullstr;
  6285. msg = "parameter not set";
  6286. if (umsg) {
  6287. if ((unsigned char)*end == CTLENDVAR) {
  6288. if (varflags & VSNUL)
  6289. tail = " or null";
  6290. } else {
  6291. msg = umsg;
  6292. }
  6293. }
  6294. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6295. }
  6296. static const char *
  6297. subevalvar(char *p, char *varname, int strloc, int subtype,
  6298. int startloc, int varflags, int flag)
  6299. {
  6300. struct nodelist *saveargbackq = argbackq;
  6301. int quotes = flag & QUOTES_ESC;
  6302. char *startp;
  6303. char *loc;
  6304. char *rmesc, *rmescend;
  6305. char *str;
  6306. int amount, resetloc;
  6307. int argstr_flags;
  6308. IF_BASH_PATTERN_SUBST(int workloc;)
  6309. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6310. IF_BASH_PATTERN_SUBST(char *repl;)
  6311. int zero;
  6312. char *(*scan)(char*, char*, char*, char*, int, int);
  6313. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6314. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6315. #if BASH_PATTERN_SUBST
  6316. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6317. * argstr() call expands possible variable references in pattern:
  6318. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6319. */
  6320. repl = NULL;
  6321. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6322. /* Find '/' and replace with NUL */
  6323. repl = p;
  6324. /* The pattern can't be empty.
  6325. * IOW: if the first char after "${v//" is a slash,
  6326. * it does not terminate the pattern - it's the first char of the pattern:
  6327. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6328. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6329. */
  6330. if (*repl == '/')
  6331. repl++;
  6332. for (;;) {
  6333. if (*repl == '\0') {
  6334. repl = NULL;
  6335. break;
  6336. }
  6337. if (*repl == '/') {
  6338. *repl = '\0';
  6339. break;
  6340. }
  6341. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6342. if ((unsigned char)*repl == CTLESC && repl[1])
  6343. repl++;
  6344. repl++;
  6345. }
  6346. }
  6347. #endif
  6348. argstr_flags = EXP_TILDE;
  6349. if (subtype != VSASSIGN
  6350. && subtype != VSQUESTION
  6351. #if BASH_SUBSTR
  6352. && subtype != VSSUBSTR
  6353. #endif
  6354. ) {
  6355. /* EXP_CASE keeps CTLESC's */
  6356. argstr_flags = EXP_TILDE | EXP_CASE;
  6357. }
  6358. argstr(p, argstr_flags);
  6359. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6360. #if BASH_PATTERN_SUBST
  6361. slash_pos = -1;
  6362. if (repl) {
  6363. slash_pos = expdest - ((char *)stackblock() + strloc);
  6364. STPUTC('/', expdest);
  6365. //bb_error_msg("repl+1:'%s'", repl + 1);
  6366. argstr(repl + 1, EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6367. *repl = '/';
  6368. }
  6369. #endif
  6370. STPUTC('\0', expdest);
  6371. argbackq = saveargbackq;
  6372. startp = (char *)stackblock() + startloc;
  6373. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6374. switch (subtype) {
  6375. case VSASSIGN:
  6376. setvar0(varname, startp);
  6377. amount = startp - expdest;
  6378. STADJUST(amount, expdest);
  6379. return startp;
  6380. case VSQUESTION:
  6381. varunset(p, varname, startp, varflags);
  6382. /* NOTREACHED */
  6383. #if BASH_SUBSTR
  6384. case VSSUBSTR: {
  6385. int pos, len, orig_len;
  6386. char *colon;
  6387. loc = str = stackblock() + strloc;
  6388. /* Read POS in ${var:POS:LEN} */
  6389. colon = strchr(loc, ':');
  6390. if (colon) *colon = '\0';
  6391. pos = substr_atoi(loc);
  6392. if (colon) *colon = ':';
  6393. /* Read LEN in ${var:POS:LEN} */
  6394. len = str - startp - 1;
  6395. /* *loc != '\0', guaranteed by parser */
  6396. if (quotes) {
  6397. char *ptr;
  6398. /* Adjust the length by the number of escapes */
  6399. for (ptr = startp; ptr < (str - 1); ptr++) {
  6400. if ((unsigned char)*ptr == CTLESC) {
  6401. len--;
  6402. ptr++;
  6403. }
  6404. }
  6405. }
  6406. orig_len = len;
  6407. if (*loc++ == ':') {
  6408. /* ${var::LEN} */
  6409. len = substr_atoi(loc);
  6410. } else {
  6411. /* Skip POS in ${var:POS:LEN} */
  6412. len = orig_len;
  6413. while (*loc && *loc != ':')
  6414. loc++;
  6415. if (*loc++ == ':')
  6416. len = substr_atoi(loc);
  6417. }
  6418. if (pos < 0) {
  6419. /* ${VAR:$((-n)):l} starts n chars from the end */
  6420. pos = orig_len + pos;
  6421. }
  6422. if ((unsigned)pos >= orig_len) {
  6423. /* apart from obvious ${VAR:999999:l},
  6424. * covers ${VAR:$((-9999999)):l} - result is ""
  6425. * (bash compat)
  6426. */
  6427. pos = 0;
  6428. len = 0;
  6429. }
  6430. if (len < 0) {
  6431. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6432. len = (orig_len - pos) + len;
  6433. }
  6434. if ((unsigned)len > (orig_len - pos))
  6435. len = orig_len - pos;
  6436. for (str = startp; pos; str++, pos--) {
  6437. if (quotes && (unsigned char)*str == CTLESC)
  6438. str++;
  6439. }
  6440. for (loc = startp; len; len--) {
  6441. if (quotes && (unsigned char)*str == CTLESC)
  6442. *loc++ = *str++;
  6443. *loc++ = *str++;
  6444. }
  6445. *loc = '\0';
  6446. amount = loc - expdest;
  6447. STADJUST(amount, expdest);
  6448. return loc;
  6449. }
  6450. #endif /* BASH_SUBSTR */
  6451. }
  6452. resetloc = expdest - (char *)stackblock();
  6453. #if BASH_PATTERN_SUBST
  6454. repl = NULL;
  6455. /* We'll comeback here if we grow the stack while handling
  6456. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6457. * stack will need rebasing, and we'll need to remove our work
  6458. * areas each time
  6459. */
  6460. restart:
  6461. #endif
  6462. amount = expdest - ((char *)stackblock() + resetloc);
  6463. STADJUST(-amount, expdest);
  6464. startp = (char *)stackblock() + startloc;
  6465. rmesc = startp;
  6466. rmescend = (char *)stackblock() + strloc;
  6467. //bb_error_msg("str7:'%s'", rmescend);
  6468. if (quotes) {
  6469. //TODO: how to handle slash_pos here if string changes (shortens?)
  6470. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6471. if (rmesc != startp) {
  6472. rmescend = expdest;
  6473. startp = (char *)stackblock() + startloc;
  6474. }
  6475. }
  6476. rmescend--;
  6477. str = (char *)stackblock() + strloc;
  6478. /*
  6479. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6480. * The result is a_\_z_c (not a\_\_z_c)!
  6481. *
  6482. * The search pattern and replace string treat backslashes differently!
  6483. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6484. * and string. It's only used on the first call.
  6485. */
  6486. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6487. rmescapes(str, RMESCAPE_GLOB,
  6488. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6489. );
  6490. #if BASH_PATTERN_SUBST
  6491. workloc = expdest - (char *)stackblock();
  6492. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6493. int len;
  6494. char *idx, *end;
  6495. if (!repl) {
  6496. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6497. repl = nullstr;
  6498. if (slash_pos >= 0) {
  6499. repl = str + slash_pos;
  6500. *repl++ = '\0';
  6501. }
  6502. }
  6503. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6504. /* If there's no pattern to match, return the expansion unmolested */
  6505. if (str[0] == '\0')
  6506. return NULL;
  6507. len = 0;
  6508. idx = startp;
  6509. end = str - 1;
  6510. while (idx < end) {
  6511. try_to_match:
  6512. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6513. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6514. if (!loc) {
  6515. /* No match, advance */
  6516. char *restart_detect = stackblock();
  6517. skip_matching:
  6518. STPUTC(*idx, expdest);
  6519. if (quotes && (unsigned char)*idx == CTLESC) {
  6520. idx++;
  6521. len++;
  6522. STPUTC(*idx, expdest);
  6523. }
  6524. if (stackblock() != restart_detect)
  6525. goto restart;
  6526. idx++;
  6527. len++;
  6528. rmesc++;
  6529. /* continue; - prone to quadratic behavior, smarter code: */
  6530. if (idx >= end)
  6531. break;
  6532. if (str[0] == '*') {
  6533. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6534. * it would never match "ong_string" etc, no point in trying.
  6535. */
  6536. goto skip_matching;
  6537. }
  6538. goto try_to_match;
  6539. }
  6540. if (subtype == VSREPLACEALL) {
  6541. while (idx < loc) {
  6542. if (quotes && (unsigned char)*idx == CTLESC)
  6543. idx++;
  6544. idx++;
  6545. rmesc++;
  6546. }
  6547. } else {
  6548. idx = loc;
  6549. }
  6550. //bb_error_msg("repl:'%s'", repl);
  6551. for (loc = (char*)repl; *loc; loc++) {
  6552. char *restart_detect = stackblock();
  6553. if (quotes && *loc == '\\') {
  6554. STPUTC(CTLESC, expdest);
  6555. len++;
  6556. }
  6557. STPUTC(*loc, expdest);
  6558. if (stackblock() != restart_detect)
  6559. goto restart;
  6560. len++;
  6561. }
  6562. if (subtype == VSREPLACE) {
  6563. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6564. while (*idx) {
  6565. char *restart_detect = stackblock();
  6566. STPUTC(*idx, expdest);
  6567. if (stackblock() != restart_detect)
  6568. goto restart;
  6569. len++;
  6570. idx++;
  6571. }
  6572. break;
  6573. }
  6574. }
  6575. /* We've put the replaced text into a buffer at workloc, now
  6576. * move it to the right place and adjust the stack.
  6577. */
  6578. STPUTC('\0', expdest);
  6579. startp = (char *)stackblock() + startloc;
  6580. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6581. //bb_error_msg("startp:'%s'", startp);
  6582. amount = expdest - (startp + len);
  6583. STADJUST(-amount, expdest);
  6584. return startp;
  6585. }
  6586. #endif /* BASH_PATTERN_SUBST */
  6587. subtype -= VSTRIMRIGHT;
  6588. #if DEBUG
  6589. if (subtype < 0 || subtype > 7)
  6590. abort();
  6591. #endif
  6592. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6593. zero = subtype >> 1;
  6594. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6595. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6596. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6597. if (loc) {
  6598. if (zero) {
  6599. memmove(startp, loc, str - loc);
  6600. loc = startp + (str - loc) - 1;
  6601. }
  6602. *loc = '\0';
  6603. amount = loc - expdest;
  6604. STADJUST(amount, expdest);
  6605. }
  6606. return loc;
  6607. }
  6608. /*
  6609. * Add the value of a specialized variable to the stack string.
  6610. * name parameter (examples):
  6611. * ash -c 'echo $1' name:'1='
  6612. * ash -c 'echo $qwe' name:'qwe='
  6613. * ash -c 'echo $$' name:'$='
  6614. * ash -c 'echo ${$}' name:'$='
  6615. * ash -c 'echo ${$##q}' name:'$=q'
  6616. * ash -c 'echo ${#$}' name:'$='
  6617. * note: examples with bad shell syntax:
  6618. * ash -c 'echo ${#$1}' name:'$=1'
  6619. * ash -c 'echo ${#1#}' name:'1=#'
  6620. */
  6621. static NOINLINE ssize_t
  6622. varvalue(char *name, int varflags, int flags, int quoted)
  6623. {
  6624. const char *p;
  6625. int num;
  6626. int i;
  6627. ssize_t len = 0;
  6628. int sep;
  6629. int subtype = varflags & VSTYPE;
  6630. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6631. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6632. int syntax;
  6633. sep = (flags & EXP_FULL) << CHAR_BIT;
  6634. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6635. switch (*name) {
  6636. case '$':
  6637. num = rootpid;
  6638. goto numvar;
  6639. case '?':
  6640. num = exitstatus;
  6641. goto numvar;
  6642. case '#':
  6643. num = shellparam.nparam;
  6644. goto numvar;
  6645. case '!':
  6646. num = backgndpid;
  6647. if (num == 0)
  6648. return -1;
  6649. numvar:
  6650. len = cvtnum(num);
  6651. goto check_1char_name;
  6652. case '-':
  6653. expdest = makestrspace(NOPTS, expdest);
  6654. for (i = NOPTS - 1; i >= 0; i--) {
  6655. if (optlist[i] && optletters(i)) {
  6656. USTPUTC(optletters(i), expdest);
  6657. len++;
  6658. }
  6659. }
  6660. check_1char_name:
  6661. #if 0
  6662. /* handles cases similar to ${#$1} */
  6663. if (name[2] != '\0')
  6664. raise_error_syntax("bad substitution");
  6665. #endif
  6666. break;
  6667. case '@':
  6668. if (quoted && sep)
  6669. goto param;
  6670. /* fall through */
  6671. case '*': {
  6672. char **ap;
  6673. char sepc;
  6674. char c;
  6675. /* We will set c to 0 or ~0 depending on whether
  6676. * we're doing field splitting. We won't do field
  6677. * splitting if either we're quoted or sep is zero.
  6678. *
  6679. * Instead of testing (quoted || !sep) the following
  6680. * trick optimises away any branches by using the
  6681. * fact that EXP_QUOTED (which is the only bit that
  6682. * can be set in quoted) is the same as EXP_FULL <<
  6683. * CHAR_BIT (which is the only bit that can be set
  6684. * in sep).
  6685. */
  6686. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6687. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6688. #endif
  6689. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6690. sep &= ~quoted;
  6691. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6692. param:
  6693. sepc = sep;
  6694. ap = shellparam.p;
  6695. if (!ap)
  6696. return -1;
  6697. while ((p = *ap++) != NULL) {
  6698. len += strtodest(p, syntax, quotes);
  6699. if (*ap && sep) {
  6700. len++;
  6701. memtodest(&sepc, 1, syntax, quotes);
  6702. }
  6703. }
  6704. break;
  6705. } /* case '*' */
  6706. case '0':
  6707. case '1':
  6708. case '2':
  6709. case '3':
  6710. case '4':
  6711. case '5':
  6712. case '6':
  6713. case '7':
  6714. case '8':
  6715. case '9':
  6716. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6717. if (num < 0 || num > shellparam.nparam)
  6718. return -1;
  6719. p = num ? shellparam.p[num - 1] : arg0;
  6720. goto value;
  6721. default:
  6722. /* NB: name has form "VAR=..." */
  6723. p = lookupvar(name);
  6724. value:
  6725. if (!p)
  6726. return -1;
  6727. len = strtodest(p, syntax, quotes);
  6728. #if ENABLE_UNICODE_SUPPORT
  6729. if (subtype == VSLENGTH && len > 0) {
  6730. reinit_unicode_for_ash();
  6731. if (unicode_status == UNICODE_ON) {
  6732. STADJUST(-len, expdest);
  6733. discard = 0;
  6734. len = unicode_strlen(p);
  6735. }
  6736. }
  6737. #endif
  6738. break;
  6739. }
  6740. if (discard)
  6741. STADJUST(-len, expdest);
  6742. return len;
  6743. }
  6744. /*
  6745. * Expand a variable, and return a pointer to the next character in the
  6746. * input string.
  6747. */
  6748. static char *
  6749. evalvar(char *p, int flag)
  6750. {
  6751. char varflags;
  6752. char subtype;
  6753. int quoted;
  6754. char *var;
  6755. int patloc;
  6756. int startloc;
  6757. ssize_t varlen;
  6758. varflags = (unsigned char) *p++;
  6759. subtype = varflags & VSTYPE;
  6760. if (!subtype)
  6761. raise_error_syntax("bad substitution");
  6762. quoted = flag & EXP_QUOTED;
  6763. var = p;
  6764. startloc = expdest - (char *)stackblock();
  6765. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6766. again:
  6767. varlen = varvalue(var, varflags, flag, quoted);
  6768. if (varflags & VSNUL)
  6769. varlen--;
  6770. if (subtype == VSPLUS) {
  6771. varlen = -1 - varlen;
  6772. goto vsplus;
  6773. }
  6774. if (subtype == VSMINUS) {
  6775. vsplus:
  6776. if (varlen < 0) {
  6777. argstr(
  6778. p,
  6779. flag | EXP_TILDE | EXP_WORD
  6780. );
  6781. goto end;
  6782. }
  6783. goto record;
  6784. }
  6785. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6786. if (varlen >= 0)
  6787. goto record;
  6788. subevalvar(p, var, 0, subtype, startloc, varflags,
  6789. flag & ~QUOTES_ESC);
  6790. varflags &= ~VSNUL;
  6791. /*
  6792. * Remove any recorded regions beyond
  6793. * start of variable
  6794. */
  6795. removerecordregions(startloc);
  6796. goto again;
  6797. }
  6798. if (varlen < 0 && uflag)
  6799. varunset(p, var, 0, 0);
  6800. if (subtype == VSLENGTH) {
  6801. cvtnum(varlen > 0 ? varlen : 0);
  6802. goto record;
  6803. }
  6804. if (subtype == VSNORMAL) {
  6805. record:
  6806. if (quoted) {
  6807. quoted = *var == '@' && shellparam.nparam;
  6808. if (!quoted)
  6809. goto end;
  6810. }
  6811. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6812. goto end;
  6813. }
  6814. #if DEBUG
  6815. switch (subtype) {
  6816. case VSTRIMLEFT:
  6817. case VSTRIMLEFTMAX:
  6818. case VSTRIMRIGHT:
  6819. case VSTRIMRIGHTMAX:
  6820. #if BASH_SUBSTR
  6821. case VSSUBSTR:
  6822. #endif
  6823. #if BASH_PATTERN_SUBST
  6824. case VSREPLACE:
  6825. case VSREPLACEALL:
  6826. #endif
  6827. break;
  6828. default:
  6829. abort();
  6830. }
  6831. #endif
  6832. if (varlen >= 0) {
  6833. /*
  6834. * Terminate the string and start recording the pattern
  6835. * right after it
  6836. */
  6837. STPUTC('\0', expdest);
  6838. patloc = expdest - (char *)stackblock();
  6839. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6840. startloc, varflags, flag)) {
  6841. int amount = expdest - (
  6842. (char *)stackblock() + patloc - 1
  6843. );
  6844. STADJUST(-amount, expdest);
  6845. }
  6846. /* Remove any recorded regions beyond start of variable */
  6847. removerecordregions(startloc);
  6848. goto record;
  6849. }
  6850. end:
  6851. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6852. int nesting = 1;
  6853. for (;;) {
  6854. unsigned char c = *p++;
  6855. if (c == CTLESC)
  6856. p++;
  6857. else if (c == CTLBACKQ) {
  6858. if (varlen >= 0)
  6859. argbackq = argbackq->next;
  6860. } else if (c == CTLVAR) {
  6861. if ((*p++ & VSTYPE) != VSNORMAL)
  6862. nesting++;
  6863. } else if (c == CTLENDVAR) {
  6864. if (--nesting == 0)
  6865. break;
  6866. }
  6867. }
  6868. }
  6869. return p;
  6870. }
  6871. /*
  6872. * Add a file name to the list.
  6873. */
  6874. static void
  6875. addfname(const char *name)
  6876. {
  6877. struct strlist *sp;
  6878. sp = stzalloc(sizeof(*sp));
  6879. sp->text = sstrdup(name);
  6880. *exparg.lastp = sp;
  6881. exparg.lastp = &sp->next;
  6882. }
  6883. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6884. static int
  6885. hasmeta(const char *p)
  6886. {
  6887. static const char chars[] ALIGN1 = {
  6888. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6889. };
  6890. for (;;) {
  6891. p = strpbrk(p, chars);
  6892. if (!p)
  6893. break;
  6894. switch ((unsigned char)*p) {
  6895. case CTLQUOTEMARK:
  6896. for (;;) {
  6897. p++;
  6898. if ((unsigned char)*p == CTLQUOTEMARK)
  6899. break;
  6900. if ((unsigned char)*p == CTLESC)
  6901. p++;
  6902. if (*p == '\0') /* huh? */
  6903. return 0;
  6904. }
  6905. break;
  6906. case '\\':
  6907. case CTLESC:
  6908. p++;
  6909. if (*p == '\0')
  6910. return 0;
  6911. break;
  6912. case '[':
  6913. if (!strchr(p + 1, ']')) {
  6914. /* It's not a properly closed [] pattern,
  6915. * but other metas may follow. Continue checking.
  6916. * my[file* _is_ globbed by bash
  6917. * and matches filenames like "my[file1".
  6918. */
  6919. break;
  6920. }
  6921. /* fallthrough */
  6922. default:
  6923. /* case '*': */
  6924. /* case '?': */
  6925. return 1;
  6926. }
  6927. p++;
  6928. }
  6929. return 0;
  6930. }
  6931. /* If we want to use glob() from libc... */
  6932. #if !ENABLE_ASH_INTERNAL_GLOB
  6933. /* Add the result of glob() to the list */
  6934. static void
  6935. addglob(const glob_t *pglob)
  6936. {
  6937. char **p = pglob->gl_pathv;
  6938. do {
  6939. addfname(*p);
  6940. } while (*++p);
  6941. }
  6942. static void
  6943. expandmeta(struct strlist *str /*, int flag*/)
  6944. {
  6945. /* TODO - EXP_REDIR */
  6946. while (str) {
  6947. char *p;
  6948. glob_t pglob;
  6949. int i;
  6950. if (fflag)
  6951. goto nometa;
  6952. if (!hasmeta(str->text))
  6953. goto nometa;
  6954. INT_OFF;
  6955. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6956. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6957. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6958. //
  6959. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6960. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6961. // Which means you need to unescape the string, right? Not so fast:
  6962. // if there _is_ a file named "file\?" (with backslash), it is returned
  6963. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6964. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6965. //
  6966. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6967. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6968. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6969. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6970. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6971. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6972. i = glob(p, 0, NULL, &pglob);
  6973. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6974. if (p != str->text)
  6975. free(p);
  6976. switch (i) {
  6977. case 0:
  6978. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6979. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6980. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6981. goto nometa2;
  6982. #endif
  6983. addglob(&pglob);
  6984. globfree(&pglob);
  6985. INT_ON;
  6986. break;
  6987. case GLOB_NOMATCH:
  6988. //nometa2:
  6989. globfree(&pglob);
  6990. INT_ON;
  6991. nometa:
  6992. *exparg.lastp = str;
  6993. rmescapes(str->text, 0, NULL);
  6994. exparg.lastp = &str->next;
  6995. break;
  6996. default: /* GLOB_NOSPACE */
  6997. globfree(&pglob);
  6998. INT_ON;
  6999. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  7000. }
  7001. str = str->next;
  7002. }
  7003. }
  7004. #else
  7005. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7006. /*
  7007. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7008. */
  7009. typedef struct exp_t {
  7010. char *dir;
  7011. unsigned dir_max;
  7012. } exp_t;
  7013. static void
  7014. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7015. {
  7016. #define expdir exp->dir
  7017. #define expdir_max exp->dir_max
  7018. char *enddir = expdir + expdir_len;
  7019. char *p;
  7020. const char *cp;
  7021. char *start;
  7022. char *endname;
  7023. int metaflag;
  7024. struct stat statb;
  7025. DIR *dirp;
  7026. struct dirent *dp;
  7027. int atend;
  7028. int matchdot;
  7029. int esc;
  7030. metaflag = 0;
  7031. start = name;
  7032. for (p = name; esc = 0, *p; p += esc + 1) {
  7033. if (*p == '*' || *p == '?')
  7034. metaflag = 1;
  7035. else if (*p == '[') {
  7036. char *q = p + 1;
  7037. if (*q == '!')
  7038. q++;
  7039. for (;;) {
  7040. if (*q == '\\')
  7041. q++;
  7042. if (*q == '/' || *q == '\0')
  7043. break;
  7044. if (*++q == ']') {
  7045. metaflag = 1;
  7046. break;
  7047. }
  7048. }
  7049. } else {
  7050. if (*p == '\\' && p[1])
  7051. esc++;
  7052. if (p[esc] == '/') {
  7053. if (metaflag)
  7054. break;
  7055. start = p + esc + 1;
  7056. }
  7057. }
  7058. }
  7059. if (metaflag == 0) { /* we've reached the end of the file name */
  7060. if (!expdir_len)
  7061. return;
  7062. p = name;
  7063. do {
  7064. if (*p == '\\' && p[1])
  7065. p++;
  7066. *enddir++ = *p;
  7067. } while (*p++);
  7068. if (lstat(expdir, &statb) == 0)
  7069. addfname(expdir);
  7070. return;
  7071. }
  7072. endname = p;
  7073. if (name < start) {
  7074. p = name;
  7075. do {
  7076. if (*p == '\\' && p[1])
  7077. p++;
  7078. *enddir++ = *p++;
  7079. } while (p < start);
  7080. }
  7081. *enddir = '\0';
  7082. cp = expdir;
  7083. expdir_len = enddir - cp;
  7084. if (!expdir_len)
  7085. cp = ".";
  7086. dirp = opendir(cp);
  7087. if (dirp == NULL)
  7088. return;
  7089. if (*endname == 0) {
  7090. atend = 1;
  7091. } else {
  7092. atend = 0;
  7093. *endname = '\0';
  7094. endname += esc + 1;
  7095. }
  7096. name_len -= endname - name;
  7097. matchdot = 0;
  7098. p = start;
  7099. if (*p == '\\')
  7100. p++;
  7101. if (*p == '.')
  7102. matchdot++;
  7103. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7104. if (dp->d_name[0] == '.' && !matchdot)
  7105. continue;
  7106. if (pmatch(start, dp->d_name)) {
  7107. if (atend) {
  7108. strcpy(enddir, dp->d_name);
  7109. addfname(expdir);
  7110. } else {
  7111. unsigned offset;
  7112. unsigned len;
  7113. p = stpcpy(enddir, dp->d_name);
  7114. *p = '/';
  7115. offset = p - expdir + 1;
  7116. len = offset + name_len + NAME_MAX;
  7117. if (len > expdir_max) {
  7118. len += PATH_MAX;
  7119. expdir = ckrealloc(expdir, len);
  7120. expdir_max = len;
  7121. }
  7122. expmeta(exp, endname, name_len, offset);
  7123. enddir = expdir + expdir_len;
  7124. }
  7125. }
  7126. }
  7127. closedir(dirp);
  7128. if (!atend)
  7129. endname[-esc - 1] = esc ? '\\' : '/';
  7130. #undef expdir
  7131. #undef expdir_max
  7132. }
  7133. static struct strlist *
  7134. msort(struct strlist *list, int len)
  7135. {
  7136. struct strlist *p, *q = NULL;
  7137. struct strlist **lpp;
  7138. int half;
  7139. int n;
  7140. if (len <= 1)
  7141. return list;
  7142. half = len >> 1;
  7143. p = list;
  7144. for (n = half; --n >= 0;) {
  7145. q = p;
  7146. p = p->next;
  7147. }
  7148. q->next = NULL; /* terminate first half of list */
  7149. q = msort(list, half); /* sort first half of list */
  7150. p = msort(p, len - half); /* sort second half */
  7151. lpp = &list;
  7152. for (;;) {
  7153. #if ENABLE_LOCALE_SUPPORT
  7154. if (strcoll(p->text, q->text) < 0)
  7155. #else
  7156. if (strcmp(p->text, q->text) < 0)
  7157. #endif
  7158. {
  7159. *lpp = p;
  7160. lpp = &p->next;
  7161. p = *lpp;
  7162. if (p == NULL) {
  7163. *lpp = q;
  7164. break;
  7165. }
  7166. } else {
  7167. *lpp = q;
  7168. lpp = &q->next;
  7169. q = *lpp;
  7170. if (q == NULL) {
  7171. *lpp = p;
  7172. break;
  7173. }
  7174. }
  7175. }
  7176. return list;
  7177. }
  7178. /*
  7179. * Sort the results of file name expansion. It calculates the number of
  7180. * strings to sort and then calls msort (short for merge sort) to do the
  7181. * work.
  7182. */
  7183. static struct strlist *
  7184. expsort(struct strlist *str)
  7185. {
  7186. int len;
  7187. struct strlist *sp;
  7188. len = 0;
  7189. for (sp = str; sp; sp = sp->next)
  7190. len++;
  7191. return msort(str, len);
  7192. }
  7193. static void
  7194. expandmeta(struct strlist *str /*, int flag*/)
  7195. {
  7196. /* TODO - EXP_REDIR */
  7197. while (str) {
  7198. exp_t exp;
  7199. struct strlist **savelastp;
  7200. struct strlist *sp;
  7201. char *p;
  7202. unsigned len;
  7203. if (fflag)
  7204. goto nometa;
  7205. if (!hasmeta(str->text))
  7206. goto nometa;
  7207. savelastp = exparg.lastp;
  7208. INT_OFF;
  7209. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7210. len = strlen(p);
  7211. exp.dir_max = len + PATH_MAX;
  7212. exp.dir = ckmalloc(exp.dir_max);
  7213. expmeta(&exp, p, len, 0);
  7214. free(exp.dir);
  7215. if (p != str->text)
  7216. free(p);
  7217. INT_ON;
  7218. if (exparg.lastp == savelastp) {
  7219. /*
  7220. * no matches
  7221. */
  7222. nometa:
  7223. *exparg.lastp = str;
  7224. rmescapes(str->text, 0, NULL);
  7225. exparg.lastp = &str->next;
  7226. } else {
  7227. *exparg.lastp = NULL;
  7228. *savelastp = sp = expsort(*savelastp);
  7229. while (sp->next != NULL)
  7230. sp = sp->next;
  7231. exparg.lastp = &sp->next;
  7232. }
  7233. str = str->next;
  7234. }
  7235. }
  7236. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7237. /*
  7238. * Perform variable substitution and command substitution on an argument,
  7239. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7240. * perform splitting and file name expansion. When arglist is NULL, perform
  7241. * here document expansion.
  7242. */
  7243. static void
  7244. expandarg(union node *arg, struct arglist *arglist, int flag)
  7245. {
  7246. struct strlist *sp;
  7247. char *p;
  7248. argbackq = arg->narg.backquote;
  7249. STARTSTACKSTR(expdest);
  7250. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7251. argstr(arg->narg.text, flag);
  7252. p = _STPUTC('\0', expdest);
  7253. expdest = p - 1;
  7254. if (arglist == NULL) {
  7255. /* here document expanded */
  7256. goto out;
  7257. }
  7258. p = grabstackstr(p);
  7259. TRACE(("expandarg: p:'%s'\n", p));
  7260. exparg.lastp = &exparg.list;
  7261. /*
  7262. * TODO - EXP_REDIR
  7263. */
  7264. if (flag & EXP_FULL) {
  7265. ifsbreakup(p, &exparg);
  7266. *exparg.lastp = NULL;
  7267. exparg.lastp = &exparg.list;
  7268. expandmeta(exparg.list /*, flag*/);
  7269. } else {
  7270. sp = stzalloc(sizeof(*sp));
  7271. sp->text = p;
  7272. *exparg.lastp = sp;
  7273. exparg.lastp = &sp->next;
  7274. }
  7275. *exparg.lastp = NULL;
  7276. if (exparg.list) {
  7277. *arglist->lastp = exparg.list;
  7278. arglist->lastp = exparg.lastp;
  7279. }
  7280. out:
  7281. ifsfree();
  7282. }
  7283. /*
  7284. * Expand shell variables and backquotes inside a here document.
  7285. */
  7286. static void
  7287. expandhere(union node *arg, int fd)
  7288. {
  7289. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7290. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7291. }
  7292. /*
  7293. * Returns true if the pattern matches the string.
  7294. */
  7295. static int
  7296. patmatch(char *pattern, const char *string)
  7297. {
  7298. char *p = preglob(pattern, 0);
  7299. int r = pmatch(p, string);
  7300. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7301. return r;
  7302. }
  7303. /*
  7304. * See if a pattern matches in a case statement.
  7305. */
  7306. static int
  7307. casematch(union node *pattern, char *val)
  7308. {
  7309. struct stackmark smark;
  7310. int result;
  7311. setstackmark(&smark);
  7312. argbackq = pattern->narg.backquote;
  7313. STARTSTACKSTR(expdest);
  7314. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7315. STACKSTRNUL(expdest);
  7316. ifsfree();
  7317. result = patmatch(stackblock(), val);
  7318. popstackmark(&smark);
  7319. return result;
  7320. }
  7321. /* ============ find_command */
  7322. struct builtincmd {
  7323. const char *name;
  7324. int (*builtin)(int, char **) FAST_FUNC;
  7325. /* unsigned flags; */
  7326. };
  7327. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7328. /* "regular" builtins always take precedence over commands,
  7329. * regardless of PATH=....%builtin... position */
  7330. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7331. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7332. struct cmdentry {
  7333. smallint cmdtype; /* CMDxxx */
  7334. union param {
  7335. int index;
  7336. /* index >= 0 for commands without path (slashes) */
  7337. /* (TODO: what exactly does the value mean? PATH position?) */
  7338. /* index == -1 for commands with slashes */
  7339. /* index == (-2 - applet_no) for NOFORK applets */
  7340. const struct builtincmd *cmd;
  7341. struct funcnode *func;
  7342. } u;
  7343. };
  7344. /* values of cmdtype */
  7345. #define CMDUNKNOWN -1 /* no entry in table for command */
  7346. #define CMDNORMAL 0 /* command is an executable program */
  7347. #define CMDFUNCTION 1 /* command is a shell function */
  7348. #define CMDBUILTIN 2 /* command is a shell builtin */
  7349. /* action to find_command() */
  7350. #define DO_ERR 0x01 /* prints errors */
  7351. #define DO_ABS 0x02 /* checks absolute paths */
  7352. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7353. #define DO_ALTPATH 0x08 /* using alternate path */
  7354. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7355. static void find_command(char *, struct cmdentry *, int, const char *);
  7356. /* ============ Hashing commands */
  7357. /*
  7358. * When commands are first encountered, they are entered in a hash table.
  7359. * This ensures that a full path search will not have to be done for them
  7360. * on each invocation.
  7361. *
  7362. * We should investigate converting to a linear search, even though that
  7363. * would make the command name "hash" a misnomer.
  7364. */
  7365. struct tblentry {
  7366. struct tblentry *next; /* next entry in hash chain */
  7367. union param param; /* definition of builtin function */
  7368. smallint cmdtype; /* CMDxxx */
  7369. char rehash; /* if set, cd done since entry created */
  7370. char cmdname[1]; /* name of command */
  7371. };
  7372. static struct tblentry **cmdtable;
  7373. #define INIT_G_cmdtable() do { \
  7374. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7375. } while (0)
  7376. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7377. static void
  7378. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7379. {
  7380. #if ENABLE_FEATURE_SH_STANDALONE
  7381. if (applet_no >= 0) {
  7382. if (APPLET_IS_NOEXEC(applet_no)) {
  7383. clearenv();
  7384. while (*envp)
  7385. putenv(*envp++);
  7386. popredir(/*drop:*/ 1);
  7387. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7388. }
  7389. /* re-exec ourselves with the new arguments */
  7390. execve(bb_busybox_exec_path, argv, envp);
  7391. /* If they called chroot or otherwise made the binary no longer
  7392. * executable, fall through */
  7393. }
  7394. #endif
  7395. repeat:
  7396. #ifdef SYSV
  7397. do {
  7398. execve(cmd, argv, envp);
  7399. } while (errno == EINTR);
  7400. #else
  7401. execve(cmd, argv, envp);
  7402. #endif
  7403. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7404. /* Run "cmd" as a shell script:
  7405. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7406. * "If the execve() function fails with ENOEXEC, the shell
  7407. * shall execute a command equivalent to having a shell invoked
  7408. * with the command name as its first operand,
  7409. * with any remaining arguments passed to the new shell"
  7410. *
  7411. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7412. * just call ourselves.
  7413. *
  7414. * Note that bash reads ~80 chars of the file, and if it sees
  7415. * a zero byte before it sees newline, it doesn't try to
  7416. * interpret it, but fails with "cannot execute binary file"
  7417. * message and exit code 126. For one, this prevents attempts
  7418. * to interpret foreign ELF binaries as shell scripts.
  7419. */
  7420. argv[0] = (char*) cmd;
  7421. cmd = bb_busybox_exec_path;
  7422. /* NB: this is only possible because all callers of shellexec()
  7423. * ensure that the argv[-1] slot exists!
  7424. */
  7425. argv--;
  7426. argv[0] = (char*) "ash";
  7427. goto repeat;
  7428. }
  7429. }
  7430. /*
  7431. * Exec a program. Never returns. If you change this routine, you may
  7432. * have to change the find_command routine as well.
  7433. * argv[-1] must exist and be writable! See tryexec() for why.
  7434. */
  7435. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7436. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7437. {
  7438. char *cmdname;
  7439. int e;
  7440. char **envp;
  7441. int exerrno;
  7442. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7443. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7444. if (strchr(prog, '/') != NULL
  7445. #if ENABLE_FEATURE_SH_STANDALONE
  7446. || (applet_no = find_applet_by_name(prog)) >= 0
  7447. #endif
  7448. ) {
  7449. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7450. if (applet_no >= 0) {
  7451. /* We tried execing ourself, but it didn't work.
  7452. * Maybe /proc/self/exe doesn't exist?
  7453. * Try $PATH search.
  7454. */
  7455. goto try_PATH;
  7456. }
  7457. e = errno;
  7458. } else {
  7459. try_PATH:
  7460. e = ENOENT;
  7461. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7462. if (--idx < 0 && pathopt == NULL) {
  7463. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7464. if (errno != ENOENT && errno != ENOTDIR)
  7465. e = errno;
  7466. }
  7467. stunalloc(cmdname);
  7468. }
  7469. }
  7470. /* Map to POSIX errors */
  7471. switch (e) {
  7472. default:
  7473. exerrno = 126;
  7474. break;
  7475. case ELOOP:
  7476. case ENAMETOOLONG:
  7477. case ENOENT:
  7478. case ENOTDIR:
  7479. exerrno = 127;
  7480. break;
  7481. }
  7482. exitstatus = exerrno;
  7483. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7484. prog, e, suppress_int));
  7485. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7486. /* NOTREACHED */
  7487. }
  7488. static void
  7489. printentry(struct tblentry *cmdp)
  7490. {
  7491. int idx;
  7492. const char *path;
  7493. char *name;
  7494. idx = cmdp->param.index;
  7495. path = pathval();
  7496. do {
  7497. name = path_advance(&path, cmdp->cmdname);
  7498. stunalloc(name);
  7499. } while (--idx >= 0);
  7500. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7501. }
  7502. /*
  7503. * Clear out command entries. The argument specifies the first entry in
  7504. * PATH which has changed.
  7505. */
  7506. static void
  7507. clearcmdentry(int firstchange)
  7508. {
  7509. struct tblentry **tblp;
  7510. struct tblentry **pp;
  7511. struct tblentry *cmdp;
  7512. INT_OFF;
  7513. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7514. pp = tblp;
  7515. while ((cmdp = *pp) != NULL) {
  7516. if ((cmdp->cmdtype == CMDNORMAL &&
  7517. cmdp->param.index >= firstchange)
  7518. || (cmdp->cmdtype == CMDBUILTIN &&
  7519. builtinloc >= firstchange)
  7520. ) {
  7521. *pp = cmdp->next;
  7522. free(cmdp);
  7523. } else {
  7524. pp = &cmdp->next;
  7525. }
  7526. }
  7527. }
  7528. INT_ON;
  7529. }
  7530. /*
  7531. * Locate a command in the command hash table. If "add" is nonzero,
  7532. * add the command to the table if it is not already present. The
  7533. * variable "lastcmdentry" is set to point to the address of the link
  7534. * pointing to the entry, so that delete_cmd_entry can delete the
  7535. * entry.
  7536. *
  7537. * Interrupts must be off if called with add != 0.
  7538. */
  7539. static struct tblentry **lastcmdentry;
  7540. static struct tblentry *
  7541. cmdlookup(const char *name, int add)
  7542. {
  7543. unsigned int hashval;
  7544. const char *p;
  7545. struct tblentry *cmdp;
  7546. struct tblentry **pp;
  7547. p = name;
  7548. hashval = (unsigned char)*p << 4;
  7549. while (*p)
  7550. hashval += (unsigned char)*p++;
  7551. hashval &= 0x7FFF;
  7552. pp = &cmdtable[hashval % CMDTABLESIZE];
  7553. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7554. if (strcmp(cmdp->cmdname, name) == 0)
  7555. break;
  7556. pp = &cmdp->next;
  7557. }
  7558. if (add && cmdp == NULL) {
  7559. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7560. + strlen(name)
  7561. /* + 1 - already done because
  7562. * tblentry::cmdname is char[1] */);
  7563. /*cmdp->next = NULL; - ckzalloc did it */
  7564. cmdp->cmdtype = CMDUNKNOWN;
  7565. strcpy(cmdp->cmdname, name);
  7566. }
  7567. lastcmdentry = pp;
  7568. return cmdp;
  7569. }
  7570. /*
  7571. * Delete the command entry returned on the last lookup.
  7572. */
  7573. static void
  7574. delete_cmd_entry(void)
  7575. {
  7576. struct tblentry *cmdp;
  7577. INT_OFF;
  7578. cmdp = *lastcmdentry;
  7579. *lastcmdentry = cmdp->next;
  7580. if (cmdp->cmdtype == CMDFUNCTION)
  7581. freefunc(cmdp->param.func);
  7582. free(cmdp);
  7583. INT_ON;
  7584. }
  7585. /*
  7586. * Add a new command entry, replacing any existing command entry for
  7587. * the same name - except special builtins.
  7588. */
  7589. static void
  7590. addcmdentry(char *name, struct cmdentry *entry)
  7591. {
  7592. struct tblentry *cmdp;
  7593. cmdp = cmdlookup(name, 1);
  7594. if (cmdp->cmdtype == CMDFUNCTION) {
  7595. freefunc(cmdp->param.func);
  7596. }
  7597. cmdp->cmdtype = entry->cmdtype;
  7598. cmdp->param = entry->u;
  7599. cmdp->rehash = 0;
  7600. }
  7601. static int FAST_FUNC
  7602. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7603. {
  7604. struct tblentry **pp;
  7605. struct tblentry *cmdp;
  7606. int c;
  7607. struct cmdentry entry;
  7608. char *name;
  7609. if (nextopt("r") != '\0') {
  7610. clearcmdentry(0);
  7611. return 0;
  7612. }
  7613. if (*argptr == NULL) {
  7614. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7615. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7616. if (cmdp->cmdtype == CMDNORMAL)
  7617. printentry(cmdp);
  7618. }
  7619. }
  7620. return 0;
  7621. }
  7622. c = 0;
  7623. while ((name = *argptr) != NULL) {
  7624. cmdp = cmdlookup(name, 0);
  7625. if (cmdp != NULL
  7626. && (cmdp->cmdtype == CMDNORMAL
  7627. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7628. ) {
  7629. delete_cmd_entry();
  7630. }
  7631. find_command(name, &entry, DO_ERR, pathval());
  7632. if (entry.cmdtype == CMDUNKNOWN)
  7633. c = 1;
  7634. argptr++;
  7635. }
  7636. return c;
  7637. }
  7638. /*
  7639. * Called when a cd is done. Marks all commands so the next time they
  7640. * are executed they will be rehashed.
  7641. */
  7642. static void
  7643. hashcd(void)
  7644. {
  7645. struct tblentry **pp;
  7646. struct tblentry *cmdp;
  7647. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7648. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7649. if (cmdp->cmdtype == CMDNORMAL
  7650. || (cmdp->cmdtype == CMDBUILTIN
  7651. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7652. && builtinloc > 0)
  7653. ) {
  7654. cmdp->rehash = 1;
  7655. }
  7656. }
  7657. }
  7658. }
  7659. /*
  7660. * Fix command hash table when PATH changed.
  7661. * Called before PATH is changed. The argument is the new value of PATH;
  7662. * pathval() still returns the old value at this point.
  7663. * Called with interrupts off.
  7664. */
  7665. static void FAST_FUNC
  7666. changepath(const char *new)
  7667. {
  7668. const char *old;
  7669. int firstchange;
  7670. int idx;
  7671. int idx_bltin;
  7672. old = pathval();
  7673. firstchange = 9999; /* assume no change */
  7674. idx = 0;
  7675. idx_bltin = -1;
  7676. for (;;) {
  7677. if (*old != *new) {
  7678. firstchange = idx;
  7679. if ((*old == '\0' && *new == ':')
  7680. || (*old == ':' && *new == '\0')
  7681. ) {
  7682. firstchange++;
  7683. }
  7684. old = new; /* ignore subsequent differences */
  7685. }
  7686. if (*new == '\0')
  7687. break;
  7688. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7689. idx_bltin = idx;
  7690. if (*new == ':')
  7691. idx++;
  7692. new++;
  7693. old++;
  7694. }
  7695. if (builtinloc < 0 && idx_bltin >= 0)
  7696. builtinloc = idx_bltin; /* zap builtins */
  7697. if (builtinloc >= 0 && idx_bltin < 0)
  7698. firstchange = 0;
  7699. clearcmdentry(firstchange);
  7700. builtinloc = idx_bltin;
  7701. }
  7702. enum {
  7703. TEOF,
  7704. TNL,
  7705. TREDIR,
  7706. TWORD,
  7707. TSEMI,
  7708. TBACKGND,
  7709. TAND,
  7710. TOR,
  7711. TPIPE,
  7712. TLP,
  7713. TRP,
  7714. TENDCASE,
  7715. TENDBQUOTE,
  7716. TNOT,
  7717. TCASE,
  7718. TDO,
  7719. TDONE,
  7720. TELIF,
  7721. TELSE,
  7722. TESAC,
  7723. TFI,
  7724. TFOR,
  7725. #if BASH_FUNCTION
  7726. TFUNCTION,
  7727. #endif
  7728. TIF,
  7729. TIN,
  7730. TTHEN,
  7731. TUNTIL,
  7732. TWHILE,
  7733. TBEGIN,
  7734. TEND
  7735. };
  7736. typedef smallint token_id_t;
  7737. /* Nth bit indicates if token marks the end of a list */
  7738. enum {
  7739. tokendlist = 0
  7740. /* 0 */ | (1u << TEOF)
  7741. /* 1 */ | (0u << TNL)
  7742. /* 2 */ | (0u << TREDIR)
  7743. /* 3 */ | (0u << TWORD)
  7744. /* 4 */ | (0u << TSEMI)
  7745. /* 5 */ | (0u << TBACKGND)
  7746. /* 6 */ | (0u << TAND)
  7747. /* 7 */ | (0u << TOR)
  7748. /* 8 */ | (0u << TPIPE)
  7749. /* 9 */ | (0u << TLP)
  7750. /* 10 */ | (1u << TRP)
  7751. /* 11 */ | (1u << TENDCASE)
  7752. /* 12 */ | (1u << TENDBQUOTE)
  7753. /* 13 */ | (0u << TNOT)
  7754. /* 14 */ | (0u << TCASE)
  7755. /* 15 */ | (1u << TDO)
  7756. /* 16 */ | (1u << TDONE)
  7757. /* 17 */ | (1u << TELIF)
  7758. /* 18 */ | (1u << TELSE)
  7759. /* 19 */ | (1u << TESAC)
  7760. /* 20 */ | (1u << TFI)
  7761. /* 21 */ | (0u << TFOR)
  7762. #if BASH_FUNCTION
  7763. /* 22 */ | (0u << TFUNCTION)
  7764. #endif
  7765. /* 23 */ | (0u << TIF)
  7766. /* 24 */ | (0u << TIN)
  7767. /* 25 */ | (1u << TTHEN)
  7768. /* 26 */ | (0u << TUNTIL)
  7769. /* 27 */ | (0u << TWHILE)
  7770. /* 28 */ | (0u << TBEGIN)
  7771. /* 29 */ | (1u << TEND)
  7772. , /* thus far 29 bits used */
  7773. };
  7774. static const char *const tokname_array[] = {
  7775. "end of file",
  7776. "newline",
  7777. "redirection",
  7778. "word",
  7779. ";",
  7780. "&",
  7781. "&&",
  7782. "||",
  7783. "|",
  7784. "(",
  7785. ")",
  7786. ";;",
  7787. "`",
  7788. #define KWDOFFSET 13
  7789. /* the following are keywords */
  7790. "!",
  7791. "case",
  7792. "do",
  7793. "done",
  7794. "elif",
  7795. "else",
  7796. "esac",
  7797. "fi",
  7798. "for",
  7799. #if BASH_FUNCTION
  7800. "function",
  7801. #endif
  7802. "if",
  7803. "in",
  7804. "then",
  7805. "until",
  7806. "while",
  7807. "{",
  7808. "}",
  7809. };
  7810. /* Wrapper around strcmp for qsort/bsearch/... */
  7811. static int
  7812. pstrcmp(const void *a, const void *b)
  7813. {
  7814. return strcmp((char*)a, *(char**)b);
  7815. }
  7816. static const char *const *
  7817. findkwd(const char *s)
  7818. {
  7819. return bsearch(s, tokname_array + KWDOFFSET,
  7820. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7821. sizeof(tokname_array[0]), pstrcmp);
  7822. }
  7823. /*
  7824. * Locate and print what a word is...
  7825. */
  7826. static int
  7827. describe_command(char *command, const char *path, int describe_command_verbose)
  7828. {
  7829. struct cmdentry entry;
  7830. #if ENABLE_ASH_ALIAS
  7831. const struct alias *ap;
  7832. #endif
  7833. path = path ? path : pathval();
  7834. if (describe_command_verbose) {
  7835. out1str(command);
  7836. }
  7837. /* First look at the keywords */
  7838. if (findkwd(command)) {
  7839. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7840. goto out;
  7841. }
  7842. #if ENABLE_ASH_ALIAS
  7843. /* Then look at the aliases */
  7844. ap = lookupalias(command, 0);
  7845. if (ap != NULL) {
  7846. if (!describe_command_verbose) {
  7847. out1str("alias ");
  7848. printalias(ap);
  7849. return 0;
  7850. }
  7851. out1fmt(" is an alias for %s", ap->val);
  7852. goto out;
  7853. }
  7854. #endif
  7855. /* Brute force */
  7856. find_command(command, &entry, DO_ABS, path);
  7857. switch (entry.cmdtype) {
  7858. case CMDNORMAL: {
  7859. int j = entry.u.index;
  7860. char *p;
  7861. if (j < 0) {
  7862. p = command;
  7863. } else {
  7864. do {
  7865. p = path_advance(&path, command);
  7866. stunalloc(p);
  7867. } while (--j >= 0);
  7868. }
  7869. if (describe_command_verbose) {
  7870. out1fmt(" is %s", p);
  7871. } else {
  7872. out1str(p);
  7873. }
  7874. break;
  7875. }
  7876. case CMDFUNCTION:
  7877. if (describe_command_verbose) {
  7878. /*out1str(" is a shell function");*/
  7879. out1str(" is a function"); /* bash says this */
  7880. } else {
  7881. out1str(command);
  7882. }
  7883. break;
  7884. case CMDBUILTIN:
  7885. if (describe_command_verbose) {
  7886. out1fmt(" is a %sshell builtin",
  7887. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7888. "special " : nullstr
  7889. );
  7890. } else {
  7891. out1str(command);
  7892. }
  7893. break;
  7894. default:
  7895. if (describe_command_verbose) {
  7896. out1str(": not found\n");
  7897. }
  7898. return 127;
  7899. }
  7900. out:
  7901. out1str("\n");
  7902. return 0;
  7903. }
  7904. static int FAST_FUNC
  7905. typecmd(int argc UNUSED_PARAM, char **argv)
  7906. {
  7907. int i = 1;
  7908. int err = 0;
  7909. int verbose = 1;
  7910. /* type -p ... ? (we don't bother checking for 'p') */
  7911. if (argv[1] && argv[1][0] == '-') {
  7912. i++;
  7913. verbose = 0;
  7914. }
  7915. while (argv[i]) {
  7916. err |= describe_command(argv[i++], NULL, verbose);
  7917. }
  7918. return err;
  7919. }
  7920. #if ENABLE_ASH_CMDCMD
  7921. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7922. static char **
  7923. parse_command_args(char **argv, const char **path)
  7924. {
  7925. char *cp, c;
  7926. for (;;) {
  7927. cp = *++argv;
  7928. if (!cp)
  7929. return NULL;
  7930. if (*cp++ != '-')
  7931. break;
  7932. c = *cp++;
  7933. if (!c)
  7934. break;
  7935. if (c == '-' && !*cp) {
  7936. if (!*++argv)
  7937. return NULL;
  7938. break;
  7939. }
  7940. do {
  7941. switch (c) {
  7942. case 'p':
  7943. *path = bb_default_path;
  7944. break;
  7945. default:
  7946. /* run 'typecmd' for other options */
  7947. return NULL;
  7948. }
  7949. c = *cp++;
  7950. } while (c);
  7951. }
  7952. return argv;
  7953. }
  7954. static int FAST_FUNC
  7955. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7956. {
  7957. char *cmd;
  7958. int c;
  7959. enum {
  7960. VERIFY_BRIEF = 1,
  7961. VERIFY_VERBOSE = 2,
  7962. } verify = 0;
  7963. const char *path = NULL;
  7964. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7965. * never reaches this function.
  7966. */
  7967. while ((c = nextopt("pvV")) != '\0')
  7968. if (c == 'V')
  7969. verify |= VERIFY_VERBOSE;
  7970. else if (c == 'v')
  7971. /*verify |= VERIFY_BRIEF*/;
  7972. #if DEBUG
  7973. else if (c != 'p')
  7974. abort();
  7975. #endif
  7976. else
  7977. path = bb_default_path;
  7978. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7979. cmd = *argptr;
  7980. if (/*verify && */ cmd)
  7981. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7982. return 0;
  7983. }
  7984. #endif
  7985. /*static int funcblocksize; // size of structures in function */
  7986. /*static int funcstringsize; // size of strings in node */
  7987. static void *funcblock; /* block to allocate function from */
  7988. static char *funcstring_end; /* end of block to allocate strings from */
  7989. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7990. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7991. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7992. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7993. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7994. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7995. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7996. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7997. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7998. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7999. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8000. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  8001. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8002. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8003. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8004. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8005. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8006. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8007. #if BASH_REDIR_OUTPUT
  8008. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8009. #endif
  8010. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8011. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8012. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8013. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8014. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8015. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8016. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8017. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8018. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8019. };
  8020. static int calcsize(int funcblocksize, union node *n);
  8021. static int
  8022. sizenodelist(int funcblocksize, struct nodelist *lp)
  8023. {
  8024. while (lp) {
  8025. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8026. funcblocksize = calcsize(funcblocksize, lp->n);
  8027. lp = lp->next;
  8028. }
  8029. return funcblocksize;
  8030. }
  8031. static int
  8032. calcsize(int funcblocksize, union node *n)
  8033. {
  8034. if (n == NULL)
  8035. return funcblocksize;
  8036. funcblocksize += nodesize[n->type];
  8037. switch (n->type) {
  8038. case NCMD:
  8039. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8040. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8041. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8042. break;
  8043. case NPIPE:
  8044. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8045. break;
  8046. case NREDIR:
  8047. case NBACKGND:
  8048. case NSUBSHELL:
  8049. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8050. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8051. break;
  8052. case NAND:
  8053. case NOR:
  8054. case NSEMI:
  8055. case NWHILE:
  8056. case NUNTIL:
  8057. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8058. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8059. break;
  8060. case NIF:
  8061. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8062. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8063. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8064. break;
  8065. case NFOR:
  8066. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8067. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8068. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8069. break;
  8070. case NCASE:
  8071. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8072. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8073. break;
  8074. case NCLIST:
  8075. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8076. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8077. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8078. break;
  8079. case NDEFUN:
  8080. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8081. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8082. break;
  8083. case NARG:
  8084. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8085. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8086. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8087. break;
  8088. case NTO:
  8089. #if BASH_REDIR_OUTPUT
  8090. case NTO2:
  8091. #endif
  8092. case NCLOBBER:
  8093. case NFROM:
  8094. case NFROMTO:
  8095. case NAPPEND:
  8096. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8097. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8098. break;
  8099. case NTOFD:
  8100. case NFROMFD:
  8101. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8102. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8103. break;
  8104. case NHERE:
  8105. case NXHERE:
  8106. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8107. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8108. break;
  8109. case NNOT:
  8110. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8111. break;
  8112. };
  8113. return funcblocksize;
  8114. }
  8115. static char *
  8116. nodeckstrdup(char *s)
  8117. {
  8118. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8119. return strcpy(funcstring_end, s);
  8120. }
  8121. static union node *copynode(union node *);
  8122. static struct nodelist *
  8123. copynodelist(struct nodelist *lp)
  8124. {
  8125. struct nodelist *start;
  8126. struct nodelist **lpp;
  8127. lpp = &start;
  8128. while (lp) {
  8129. *lpp = funcblock;
  8130. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8131. (*lpp)->n = copynode(lp->n);
  8132. lp = lp->next;
  8133. lpp = &(*lpp)->next;
  8134. }
  8135. *lpp = NULL;
  8136. return start;
  8137. }
  8138. static union node *
  8139. copynode(union node *n)
  8140. {
  8141. union node *new;
  8142. if (n == NULL)
  8143. return NULL;
  8144. new = funcblock;
  8145. funcblock = (char *) funcblock + nodesize[n->type];
  8146. switch (n->type) {
  8147. case NCMD:
  8148. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8149. new->ncmd.args = copynode(n->ncmd.args);
  8150. new->ncmd.assign = copynode(n->ncmd.assign);
  8151. new->ncmd.linno = n->ncmd.linno;
  8152. break;
  8153. case NPIPE:
  8154. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8155. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8156. break;
  8157. case NREDIR:
  8158. case NBACKGND:
  8159. case NSUBSHELL:
  8160. new->nredir.redirect = copynode(n->nredir.redirect);
  8161. new->nredir.n = copynode(n->nredir.n);
  8162. new->nredir.linno = n->nredir.linno;
  8163. break;
  8164. case NAND:
  8165. case NOR:
  8166. case NSEMI:
  8167. case NWHILE:
  8168. case NUNTIL:
  8169. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8170. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8171. break;
  8172. case NIF:
  8173. new->nif.elsepart = copynode(n->nif.elsepart);
  8174. new->nif.ifpart = copynode(n->nif.ifpart);
  8175. new->nif.test = copynode(n->nif.test);
  8176. break;
  8177. case NFOR:
  8178. new->nfor.var = nodeckstrdup(n->nfor.var);
  8179. new->nfor.body = copynode(n->nfor.body);
  8180. new->nfor.args = copynode(n->nfor.args);
  8181. new->nfor.linno = n->nfor.linno;
  8182. break;
  8183. case NCASE:
  8184. new->ncase.cases = copynode(n->ncase.cases);
  8185. new->ncase.expr = copynode(n->ncase.expr);
  8186. new->ncase.linno = n->ncase.linno;
  8187. break;
  8188. case NCLIST:
  8189. new->nclist.body = copynode(n->nclist.body);
  8190. new->nclist.pattern = copynode(n->nclist.pattern);
  8191. new->nclist.next = copynode(n->nclist.next);
  8192. break;
  8193. case NDEFUN:
  8194. new->ndefun.body = copynode(n->ndefun.body);
  8195. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8196. new->ndefun.linno = n->ndefun.linno;
  8197. break;
  8198. case NARG:
  8199. new->narg.backquote = copynodelist(n->narg.backquote);
  8200. new->narg.text = nodeckstrdup(n->narg.text);
  8201. new->narg.next = copynode(n->narg.next);
  8202. break;
  8203. case NTO:
  8204. #if BASH_REDIR_OUTPUT
  8205. case NTO2:
  8206. #endif
  8207. case NCLOBBER:
  8208. case NFROM:
  8209. case NFROMTO:
  8210. case NAPPEND:
  8211. new->nfile.fname = copynode(n->nfile.fname);
  8212. new->nfile.fd = n->nfile.fd;
  8213. new->nfile.next = copynode(n->nfile.next);
  8214. break;
  8215. case NTOFD:
  8216. case NFROMFD:
  8217. new->ndup.vname = copynode(n->ndup.vname);
  8218. new->ndup.dupfd = n->ndup.dupfd;
  8219. new->ndup.fd = n->ndup.fd;
  8220. new->ndup.next = copynode(n->ndup.next);
  8221. break;
  8222. case NHERE:
  8223. case NXHERE:
  8224. new->nhere.doc = copynode(n->nhere.doc);
  8225. new->nhere.fd = n->nhere.fd;
  8226. new->nhere.next = copynode(n->nhere.next);
  8227. break;
  8228. case NNOT:
  8229. new->nnot.com = copynode(n->nnot.com);
  8230. break;
  8231. };
  8232. new->type = n->type;
  8233. return new;
  8234. }
  8235. /*
  8236. * Make a copy of a parse tree.
  8237. */
  8238. static struct funcnode *
  8239. copyfunc(union node *n)
  8240. {
  8241. struct funcnode *f;
  8242. size_t blocksize;
  8243. /*funcstringsize = 0;*/
  8244. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8245. f = ckzalloc(blocksize /* + funcstringsize */);
  8246. funcblock = (char *) f + offsetof(struct funcnode, n);
  8247. funcstring_end = (char *) f + blocksize;
  8248. copynode(n);
  8249. /* f->count = 0; - ckzalloc did it */
  8250. return f;
  8251. }
  8252. /*
  8253. * Define a shell function.
  8254. */
  8255. static void
  8256. defun(union node *func)
  8257. {
  8258. struct cmdentry entry;
  8259. INT_OFF;
  8260. entry.cmdtype = CMDFUNCTION;
  8261. entry.u.func = copyfunc(func);
  8262. addcmdentry(func->ndefun.text, &entry);
  8263. INT_ON;
  8264. }
  8265. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8266. #define SKIPBREAK (1 << 0)
  8267. #define SKIPCONT (1 << 1)
  8268. #define SKIPFUNC (1 << 2)
  8269. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8270. static int skipcount; /* number of levels to skip */
  8271. static int loopnest; /* current loop nesting level */
  8272. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8273. /* Forward decl way out to parsing code - dotrap needs it */
  8274. static int evalstring(char *s, int flags);
  8275. /* Called to execute a trap.
  8276. * Single callsite - at the end of evaltree().
  8277. * If we return non-zero, evaltree raises EXEXIT exception.
  8278. *
  8279. * Perhaps we should avoid entering new trap handlers
  8280. * while we are executing a trap handler. [is it a TODO?]
  8281. */
  8282. static void
  8283. dotrap(void)
  8284. {
  8285. uint8_t *g;
  8286. int sig;
  8287. uint8_t last_status;
  8288. if (!pending_sig)
  8289. return;
  8290. last_status = exitstatus;
  8291. pending_sig = 0;
  8292. barrier();
  8293. TRACE(("dotrap entered\n"));
  8294. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8295. char *p;
  8296. if (!*g)
  8297. continue;
  8298. if (evalskip) {
  8299. pending_sig = sig;
  8300. break;
  8301. }
  8302. p = trap[sig];
  8303. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8304. * don't upset it by resetting gotsig[SIGINT-1] */
  8305. if (sig == SIGINT && !p)
  8306. continue;
  8307. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8308. *g = 0;
  8309. if (!p)
  8310. continue;
  8311. evalstring(p, 0);
  8312. }
  8313. exitstatus = last_status;
  8314. TRACE(("dotrap returns\n"));
  8315. }
  8316. /* forward declarations - evaluation is fairly recursive business... */
  8317. static int evalloop(union node *, int);
  8318. static int evalfor(union node *, int);
  8319. static int evalcase(union node *, int);
  8320. static int evalsubshell(union node *, int);
  8321. static void expredir(union node *);
  8322. static int evalpipe(union node *, int);
  8323. static int evalcommand(union node *, int);
  8324. static int evalbltin(const struct builtincmd *, int, char **, int);
  8325. static void prehash(union node *);
  8326. /*
  8327. * Evaluate a parse tree. The value is left in the global variable
  8328. * exitstatus.
  8329. */
  8330. static int
  8331. evaltree(union node *n, int flags)
  8332. {
  8333. int checkexit = 0;
  8334. int (*evalfn)(union node *, int);
  8335. struct stackmark smark;
  8336. int status = 0;
  8337. setstackmark(&smark);
  8338. if (n == NULL) {
  8339. TRACE(("evaltree(NULL) called\n"));
  8340. goto out;
  8341. }
  8342. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8343. dotrap();
  8344. switch (n->type) {
  8345. default:
  8346. #if DEBUG
  8347. out1fmt("Node type = %d\n", n->type);
  8348. fflush_all();
  8349. break;
  8350. #endif
  8351. case NNOT:
  8352. status = !evaltree(n->nnot.com, EV_TESTED);
  8353. goto setstatus;
  8354. case NREDIR:
  8355. errlinno = lineno = n->nredir.linno;
  8356. if (funcline)
  8357. lineno -= funcline - 1;
  8358. expredir(n->nredir.redirect);
  8359. pushredir(n->nredir.redirect);
  8360. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8361. if (!status) {
  8362. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8363. }
  8364. if (n->nredir.redirect)
  8365. popredir(/*drop:*/ 0);
  8366. goto setstatus;
  8367. case NCMD:
  8368. evalfn = evalcommand;
  8369. checkexit:
  8370. if (eflag && !(flags & EV_TESTED))
  8371. checkexit = ~0;
  8372. goto calleval;
  8373. case NFOR:
  8374. evalfn = evalfor;
  8375. goto calleval;
  8376. case NWHILE:
  8377. case NUNTIL:
  8378. evalfn = evalloop;
  8379. goto calleval;
  8380. case NSUBSHELL:
  8381. case NBACKGND:
  8382. evalfn = evalsubshell;
  8383. goto checkexit;
  8384. case NPIPE:
  8385. evalfn = evalpipe;
  8386. goto checkexit;
  8387. case NCASE:
  8388. evalfn = evalcase;
  8389. goto calleval;
  8390. case NAND:
  8391. case NOR:
  8392. case NSEMI: {
  8393. #if NAND + 1 != NOR
  8394. #error NAND + 1 != NOR
  8395. #endif
  8396. #if NOR + 1 != NSEMI
  8397. #error NOR + 1 != NSEMI
  8398. #endif
  8399. unsigned is_or = n->type - NAND;
  8400. status = evaltree(
  8401. n->nbinary.ch1,
  8402. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8403. );
  8404. if ((!status) == is_or || evalskip)
  8405. break;
  8406. n = n->nbinary.ch2;
  8407. evaln:
  8408. evalfn = evaltree;
  8409. calleval:
  8410. status = evalfn(n, flags);
  8411. goto setstatus;
  8412. }
  8413. case NIF:
  8414. status = evaltree(n->nif.test, EV_TESTED);
  8415. if (evalskip)
  8416. break;
  8417. if (!status) {
  8418. n = n->nif.ifpart;
  8419. goto evaln;
  8420. }
  8421. if (n->nif.elsepart) {
  8422. n = n->nif.elsepart;
  8423. goto evaln;
  8424. }
  8425. status = 0;
  8426. goto setstatus;
  8427. case NDEFUN:
  8428. defun(n);
  8429. /* Not necessary. To test it:
  8430. * "false; f() { qwerty; }; echo $?" should print 0.
  8431. */
  8432. /* status = 0; */
  8433. setstatus:
  8434. exitstatus = status;
  8435. break;
  8436. }
  8437. out:
  8438. /* Order of checks below is important:
  8439. * signal handlers trigger before exit caused by "set -e".
  8440. */
  8441. dotrap();
  8442. if (checkexit & status)
  8443. raise_exception(EXEXIT);
  8444. if (flags & EV_EXIT)
  8445. raise_exception(EXEXIT);
  8446. popstackmark(&smark);
  8447. TRACE(("leaving evaltree (no interrupts)\n"));
  8448. return exitstatus;
  8449. }
  8450. static int
  8451. skiploop(void)
  8452. {
  8453. int skip = evalskip;
  8454. switch (skip) {
  8455. case 0:
  8456. break;
  8457. case SKIPBREAK:
  8458. case SKIPCONT:
  8459. if (--skipcount <= 0) {
  8460. evalskip = 0;
  8461. break;
  8462. }
  8463. skip = SKIPBREAK;
  8464. break;
  8465. }
  8466. return skip;
  8467. }
  8468. static int
  8469. evalloop(union node *n, int flags)
  8470. {
  8471. int skip;
  8472. int status;
  8473. loopnest++;
  8474. status = 0;
  8475. flags &= EV_TESTED;
  8476. do {
  8477. int i;
  8478. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8479. skip = skiploop();
  8480. if (skip == SKIPFUNC)
  8481. status = i;
  8482. if (skip)
  8483. continue;
  8484. if (n->type != NWHILE)
  8485. i = !i;
  8486. if (i != 0)
  8487. break;
  8488. status = evaltree(n->nbinary.ch2, flags);
  8489. skip = skiploop();
  8490. } while (!(skip & ~SKIPCONT));
  8491. loopnest--;
  8492. return status;
  8493. }
  8494. static int
  8495. evalfor(union node *n, int flags)
  8496. {
  8497. struct arglist arglist;
  8498. union node *argp;
  8499. struct strlist *sp;
  8500. int status = 0;
  8501. errlinno = lineno = n->ncase.linno;
  8502. if (funcline)
  8503. lineno -= funcline - 1;
  8504. arglist.list = NULL;
  8505. arglist.lastp = &arglist.list;
  8506. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8507. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8508. }
  8509. *arglist.lastp = NULL;
  8510. loopnest++;
  8511. flags &= EV_TESTED;
  8512. for (sp = arglist.list; sp; sp = sp->next) {
  8513. setvar0(n->nfor.var, sp->text);
  8514. status = evaltree(n->nfor.body, flags);
  8515. if (skiploop() & ~SKIPCONT)
  8516. break;
  8517. }
  8518. loopnest--;
  8519. return status;
  8520. }
  8521. static int
  8522. evalcase(union node *n, int flags)
  8523. {
  8524. union node *cp;
  8525. union node *patp;
  8526. struct arglist arglist;
  8527. int status = 0;
  8528. errlinno = lineno = n->ncase.linno;
  8529. if (funcline)
  8530. lineno -= funcline - 1;
  8531. arglist.list = NULL;
  8532. arglist.lastp = &arglist.list;
  8533. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8534. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8535. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8536. if (casematch(patp, arglist.list->text)) {
  8537. /* Ensure body is non-empty as otherwise
  8538. * EV_EXIT may prevent us from setting the
  8539. * exit status.
  8540. */
  8541. if (evalskip == 0 && cp->nclist.body) {
  8542. status = evaltree(cp->nclist.body, flags);
  8543. }
  8544. goto out;
  8545. }
  8546. }
  8547. }
  8548. out:
  8549. return status;
  8550. }
  8551. /*
  8552. * Kick off a subshell to evaluate a tree.
  8553. */
  8554. static int
  8555. evalsubshell(union node *n, int flags)
  8556. {
  8557. struct job *jp;
  8558. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8559. int status;
  8560. errlinno = lineno = n->nredir.linno;
  8561. if (funcline)
  8562. lineno -= funcline - 1;
  8563. expredir(n->nredir.redirect);
  8564. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8565. goto nofork;
  8566. INT_OFF;
  8567. if (backgnd == FORK_FG)
  8568. get_tty_state();
  8569. jp = makejob(/*n,*/ 1);
  8570. if (forkshell(jp, n, backgnd) == 0) {
  8571. /* child */
  8572. INT_ON;
  8573. flags |= EV_EXIT;
  8574. if (backgnd)
  8575. flags &= ~EV_TESTED;
  8576. nofork:
  8577. redirect(n->nredir.redirect, 0);
  8578. evaltreenr(n->nredir.n, flags);
  8579. /* never returns */
  8580. }
  8581. /* parent */
  8582. status = 0;
  8583. if (backgnd == FORK_FG)
  8584. status = waitforjob(jp);
  8585. INT_ON;
  8586. return status;
  8587. }
  8588. /*
  8589. * Compute the names of the files in a redirection list.
  8590. */
  8591. static void fixredir(union node *, const char *, int);
  8592. static void
  8593. expredir(union node *n)
  8594. {
  8595. union node *redir;
  8596. for (redir = n; redir; redir = redir->nfile.next) {
  8597. struct arglist fn;
  8598. fn.list = NULL;
  8599. fn.lastp = &fn.list;
  8600. switch (redir->type) {
  8601. case NFROMTO:
  8602. case NFROM:
  8603. case NTO:
  8604. #if BASH_REDIR_OUTPUT
  8605. case NTO2:
  8606. #endif
  8607. case NCLOBBER:
  8608. case NAPPEND:
  8609. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8610. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8611. #if BASH_REDIR_OUTPUT
  8612. store_expfname:
  8613. #endif
  8614. #if 0
  8615. // By the design of stack allocator, the loop of this kind:
  8616. // while true; do while true; do break; done </dev/null; done
  8617. // will look like a memory leak: ash plans to free expfname's
  8618. // of "/dev/null" as soon as it finishes running the loop
  8619. // (in this case, never).
  8620. // This "fix" is wrong:
  8621. if (redir->nfile.expfname)
  8622. stunalloc(redir->nfile.expfname);
  8623. // It results in corrupted state of stacked allocations.
  8624. #endif
  8625. redir->nfile.expfname = fn.list->text;
  8626. break;
  8627. case NFROMFD:
  8628. case NTOFD: /* >& */
  8629. if (redir->ndup.vname) {
  8630. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8631. if (fn.list == NULL)
  8632. ash_msg_and_raise_error("redir error");
  8633. #if BASH_REDIR_OUTPUT
  8634. //FIXME: we used expandarg with different args!
  8635. if (!isdigit_str9(fn.list->text)) {
  8636. /* >&file, not >&fd */
  8637. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8638. ash_msg_and_raise_error("redir error");
  8639. redir->type = NTO2;
  8640. goto store_expfname;
  8641. }
  8642. #endif
  8643. fixredir(redir, fn.list->text, 1);
  8644. }
  8645. break;
  8646. }
  8647. }
  8648. }
  8649. /*
  8650. * Evaluate a pipeline. All the processes in the pipeline are children
  8651. * of the process creating the pipeline. (This differs from some versions
  8652. * of the shell, which make the last process in a pipeline the parent
  8653. * of all the rest.)
  8654. */
  8655. static int
  8656. evalpipe(union node *n, int flags)
  8657. {
  8658. struct job *jp;
  8659. struct nodelist *lp;
  8660. int pipelen;
  8661. int prevfd;
  8662. int pip[2];
  8663. int status = 0;
  8664. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8665. pipelen = 0;
  8666. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8667. pipelen++;
  8668. flags |= EV_EXIT;
  8669. INT_OFF;
  8670. if (n->npipe.pipe_backgnd == 0)
  8671. get_tty_state();
  8672. jp = makejob(/*n,*/ pipelen);
  8673. prevfd = -1;
  8674. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8675. prehash(lp->n);
  8676. pip[1] = -1;
  8677. if (lp->next) {
  8678. if (pipe(pip) < 0) {
  8679. close(prevfd);
  8680. ash_msg_and_raise_perror("can't create pipe");
  8681. }
  8682. }
  8683. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8684. /* child */
  8685. INT_ON;
  8686. if (pip[1] >= 0) {
  8687. close(pip[0]);
  8688. }
  8689. if (prevfd > 0) {
  8690. dup2(prevfd, 0);
  8691. close(prevfd);
  8692. }
  8693. if (pip[1] > 1) {
  8694. dup2(pip[1], 1);
  8695. close(pip[1]);
  8696. }
  8697. evaltreenr(lp->n, flags);
  8698. /* never returns */
  8699. }
  8700. /* parent */
  8701. if (prevfd >= 0)
  8702. close(prevfd);
  8703. prevfd = pip[0];
  8704. /* Don't want to trigger debugging */
  8705. if (pip[1] != -1)
  8706. close(pip[1]);
  8707. }
  8708. if (n->npipe.pipe_backgnd == 0) {
  8709. status = waitforjob(jp);
  8710. TRACE(("evalpipe: job done exit status %d\n", status));
  8711. }
  8712. INT_ON;
  8713. return status;
  8714. }
  8715. /*
  8716. * Controls whether the shell is interactive or not.
  8717. */
  8718. static void
  8719. setinteractive(int on)
  8720. {
  8721. static smallint is_interactive;
  8722. if (++on == is_interactive)
  8723. return;
  8724. is_interactive = on;
  8725. setsignal(SIGINT);
  8726. setsignal(SIGQUIT);
  8727. setsignal(SIGTERM);
  8728. if (is_interactive > 1) {
  8729. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8730. /* Looks like they want an interactive shell */
  8731. static smallint did_banner;
  8732. if (!did_banner) {
  8733. /* note: ash and hush share this string */
  8734. out1fmt("\n\n%s %s\n"
  8735. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8736. "\n",
  8737. bb_banner,
  8738. "built-in shell (ash)"
  8739. );
  8740. did_banner = 1;
  8741. }
  8742. #endif
  8743. #if ENABLE_FEATURE_EDITING
  8744. if (!line_input_state)
  8745. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8746. #endif
  8747. }
  8748. }
  8749. static void
  8750. optschanged(void)
  8751. {
  8752. #if DEBUG
  8753. opentrace();
  8754. #endif
  8755. setinteractive(iflag);
  8756. setjobctl(mflag);
  8757. #if ENABLE_FEATURE_EDITING_VI
  8758. if (line_input_state) {
  8759. if (viflag)
  8760. line_input_state->flags |= VI_MODE;
  8761. else
  8762. line_input_state->flags &= ~VI_MODE;
  8763. }
  8764. #else
  8765. viflag = 0; /* forcibly keep the option off */
  8766. #endif
  8767. }
  8768. struct localvar_list {
  8769. struct localvar_list *next;
  8770. struct localvar *lv;
  8771. };
  8772. static struct localvar_list *localvar_stack;
  8773. /*
  8774. * Called after a function returns.
  8775. * Interrupts must be off.
  8776. */
  8777. static void
  8778. poplocalvars(int keep)
  8779. {
  8780. struct localvar_list *ll;
  8781. struct localvar *lvp, *next;
  8782. struct var *vp;
  8783. INT_OFF;
  8784. ll = localvar_stack;
  8785. localvar_stack = ll->next;
  8786. next = ll->lv;
  8787. free(ll);
  8788. while ((lvp = next) != NULL) {
  8789. next = lvp->next;
  8790. vp = lvp->vp;
  8791. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8792. if (keep) {
  8793. int bits = VSTRFIXED;
  8794. if (lvp->flags != VUNSET) {
  8795. if (vp->var_text == lvp->text)
  8796. bits |= VTEXTFIXED;
  8797. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8798. free((char*)lvp->text);
  8799. }
  8800. vp->flags &= ~bits;
  8801. vp->flags |= (lvp->flags & bits);
  8802. if ((vp->flags &
  8803. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8804. unsetvar(vp->var_text);
  8805. } else if (vp == NULL) { /* $- saved */
  8806. memcpy(optlist, lvp->text, sizeof(optlist));
  8807. free((char*)lvp->text);
  8808. optschanged();
  8809. } else if (lvp->flags == VUNSET) {
  8810. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8811. unsetvar(vp->var_text);
  8812. } else {
  8813. if (vp->var_func)
  8814. vp->var_func(var_end(lvp->text));
  8815. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8816. free((char*)vp->var_text);
  8817. vp->flags = lvp->flags;
  8818. vp->var_text = lvp->text;
  8819. }
  8820. free(lvp);
  8821. }
  8822. INT_ON;
  8823. }
  8824. /*
  8825. * Create a new localvar environment.
  8826. */
  8827. static struct localvar_list *
  8828. pushlocalvars(void)
  8829. {
  8830. struct localvar_list *ll;
  8831. INT_OFF;
  8832. ll = ckzalloc(sizeof(*ll));
  8833. /*ll->lv = NULL; - zalloc did it */
  8834. ll->next = localvar_stack;
  8835. localvar_stack = ll;
  8836. INT_ON;
  8837. return ll->next;
  8838. }
  8839. static void
  8840. unwindlocalvars(struct localvar_list *stop)
  8841. {
  8842. while (localvar_stack != stop)
  8843. poplocalvars(0);
  8844. }
  8845. static int
  8846. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8847. {
  8848. volatile struct shparam saveparam;
  8849. struct jmploc *volatile savehandler;
  8850. struct jmploc jmploc;
  8851. int e;
  8852. int savefuncline;
  8853. saveparam = shellparam;
  8854. savefuncline = funcline;
  8855. savehandler = exception_handler;
  8856. e = setjmp(jmploc.loc);
  8857. if (e) {
  8858. goto funcdone;
  8859. }
  8860. INT_OFF;
  8861. exception_handler = &jmploc;
  8862. shellparam.malloced = 0;
  8863. func->count++;
  8864. funcline = func->n.ndefun.linno;
  8865. INT_ON;
  8866. shellparam.nparam = argc - 1;
  8867. shellparam.p = argv + 1;
  8868. #if ENABLE_ASH_GETOPTS
  8869. shellparam.optind = 1;
  8870. shellparam.optoff = -1;
  8871. #endif
  8872. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8873. funcdone:
  8874. INT_OFF;
  8875. funcline = savefuncline;
  8876. freefunc(func);
  8877. freeparam(&shellparam);
  8878. shellparam = saveparam;
  8879. exception_handler = savehandler;
  8880. INT_ON;
  8881. evalskip &= ~SKIPFUNC;
  8882. return e;
  8883. }
  8884. /*
  8885. * Make a variable a local variable. When a variable is made local, it's
  8886. * value and flags are saved in a localvar structure. The saved values
  8887. * will be restored when the shell function returns. We handle the name
  8888. * "-" as a special case: it makes changes to "set +-options" local
  8889. * (options will be restored on return from the function).
  8890. */
  8891. static void
  8892. mklocal(char *name)
  8893. {
  8894. struct localvar *lvp;
  8895. struct var **vpp;
  8896. struct var *vp;
  8897. char *eq = strchr(name, '=');
  8898. INT_OFF;
  8899. /* Cater for duplicate "local". Examples:
  8900. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8901. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8902. */
  8903. lvp = localvar_stack->lv;
  8904. while (lvp) {
  8905. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8906. if (eq)
  8907. setvareq(name, 0);
  8908. /* else:
  8909. * it's a duplicate "local VAR" declaration, do nothing
  8910. */
  8911. goto ret;
  8912. }
  8913. lvp = lvp->next;
  8914. }
  8915. lvp = ckzalloc(sizeof(*lvp));
  8916. if (LONE_DASH(name)) {
  8917. char *p;
  8918. p = ckmalloc(sizeof(optlist));
  8919. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8920. vp = NULL;
  8921. } else {
  8922. vpp = hashvar(name);
  8923. vp = *findvar(vpp, name);
  8924. if (vp == NULL) {
  8925. /* variable did not exist yet */
  8926. if (eq)
  8927. vp = setvareq(name, VSTRFIXED);
  8928. else
  8929. vp = setvar(name, NULL, VSTRFIXED);
  8930. lvp->flags = VUNSET;
  8931. } else {
  8932. lvp->text = vp->var_text;
  8933. lvp->flags = vp->flags;
  8934. /* make sure neither "struct var" nor string gets freed
  8935. * during (un)setting:
  8936. */
  8937. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8938. if (eq)
  8939. setvareq(name, 0);
  8940. else
  8941. /* "local VAR" unsets VAR: */
  8942. setvar0(name, NULL);
  8943. }
  8944. }
  8945. lvp->vp = vp;
  8946. lvp->next = localvar_stack->lv;
  8947. localvar_stack->lv = lvp;
  8948. ret:
  8949. INT_ON;
  8950. }
  8951. /*
  8952. * The "local" command.
  8953. */
  8954. static int FAST_FUNC
  8955. localcmd(int argc UNUSED_PARAM, char **argv)
  8956. {
  8957. char *name;
  8958. if (!localvar_stack)
  8959. ash_msg_and_raise_error("not in a function");
  8960. argv = argptr;
  8961. while ((name = *argv++) != NULL) {
  8962. mklocal(name);
  8963. }
  8964. return 0;
  8965. }
  8966. static int FAST_FUNC
  8967. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8968. {
  8969. return 1;
  8970. }
  8971. static int FAST_FUNC
  8972. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8973. {
  8974. return 0;
  8975. }
  8976. static int FAST_FUNC
  8977. execcmd(int argc UNUSED_PARAM, char **argv)
  8978. {
  8979. optionarg = NULL;
  8980. while (nextopt("a:") != '\0')
  8981. /* nextopt() sets optionarg to "-a ARGV0" */;
  8982. argv = argptr;
  8983. if (argv[0]) {
  8984. char *prog;
  8985. iflag = 0; /* exit on error */
  8986. mflag = 0;
  8987. optschanged();
  8988. /* We should set up signals for "exec CMD"
  8989. * the same way as for "CMD" without "exec".
  8990. * But optschanged->setinteractive->setsignal
  8991. * still thought we are a root shell. Therefore, for example,
  8992. * SIGQUIT is still set to IGN. Fix it:
  8993. */
  8994. shlvl++;
  8995. setsignal(SIGQUIT);
  8996. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8997. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8998. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8999. prog = argv[0];
  9000. if (optionarg)
  9001. argv[0] = optionarg;
  9002. shellexec(prog, argv, pathval(), 0);
  9003. /* NOTREACHED */
  9004. }
  9005. return 0;
  9006. }
  9007. /*
  9008. * The return command.
  9009. */
  9010. static int FAST_FUNC
  9011. returncmd(int argc UNUSED_PARAM, char **argv)
  9012. {
  9013. /*
  9014. * If called outside a function, do what ksh does;
  9015. * skip the rest of the file.
  9016. */
  9017. evalskip = SKIPFUNC;
  9018. return argv[1] ? number(argv[1]) : exitstatus;
  9019. }
  9020. /* Forward declarations for builtintab[] */
  9021. static int breakcmd(int, char **) FAST_FUNC;
  9022. static int dotcmd(int, char **) FAST_FUNC;
  9023. static int evalcmd(int, char **, int) FAST_FUNC;
  9024. static int exitcmd(int, char **) FAST_FUNC;
  9025. static int exportcmd(int, char **) FAST_FUNC;
  9026. #if ENABLE_ASH_GETOPTS
  9027. static int getoptscmd(int, char **) FAST_FUNC;
  9028. #endif
  9029. #if ENABLE_ASH_HELP
  9030. static int helpcmd(int, char **) FAST_FUNC;
  9031. #endif
  9032. #if MAX_HISTORY
  9033. static int historycmd(int, char **) FAST_FUNC;
  9034. #endif
  9035. #if ENABLE_FEATURE_SH_MATH
  9036. static int letcmd(int, char **) FAST_FUNC;
  9037. #endif
  9038. static int readcmd(int, char **) FAST_FUNC;
  9039. static int setcmd(int, char **) FAST_FUNC;
  9040. static int shiftcmd(int, char **) FAST_FUNC;
  9041. static int timescmd(int, char **) FAST_FUNC;
  9042. static int trapcmd(int, char **) FAST_FUNC;
  9043. static int umaskcmd(int, char **) FAST_FUNC;
  9044. static int unsetcmd(int, char **) FAST_FUNC;
  9045. static int ulimitcmd(int, char **) FAST_FUNC;
  9046. #define BUILTIN_NOSPEC "0"
  9047. #define BUILTIN_SPECIAL "1"
  9048. #define BUILTIN_REGULAR "2"
  9049. #define BUILTIN_SPEC_REG "3"
  9050. #define BUILTIN_ASSIGN "4"
  9051. #define BUILTIN_SPEC_ASSG "5"
  9052. #define BUILTIN_REG_ASSG "6"
  9053. #define BUILTIN_SPEC_REG_ASSG "7"
  9054. /* Stubs for calling non-FAST_FUNC's */
  9055. #if ENABLE_ASH_ECHO
  9056. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9057. #endif
  9058. #if ENABLE_ASH_PRINTF
  9059. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9060. #endif
  9061. #if ENABLE_ASH_TEST || BASH_TEST2
  9062. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9063. #endif
  9064. /* Keep these in proper order since it is searched via bsearch() */
  9065. static const struct builtincmd builtintab[] = {
  9066. { BUILTIN_SPEC_REG "." , dotcmd },
  9067. { BUILTIN_SPEC_REG ":" , truecmd },
  9068. #if ENABLE_ASH_TEST
  9069. { BUILTIN_REGULAR "[" , testcmd },
  9070. #endif
  9071. #if BASH_TEST2
  9072. { BUILTIN_REGULAR "[[" , testcmd },
  9073. #endif
  9074. #if ENABLE_ASH_ALIAS
  9075. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9076. #endif
  9077. #if JOBS
  9078. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9079. #endif
  9080. { BUILTIN_SPEC_REG "break" , breakcmd },
  9081. { BUILTIN_REGULAR "cd" , cdcmd },
  9082. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9083. #if ENABLE_ASH_CMDCMD
  9084. { BUILTIN_REGULAR "command" , commandcmd },
  9085. #endif
  9086. { BUILTIN_SPEC_REG "continue", breakcmd },
  9087. #if ENABLE_ASH_ECHO
  9088. { BUILTIN_REGULAR "echo" , echocmd },
  9089. #endif
  9090. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9091. { BUILTIN_SPEC_REG "exec" , execcmd },
  9092. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9093. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9094. { BUILTIN_REGULAR "false" , falsecmd },
  9095. #if JOBS
  9096. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9097. #endif
  9098. #if ENABLE_ASH_GETOPTS
  9099. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9100. #endif
  9101. { BUILTIN_NOSPEC "hash" , hashcmd },
  9102. #if ENABLE_ASH_HELP
  9103. { BUILTIN_NOSPEC "help" , helpcmd },
  9104. #endif
  9105. #if MAX_HISTORY
  9106. { BUILTIN_NOSPEC "history" , historycmd },
  9107. #endif
  9108. #if JOBS
  9109. { BUILTIN_REGULAR "jobs" , jobscmd },
  9110. { BUILTIN_REGULAR "kill" , killcmd },
  9111. #endif
  9112. #if ENABLE_FEATURE_SH_MATH
  9113. { BUILTIN_NOSPEC "let" , letcmd },
  9114. #endif
  9115. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9116. #if ENABLE_ASH_PRINTF
  9117. { BUILTIN_REGULAR "printf" , printfcmd },
  9118. #endif
  9119. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  9120. { BUILTIN_REGULAR "read" , readcmd },
  9121. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9122. { BUILTIN_SPEC_REG "return" , returncmd },
  9123. { BUILTIN_SPEC_REG "set" , setcmd },
  9124. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9125. #if BASH_SOURCE
  9126. { BUILTIN_SPEC_REG "source" , dotcmd },
  9127. #endif
  9128. #if ENABLE_ASH_TEST
  9129. { BUILTIN_REGULAR "test" , testcmd },
  9130. #endif
  9131. { BUILTIN_SPEC_REG "times" , timescmd },
  9132. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9133. { BUILTIN_REGULAR "true" , truecmd },
  9134. { BUILTIN_NOSPEC "type" , typecmd },
  9135. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  9136. { BUILTIN_REGULAR "umask" , umaskcmd },
  9137. #if ENABLE_ASH_ALIAS
  9138. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9139. #endif
  9140. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9141. { BUILTIN_REGULAR "wait" , waitcmd },
  9142. };
  9143. /* Should match the above table! */
  9144. #define COMMANDCMD (builtintab + \
  9145. /* . : */ 2 + \
  9146. /* [ */ 1 * ENABLE_ASH_TEST + \
  9147. /* [[ */ 1 * BASH_TEST2 + \
  9148. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9149. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9150. /* break cd cddir */ 3)
  9151. #define EVALCMD (COMMANDCMD + \
  9152. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9153. /* continue */ 1 + \
  9154. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9155. 0)
  9156. #define EXECCMD (EVALCMD + \
  9157. /* eval */ 1)
  9158. /*
  9159. * Search the table of builtin commands.
  9160. */
  9161. static int
  9162. pstrcmp1(const void *a, const void *b)
  9163. {
  9164. return strcmp((char*)a, *(char**)b + 1);
  9165. }
  9166. static struct builtincmd *
  9167. find_builtin(const char *name)
  9168. {
  9169. struct builtincmd *bp;
  9170. bp = bsearch(
  9171. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9172. pstrcmp1
  9173. );
  9174. return bp;
  9175. }
  9176. /*
  9177. * Execute a simple command.
  9178. */
  9179. static void unwindfiles(struct parsefile *stop);
  9180. static int
  9181. isassignment(const char *p)
  9182. {
  9183. const char *q = endofname(p);
  9184. if (p == q)
  9185. return 0;
  9186. return *q == '=';
  9187. }
  9188. static int FAST_FUNC
  9189. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9190. {
  9191. /* Preserve exitstatus of a previous possible redirection
  9192. * as POSIX mandates */
  9193. return back_exitstatus;
  9194. }
  9195. static int
  9196. evalcommand(union node *cmd, int flags)
  9197. {
  9198. static const struct builtincmd null_bltin = {
  9199. "\0\0", bltincmd /* why three NULs? */
  9200. };
  9201. struct localvar_list *localvar_stop;
  9202. struct parsefile *file_stop;
  9203. struct redirtab *redir_stop;
  9204. union node *argp;
  9205. struct arglist arglist;
  9206. struct arglist varlist;
  9207. char **argv;
  9208. int argc;
  9209. const struct strlist *sp;
  9210. struct cmdentry cmdentry;
  9211. struct job *jp;
  9212. char *lastarg;
  9213. const char *path;
  9214. int spclbltin;
  9215. int status;
  9216. char **nargv;
  9217. smallint cmd_is_exec;
  9218. errlinno = lineno = cmd->ncmd.linno;
  9219. if (funcline)
  9220. lineno -= funcline - 1;
  9221. /* First expand the arguments. */
  9222. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9223. localvar_stop = pushlocalvars();
  9224. file_stop = g_parsefile;
  9225. back_exitstatus = 0;
  9226. cmdentry.cmdtype = CMDBUILTIN;
  9227. cmdentry.u.cmd = &null_bltin;
  9228. varlist.lastp = &varlist.list;
  9229. *varlist.lastp = NULL;
  9230. arglist.lastp = &arglist.list;
  9231. *arglist.lastp = NULL;
  9232. argc = 0;
  9233. if (cmd->ncmd.args) {
  9234. struct builtincmd *bcmd;
  9235. smallint pseudovarflag;
  9236. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  9237. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  9238. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  9239. struct strlist **spp;
  9240. spp = arglist.lastp;
  9241. if (pseudovarflag && isassignment(argp->narg.text))
  9242. expandarg(argp, &arglist, EXP_VARTILDE);
  9243. else
  9244. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  9245. for (sp = *spp; sp; sp = sp->next)
  9246. argc++;
  9247. }
  9248. }
  9249. /* Reserve one extra spot at the front for shellexec. */
  9250. nargv = stalloc(sizeof(char *) * (argc + 2));
  9251. argv = ++nargv;
  9252. for (sp = arglist.list; sp; sp = sp->next) {
  9253. TRACE(("evalcommand arg: %s\n", sp->text));
  9254. *nargv++ = sp->text;
  9255. }
  9256. *nargv = NULL;
  9257. lastarg = NULL;
  9258. if (iflag && funcline == 0 && argc > 0)
  9259. lastarg = nargv[-1];
  9260. expredir(cmd->ncmd.redirect);
  9261. redir_stop = pushredir(cmd->ncmd.redirect);
  9262. preverrout_fd = 2;
  9263. if (BASH_XTRACEFD && xflag) {
  9264. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9265. * we do not emulate this. We only use its value.
  9266. */
  9267. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9268. if (xtracefd && is_number(xtracefd))
  9269. preverrout_fd = atoi(xtracefd);
  9270. }
  9271. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9272. path = vpath.var_text;
  9273. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9274. struct strlist **spp;
  9275. char *p;
  9276. spp = varlist.lastp;
  9277. expandarg(argp, &varlist, EXP_VARTILDE);
  9278. mklocal((*spp)->text);
  9279. /*
  9280. * Modify the command lookup path, if a PATH= assignment
  9281. * is present
  9282. */
  9283. p = (*spp)->text;
  9284. if (varcmp(p, path) == 0)
  9285. path = p;
  9286. }
  9287. /* Print the command if xflag is set. */
  9288. if (xflag) {
  9289. const char *pfx = "";
  9290. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9291. sp = varlist.list;
  9292. while (sp) {
  9293. char *varval = sp->text;
  9294. char *eq = strchrnul(varval, '=');
  9295. if (*eq)
  9296. eq++;
  9297. fdprintf(preverrout_fd, "%s%.*s%s",
  9298. pfx,
  9299. (int)(eq - varval), varval,
  9300. maybe_single_quote(eq)
  9301. );
  9302. sp = sp->next;
  9303. pfx = " ";
  9304. }
  9305. sp = arglist.list;
  9306. while (sp) {
  9307. fdprintf(preverrout_fd, "%s%s",
  9308. pfx,
  9309. /* always quote if matches reserved word: */
  9310. findkwd(sp->text)
  9311. ? single_quote(sp->text)
  9312. : maybe_single_quote(sp->text)
  9313. );
  9314. sp = sp->next;
  9315. pfx = " ";
  9316. }
  9317. safe_write(preverrout_fd, "\n", 1);
  9318. }
  9319. cmd_is_exec = 0;
  9320. spclbltin = -1;
  9321. /* Now locate the command. */
  9322. if (argc) {
  9323. int cmd_flag = DO_ERR;
  9324. #if ENABLE_ASH_CMDCMD
  9325. const char *oldpath = path + 5;
  9326. #endif
  9327. path += 5;
  9328. for (;;) {
  9329. find_command(argv[0], &cmdentry, cmd_flag, path);
  9330. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9331. flush_stdout_stderr();
  9332. status = 127;
  9333. goto bail;
  9334. }
  9335. /* implement bltin and command here */
  9336. if (cmdentry.cmdtype != CMDBUILTIN)
  9337. break;
  9338. if (spclbltin < 0)
  9339. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9340. if (cmdentry.u.cmd == EXECCMD)
  9341. cmd_is_exec = 1;
  9342. #if ENABLE_ASH_CMDCMD
  9343. if (cmdentry.u.cmd == COMMANDCMD) {
  9344. path = oldpath;
  9345. nargv = parse_command_args(argv, &path);
  9346. if (!nargv)
  9347. break;
  9348. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9349. * nargv => "PROG". path is updated if -p.
  9350. */
  9351. argc -= nargv - argv;
  9352. argv = nargv;
  9353. cmd_flag |= DO_NOFUNC;
  9354. } else
  9355. #endif
  9356. break;
  9357. }
  9358. }
  9359. if (status) {
  9360. bail:
  9361. exitstatus = status;
  9362. /* We have a redirection error. */
  9363. if (spclbltin > 0)
  9364. raise_exception(EXERROR);
  9365. goto out;
  9366. }
  9367. /* Execute the command. */
  9368. switch (cmdentry.cmdtype) {
  9369. default: {
  9370. #if ENABLE_FEATURE_SH_STANDALONE \
  9371. && ENABLE_FEATURE_SH_NOFORK \
  9372. && NUM_APPLETS > 1
  9373. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9374. * around run_nofork_applet() call.
  9375. * (2) Should this check also be done in forkshell()?
  9376. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9377. */
  9378. /* find_command() encodes applet_no as (-2 - applet_no) */
  9379. int applet_no = (- cmdentry.u.index - 2);
  9380. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9381. char **sv_environ;
  9382. INT_OFF;
  9383. sv_environ = environ;
  9384. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9385. /*
  9386. * Run <applet>_main().
  9387. * Signals (^C) can't interrupt here.
  9388. * Otherwise we can mangle stdio or malloc internal state.
  9389. * This makes applets which can run for a long time
  9390. * and/or wait for user input ineligible for NOFORK:
  9391. * for example, "yes" or "rm" (rm -i waits for input).
  9392. */
  9393. status = run_nofork_applet(applet_no, argv);
  9394. environ = sv_environ;
  9395. /*
  9396. * Try enabling NOFORK for "yes" applet.
  9397. * ^C _will_ stop it (write returns EINTR),
  9398. * but this causes stdout FILE to be stuck
  9399. * and needing clearerr(). What if other applets
  9400. * also can get EINTRs? Do we need to switch
  9401. * our signals to SA_RESTART?
  9402. */
  9403. /*clearerr(stdout);*/
  9404. INT_ON;
  9405. break;
  9406. }
  9407. #endif
  9408. /* Can we avoid forking? For example, very last command
  9409. * in a script or a subshell does not need forking,
  9410. * we can just exec it.
  9411. */
  9412. if (!(flags & EV_EXIT) || may_have_traps) {
  9413. /* No, forking off a child is necessary */
  9414. INT_OFF;
  9415. get_tty_state();
  9416. jp = makejob(/*cmd,*/ 1);
  9417. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9418. /* parent */
  9419. status = waitforjob(jp);
  9420. INT_ON;
  9421. TRACE(("forked child exited with %d\n", status));
  9422. break;
  9423. }
  9424. /* child */
  9425. FORCE_INT_ON;
  9426. /* fall through to exec'ing external program */
  9427. }
  9428. listsetvar(varlist.list, VEXPORT|VSTACK);
  9429. shellexec(argv[0], argv, path, cmdentry.u.index);
  9430. /* NOTREACHED */
  9431. } /* default */
  9432. case CMDBUILTIN:
  9433. if (spclbltin > 0 || argc == 0) {
  9434. poplocalvars(1);
  9435. if (cmd_is_exec && argc > 1)
  9436. listsetvar(varlist.list, VEXPORT);
  9437. }
  9438. /* Tight loop with builtins only:
  9439. * "while kill -0 $child; do true; done"
  9440. * will never exit even if $child died, unless we do this
  9441. * to reap the zombie and make kill detect that it's gone: */
  9442. dowait(DOWAIT_NONBLOCK, NULL);
  9443. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9444. if (exception_type == EXERROR && spclbltin <= 0) {
  9445. FORCE_INT_ON;
  9446. goto readstatus;
  9447. }
  9448. raise:
  9449. longjmp(exception_handler->loc, 1);
  9450. }
  9451. goto readstatus;
  9452. case CMDFUNCTION:
  9453. /* See above for the rationale */
  9454. dowait(DOWAIT_NONBLOCK, NULL);
  9455. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9456. goto raise;
  9457. readstatus:
  9458. status = exitstatus;
  9459. break;
  9460. } /* switch */
  9461. out:
  9462. if (cmd->ncmd.redirect)
  9463. popredir(/*drop:*/ cmd_is_exec);
  9464. unwindredir(redir_stop);
  9465. unwindfiles(file_stop);
  9466. unwindlocalvars(localvar_stop);
  9467. if (lastarg) {
  9468. /* dsl: I think this is intended to be used to support
  9469. * '_' in 'vi' command mode during line editing...
  9470. * However I implemented that within libedit itself.
  9471. */
  9472. setvar0("_", lastarg);
  9473. }
  9474. return status;
  9475. }
  9476. static int
  9477. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9478. {
  9479. char *volatile savecmdname;
  9480. struct jmploc *volatile savehandler;
  9481. struct jmploc jmploc;
  9482. int status;
  9483. int i;
  9484. savecmdname = commandname;
  9485. savehandler = exception_handler;
  9486. i = setjmp(jmploc.loc);
  9487. if (i)
  9488. goto cmddone;
  9489. exception_handler = &jmploc;
  9490. commandname = argv[0];
  9491. argptr = argv + 1;
  9492. optptr = NULL; /* initialize nextopt */
  9493. if (cmd == EVALCMD)
  9494. status = evalcmd(argc, argv, flags);
  9495. else
  9496. status = (*cmd->builtin)(argc, argv);
  9497. flush_stdout_stderr();
  9498. status |= ferror(stdout);
  9499. exitstatus = status;
  9500. cmddone:
  9501. clearerr(stdout);
  9502. commandname = savecmdname;
  9503. exception_handler = savehandler;
  9504. return i;
  9505. }
  9506. static int
  9507. goodname(const char *p)
  9508. {
  9509. return endofname(p)[0] == '\0';
  9510. }
  9511. /*
  9512. * Search for a command. This is called before we fork so that the
  9513. * location of the command will be available in the parent as well as
  9514. * the child. The check for "goodname" is an overly conservative
  9515. * check that the name will not be subject to expansion.
  9516. */
  9517. static void
  9518. prehash(union node *n)
  9519. {
  9520. struct cmdentry entry;
  9521. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9522. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9523. }
  9524. /* ============ Builtin commands
  9525. *
  9526. * Builtin commands whose functions are closely tied to evaluation
  9527. * are implemented here.
  9528. */
  9529. /*
  9530. * Handle break and continue commands. Break, continue, and return are
  9531. * all handled by setting the evalskip flag. The evaluation routines
  9532. * above all check this flag, and if it is set they start skipping
  9533. * commands rather than executing them. The variable skipcount is
  9534. * the number of loops to break/continue, or the number of function
  9535. * levels to return. (The latter is always 1.) It should probably
  9536. * be an error to break out of more loops than exist, but it isn't
  9537. * in the standard shell so we don't make it one here.
  9538. */
  9539. static int FAST_FUNC
  9540. breakcmd(int argc UNUSED_PARAM, char **argv)
  9541. {
  9542. int n = argv[1] ? number(argv[1]) : 1;
  9543. if (n <= 0)
  9544. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9545. if (n > loopnest)
  9546. n = loopnest;
  9547. if (n > 0) {
  9548. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9549. skipcount = n;
  9550. }
  9551. return 0;
  9552. }
  9553. /*
  9554. * This implements the input routines used by the parser.
  9555. */
  9556. enum {
  9557. INPUT_PUSH_FILE = 1,
  9558. INPUT_NOFILE_OK = 2,
  9559. };
  9560. static smallint checkkwd;
  9561. /* values of checkkwd variable */
  9562. #define CHKALIAS 0x1
  9563. #define CHKKWD 0x2
  9564. #define CHKNL 0x4
  9565. #define CHKEOFMARK 0x8
  9566. /*
  9567. * Push a string back onto the input at this current parsefile level.
  9568. * We handle aliases this way.
  9569. */
  9570. #if !ENABLE_ASH_ALIAS
  9571. #define pushstring(s, ap) pushstring(s)
  9572. #endif
  9573. static void
  9574. pushstring(char *s, struct alias *ap)
  9575. {
  9576. struct strpush *sp;
  9577. int len;
  9578. len = strlen(s);
  9579. INT_OFF;
  9580. if (g_parsefile->strpush) {
  9581. sp = ckzalloc(sizeof(*sp));
  9582. sp->prev = g_parsefile->strpush;
  9583. } else {
  9584. sp = &(g_parsefile->basestrpush);
  9585. }
  9586. g_parsefile->strpush = sp;
  9587. sp->prev_string = g_parsefile->next_to_pgetc;
  9588. sp->prev_left_in_line = g_parsefile->left_in_line;
  9589. sp->unget = g_parsefile->unget;
  9590. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9591. #if ENABLE_ASH_ALIAS
  9592. sp->ap = ap;
  9593. if (ap) {
  9594. ap->flag |= ALIASINUSE;
  9595. sp->string = s;
  9596. }
  9597. #endif
  9598. g_parsefile->next_to_pgetc = s;
  9599. g_parsefile->left_in_line = len;
  9600. g_parsefile->unget = 0;
  9601. INT_ON;
  9602. }
  9603. static void
  9604. popstring(void)
  9605. {
  9606. struct strpush *sp = g_parsefile->strpush;
  9607. INT_OFF;
  9608. #if ENABLE_ASH_ALIAS
  9609. if (sp->ap) {
  9610. if (g_parsefile->next_to_pgetc[-1] == ' '
  9611. || g_parsefile->next_to_pgetc[-1] == '\t'
  9612. ) {
  9613. checkkwd |= CHKALIAS;
  9614. }
  9615. if (sp->string != sp->ap->val) {
  9616. free(sp->string);
  9617. }
  9618. sp->ap->flag &= ~ALIASINUSE;
  9619. if (sp->ap->flag & ALIASDEAD) {
  9620. unalias(sp->ap->name);
  9621. }
  9622. }
  9623. #endif
  9624. g_parsefile->next_to_pgetc = sp->prev_string;
  9625. g_parsefile->left_in_line = sp->prev_left_in_line;
  9626. g_parsefile->unget = sp->unget;
  9627. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9628. g_parsefile->strpush = sp->prev;
  9629. if (sp != &(g_parsefile->basestrpush))
  9630. free(sp);
  9631. INT_ON;
  9632. }
  9633. static int
  9634. preadfd(void)
  9635. {
  9636. int nr;
  9637. char *buf = g_parsefile->buf;
  9638. g_parsefile->next_to_pgetc = buf;
  9639. #if ENABLE_FEATURE_EDITING
  9640. retry:
  9641. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9642. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9643. else {
  9644. # if ENABLE_ASH_IDLE_TIMEOUT
  9645. int timeout = -1;
  9646. const char *tmout_var = lookupvar("TMOUT");
  9647. if (tmout_var) {
  9648. timeout = atoi(tmout_var) * 1000;
  9649. if (timeout <= 0)
  9650. timeout = -1;
  9651. }
  9652. line_input_state->timeout = timeout;
  9653. # endif
  9654. # if ENABLE_FEATURE_TAB_COMPLETION
  9655. line_input_state->path_lookup = pathval();
  9656. # endif
  9657. reinit_unicode_for_ash();
  9658. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9659. if (nr == 0) {
  9660. /* ^C pressed, "convert" to SIGINT */
  9661. write(STDOUT_FILENO, "^C", 2);
  9662. if (trap[SIGINT]) {
  9663. buf[0] = '\n';
  9664. buf[1] = '\0';
  9665. raise(SIGINT);
  9666. return 1;
  9667. }
  9668. exitstatus = 128 + SIGINT;
  9669. bb_putchar('\n');
  9670. goto retry;
  9671. }
  9672. if (nr < 0) {
  9673. if (errno == 0) {
  9674. /* Ctrl+D pressed */
  9675. nr = 0;
  9676. }
  9677. # if ENABLE_ASH_IDLE_TIMEOUT
  9678. else if (errno == EAGAIN && timeout > 0) {
  9679. puts("\007timed out waiting for input: auto-logout");
  9680. exitshell();
  9681. }
  9682. # endif
  9683. }
  9684. }
  9685. #else
  9686. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9687. #endif
  9688. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9689. if (nr < 0) {
  9690. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9691. int flags = fcntl(0, F_GETFL);
  9692. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9693. flags &= ~O_NONBLOCK;
  9694. if (fcntl(0, F_SETFL, flags) >= 0) {
  9695. out2str("sh: turning off NDELAY mode\n");
  9696. goto retry;
  9697. }
  9698. }
  9699. }
  9700. }
  9701. #endif
  9702. return nr;
  9703. }
  9704. /*
  9705. * Refill the input buffer and return the next input character:
  9706. *
  9707. * 1) If a string was pushed back on the input, pop it;
  9708. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9709. * or we are reading from a string so we can't refill the buffer,
  9710. * return EOF.
  9711. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9712. * 4) Process input up to the next newline, deleting nul characters.
  9713. */
  9714. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9715. #define pgetc_debug(...) ((void)0)
  9716. static int pgetc(void);
  9717. static int
  9718. preadbuffer(void)
  9719. {
  9720. char *q;
  9721. int more;
  9722. if (g_parsefile->strpush) {
  9723. #if ENABLE_ASH_ALIAS
  9724. if (g_parsefile->left_in_line == -1
  9725. && g_parsefile->strpush->ap
  9726. && g_parsefile->next_to_pgetc[-1] != ' '
  9727. && g_parsefile->next_to_pgetc[-1] != '\t'
  9728. ) {
  9729. pgetc_debug("preadbuffer PEOA");
  9730. return PEOA;
  9731. }
  9732. #endif
  9733. popstring();
  9734. return pgetc();
  9735. }
  9736. /* on both branches above g_parsefile->left_in_line < 0.
  9737. * "pgetc" needs refilling.
  9738. */
  9739. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9740. * pungetc() may increment it a few times.
  9741. * Assuming it won't increment it to less than -90.
  9742. */
  9743. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9744. pgetc_debug("preadbuffer PEOF1");
  9745. /* even in failure keep left_in_line and next_to_pgetc
  9746. * in lock step, for correct multi-layer pungetc.
  9747. * left_in_line was decremented before preadbuffer(),
  9748. * must inc next_to_pgetc: */
  9749. g_parsefile->next_to_pgetc++;
  9750. return PEOF;
  9751. }
  9752. more = g_parsefile->left_in_buffer;
  9753. if (more <= 0) {
  9754. flush_stdout_stderr();
  9755. again:
  9756. more = preadfd();
  9757. if (more <= 0) {
  9758. /* don't try reading again */
  9759. g_parsefile->left_in_line = -99;
  9760. pgetc_debug("preadbuffer PEOF2");
  9761. g_parsefile->next_to_pgetc++;
  9762. return PEOF;
  9763. }
  9764. }
  9765. /* Find out where's the end of line.
  9766. * Set g_parsefile->left_in_line
  9767. * and g_parsefile->left_in_buffer acordingly.
  9768. * NUL chars are deleted.
  9769. */
  9770. q = g_parsefile->next_to_pgetc;
  9771. for (;;) {
  9772. char c;
  9773. more--;
  9774. c = *q;
  9775. if (c == '\0') {
  9776. memmove(q, q + 1, more);
  9777. } else {
  9778. q++;
  9779. if (c == '\n') {
  9780. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9781. break;
  9782. }
  9783. }
  9784. if (more <= 0) {
  9785. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9786. if (g_parsefile->left_in_line < 0)
  9787. goto again;
  9788. break;
  9789. }
  9790. }
  9791. g_parsefile->left_in_buffer = more;
  9792. if (vflag) {
  9793. char save = *q;
  9794. *q = '\0';
  9795. out2str(g_parsefile->next_to_pgetc);
  9796. *q = save;
  9797. }
  9798. pgetc_debug("preadbuffer at %d:%p'%s'",
  9799. g_parsefile->left_in_line,
  9800. g_parsefile->next_to_pgetc,
  9801. g_parsefile->next_to_pgetc);
  9802. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9803. }
  9804. static void
  9805. nlprompt(void)
  9806. {
  9807. g_parsefile->linno++;
  9808. setprompt_if(doprompt, 2);
  9809. }
  9810. static void
  9811. nlnoprompt(void)
  9812. {
  9813. g_parsefile->linno++;
  9814. needprompt = doprompt;
  9815. }
  9816. static int
  9817. pgetc(void)
  9818. {
  9819. int c;
  9820. pgetc_debug("pgetc at %d:%p'%s'",
  9821. g_parsefile->left_in_line,
  9822. g_parsefile->next_to_pgetc,
  9823. g_parsefile->next_to_pgetc);
  9824. if (g_parsefile->unget)
  9825. return g_parsefile->lastc[--g_parsefile->unget];
  9826. if (--g_parsefile->left_in_line >= 0)
  9827. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9828. else
  9829. c = preadbuffer();
  9830. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9831. g_parsefile->lastc[0] = c;
  9832. return c;
  9833. }
  9834. #if ENABLE_ASH_ALIAS
  9835. static int
  9836. pgetc_without_PEOA(void)
  9837. {
  9838. int c;
  9839. do {
  9840. pgetc_debug("pgetc at %d:%p'%s'",
  9841. g_parsefile->left_in_line,
  9842. g_parsefile->next_to_pgetc,
  9843. g_parsefile->next_to_pgetc);
  9844. c = pgetc();
  9845. } while (c == PEOA);
  9846. return c;
  9847. }
  9848. #else
  9849. # define pgetc_without_PEOA() pgetc()
  9850. #endif
  9851. /*
  9852. * Undo a call to pgetc. Only two characters may be pushed back.
  9853. * PEOF may be pushed back.
  9854. */
  9855. static void
  9856. pungetc(void)
  9857. {
  9858. g_parsefile->unget++;
  9859. }
  9860. /* This one eats backslash+newline */
  9861. static int
  9862. pgetc_eatbnl(void)
  9863. {
  9864. int c;
  9865. while ((c = pgetc()) == '\\') {
  9866. if (pgetc() != '\n') {
  9867. pungetc();
  9868. break;
  9869. }
  9870. nlprompt();
  9871. }
  9872. return c;
  9873. }
  9874. struct synstack {
  9875. smalluint syntax;
  9876. uint8_t innerdq :1;
  9877. uint8_t varpushed :1;
  9878. uint8_t dblquote :1;
  9879. int varnest; /* levels of variables expansion */
  9880. int dqvarnest; /* levels of variables expansion within double quotes */
  9881. int parenlevel; /* levels of parens in arithmetic */
  9882. struct synstack *prev;
  9883. struct synstack *next;
  9884. };
  9885. static void
  9886. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9887. {
  9888. memset(next, 0, sizeof(*next));
  9889. next->syntax = syntax;
  9890. next->next = *stack;
  9891. (*stack)->prev = next;
  9892. *stack = next;
  9893. }
  9894. static ALWAYS_INLINE void
  9895. synstack_pop(struct synstack **stack)
  9896. {
  9897. *stack = (*stack)->next;
  9898. }
  9899. /*
  9900. * To handle the "." command, a stack of input files is used. Pushfile
  9901. * adds a new entry to the stack and popfile restores the previous level.
  9902. */
  9903. static void
  9904. pushfile(void)
  9905. {
  9906. struct parsefile *pf;
  9907. pf = ckzalloc(sizeof(*pf));
  9908. pf->prev = g_parsefile;
  9909. pf->pf_fd = -1;
  9910. /*pf->strpush = NULL; - ckzalloc did it */
  9911. /*pf->basestrpush.prev = NULL;*/
  9912. /*pf->unget = 0;*/
  9913. g_parsefile = pf;
  9914. }
  9915. static void
  9916. popfile(void)
  9917. {
  9918. struct parsefile *pf = g_parsefile;
  9919. if (pf == &basepf)
  9920. return;
  9921. INT_OFF;
  9922. if (pf->pf_fd >= 0)
  9923. close(pf->pf_fd);
  9924. free(pf->buf);
  9925. while (pf->strpush)
  9926. popstring();
  9927. g_parsefile = pf->prev;
  9928. free(pf);
  9929. INT_ON;
  9930. }
  9931. static void
  9932. unwindfiles(struct parsefile *stop)
  9933. {
  9934. while (g_parsefile != stop)
  9935. popfile();
  9936. }
  9937. /*
  9938. * Return to top level.
  9939. */
  9940. static void
  9941. popallfiles(void)
  9942. {
  9943. unwindfiles(&basepf);
  9944. }
  9945. /*
  9946. * Close the file(s) that the shell is reading commands from. Called
  9947. * after a fork is done.
  9948. */
  9949. static void
  9950. closescript(void)
  9951. {
  9952. popallfiles();
  9953. if (g_parsefile->pf_fd > 0) {
  9954. close(g_parsefile->pf_fd);
  9955. g_parsefile->pf_fd = 0;
  9956. }
  9957. }
  9958. /*
  9959. * Like setinputfile, but takes an open file descriptor. Call this with
  9960. * interrupts off.
  9961. */
  9962. static void
  9963. setinputfd(int fd, int push)
  9964. {
  9965. if (push) {
  9966. pushfile();
  9967. g_parsefile->buf = NULL;
  9968. }
  9969. g_parsefile->pf_fd = fd;
  9970. if (g_parsefile->buf == NULL)
  9971. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9972. g_parsefile->left_in_buffer = 0;
  9973. g_parsefile->left_in_line = 0;
  9974. g_parsefile->linno = 1;
  9975. }
  9976. /*
  9977. * Set the input to take input from a file. If push is set, push the
  9978. * old input onto the stack first.
  9979. */
  9980. static int
  9981. setinputfile(const char *fname, int flags)
  9982. {
  9983. int fd;
  9984. INT_OFF;
  9985. fd = open(fname, O_RDONLY | O_CLOEXEC);
  9986. if (fd < 0) {
  9987. if (flags & INPUT_NOFILE_OK)
  9988. goto out;
  9989. exitstatus = 127;
  9990. ash_msg_and_raise_perror("can't open '%s'", fname);
  9991. }
  9992. if (fd < 10)
  9993. fd = savefd(fd);
  9994. else if (O_CLOEXEC == 0) /* old libc */
  9995. close_on_exec_on(fd);
  9996. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9997. out:
  9998. INT_ON;
  9999. return fd;
  10000. }
  10001. /*
  10002. * Like setinputfile, but takes input from a string.
  10003. */
  10004. static void
  10005. setinputstring(char *string)
  10006. {
  10007. INT_OFF;
  10008. pushfile();
  10009. g_parsefile->next_to_pgetc = string;
  10010. g_parsefile->left_in_line = strlen(string);
  10011. g_parsefile->buf = NULL;
  10012. g_parsefile->linno = 1;
  10013. INT_ON;
  10014. }
  10015. /*
  10016. * Routines to check for mail.
  10017. */
  10018. #if ENABLE_ASH_MAIL
  10019. /* Hash of mtimes of mailboxes */
  10020. static unsigned mailtime_hash;
  10021. /* Set if MAIL or MAILPATH is changed. */
  10022. static smallint mail_var_path_changed;
  10023. /*
  10024. * Print appropriate message(s) if mail has arrived.
  10025. * If mail_var_path_changed is set,
  10026. * then the value of MAIL has mail_var_path_changed,
  10027. * so we just update the values.
  10028. */
  10029. static void
  10030. chkmail(void)
  10031. {
  10032. const char *mpath;
  10033. char *p;
  10034. char *q;
  10035. unsigned new_hash;
  10036. struct stackmark smark;
  10037. struct stat statb;
  10038. setstackmark(&smark);
  10039. mpath = mpathset() ? mpathval() : mailval();
  10040. new_hash = 0;
  10041. for (;;) {
  10042. p = path_advance(&mpath, nullstr);
  10043. if (p == NULL)
  10044. break;
  10045. if (*p == '\0')
  10046. continue;
  10047. for (q = p; *q; q++)
  10048. continue;
  10049. #if DEBUG
  10050. if (q[-1] != '/')
  10051. abort();
  10052. #endif
  10053. q[-1] = '\0'; /* delete trailing '/' */
  10054. if (stat(p, &statb) < 0) {
  10055. continue;
  10056. }
  10057. /* Very simplistic "hash": just a sum of all mtimes */
  10058. new_hash += (unsigned)statb.st_mtime;
  10059. }
  10060. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10061. if (mailtime_hash != 0)
  10062. out2str("you have mail\n");
  10063. mailtime_hash = new_hash;
  10064. }
  10065. mail_var_path_changed = 0;
  10066. popstackmark(&smark);
  10067. }
  10068. static void FAST_FUNC
  10069. changemail(const char *val UNUSED_PARAM)
  10070. {
  10071. mail_var_path_changed = 1;
  10072. }
  10073. #endif /* ASH_MAIL */
  10074. /* ============ ??? */
  10075. /*
  10076. * Set the shell parameters.
  10077. */
  10078. static void
  10079. setparam(char **argv)
  10080. {
  10081. char **newparam;
  10082. char **ap;
  10083. int nparam;
  10084. for (nparam = 0; argv[nparam]; nparam++)
  10085. continue;
  10086. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10087. while (*argv) {
  10088. *ap++ = ckstrdup(*argv++);
  10089. }
  10090. *ap = NULL;
  10091. freeparam(&shellparam);
  10092. shellparam.malloced = 1;
  10093. shellparam.nparam = nparam;
  10094. shellparam.p = newparam;
  10095. #if ENABLE_ASH_GETOPTS
  10096. shellparam.optind = 1;
  10097. shellparam.optoff = -1;
  10098. #endif
  10099. }
  10100. /*
  10101. * Process shell options. The global variable argptr contains a pointer
  10102. * to the argument list; we advance it past the options.
  10103. *
  10104. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10105. * For a non-interactive shell, an error condition encountered
  10106. * by a special built-in ... shall cause the shell to write a diagnostic message
  10107. * to standard error and exit as shown in the following table:
  10108. * Error Special Built-In
  10109. * ...
  10110. * Utility syntax error (option or operand error) Shall exit
  10111. * ...
  10112. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10113. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10114. * and shell continues), and people rely on this behavior!
  10115. * Testcase:
  10116. * set -o barfoo 2>/dev/null
  10117. * echo $?
  10118. *
  10119. * Oh well. Let's mimic that.
  10120. */
  10121. static int
  10122. plus_minus_o(char *name, int val)
  10123. {
  10124. int i;
  10125. if (name) {
  10126. for (i = 0; i < NOPTS; i++) {
  10127. if (strcmp(name, optnames(i)) == 0) {
  10128. optlist[i] = val;
  10129. return 0;
  10130. }
  10131. }
  10132. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10133. return 1;
  10134. }
  10135. for (i = 0; i < NOPTS; i++) {
  10136. if (val) {
  10137. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10138. } else {
  10139. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10140. }
  10141. }
  10142. return 0;
  10143. }
  10144. static void
  10145. setoption(int flag, int val)
  10146. {
  10147. int i;
  10148. for (i = 0; i < NOPTS; i++) {
  10149. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10150. optlist[i] = val;
  10151. return;
  10152. }
  10153. }
  10154. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10155. /* NOTREACHED */
  10156. }
  10157. /* If login_sh is not NULL, we are called to parse command line opts,
  10158. * not "set -opts"
  10159. */
  10160. static int
  10161. options(int *login_sh)
  10162. {
  10163. char *p;
  10164. int val;
  10165. int c;
  10166. if (login_sh)
  10167. minusc = NULL;
  10168. while ((p = *argptr) != NULL) {
  10169. c = *p++;
  10170. if (c != '-' && c != '+')
  10171. break;
  10172. argptr++;
  10173. val = 0; /* val = 0 if c == '+' */
  10174. if (c == '-') {
  10175. val = 1;
  10176. if (p[0] == '\0' || LONE_DASH(p)) {
  10177. if (!login_sh) {
  10178. /* "-" means turn off -x and -v */
  10179. if (p[0] == '\0')
  10180. xflag = vflag = 0;
  10181. /* "--" means reset params */
  10182. else if (*argptr == NULL)
  10183. setparam(argptr);
  10184. }
  10185. break; /* "-" or "--" terminates options */
  10186. }
  10187. }
  10188. /* first char was + or - */
  10189. while ((c = *p++) != '\0') {
  10190. if (login_sh) {
  10191. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10192. if (c == 'c') {
  10193. minusc = p; /* command is after shell args */
  10194. cflag = 1;
  10195. continue;
  10196. }
  10197. if (c == 's') { /* -s, +s */
  10198. sflag = 1;
  10199. continue;
  10200. }
  10201. if (c == 'i') { /* -i, +i */
  10202. iflag = 1;
  10203. continue;
  10204. }
  10205. if (c == 'l') {
  10206. *login_sh = 1; /* -l or +l == --login */
  10207. continue;
  10208. }
  10209. /* bash does not accept +-login, we also won't */
  10210. if (val && (c == '-')) { /* long options */
  10211. if (strcmp(p, "login") == 0) {
  10212. *login_sh = 1;
  10213. }
  10214. break;
  10215. }
  10216. }
  10217. if (c == 'o') {
  10218. if (plus_minus_o(*argptr, val)) {
  10219. /* it already printed err message */
  10220. return 1; /* error */
  10221. }
  10222. if (*argptr)
  10223. argptr++;
  10224. } else {
  10225. setoption(c, val);
  10226. }
  10227. }
  10228. }
  10229. return 0;
  10230. }
  10231. /*
  10232. * The shift builtin command.
  10233. */
  10234. static int FAST_FUNC
  10235. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10236. {
  10237. int n;
  10238. char **ap1, **ap2;
  10239. n = 1;
  10240. if (argv[1])
  10241. n = number(argv[1]);
  10242. if (n > shellparam.nparam)
  10243. return 1;
  10244. INT_OFF;
  10245. shellparam.nparam -= n;
  10246. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10247. if (shellparam.malloced)
  10248. free(*ap1);
  10249. }
  10250. ap2 = shellparam.p;
  10251. while ((*ap2++ = *ap1++) != NULL)
  10252. continue;
  10253. #if ENABLE_ASH_GETOPTS
  10254. shellparam.optind = 1;
  10255. shellparam.optoff = -1;
  10256. #endif
  10257. INT_ON;
  10258. return 0;
  10259. }
  10260. /*
  10261. * POSIX requires that 'set' (but not export or readonly) output the
  10262. * variables in lexicographic order - by the locale's collating order (sigh).
  10263. * Maybe we could keep them in an ordered balanced binary tree
  10264. * instead of hashed lists.
  10265. * For now just roll 'em through qsort for printing...
  10266. */
  10267. static int
  10268. showvars(const char *sep_prefix, int on, int off)
  10269. {
  10270. const char *sep;
  10271. char **ep, **epend;
  10272. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10273. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10274. sep = *sep_prefix ? " " : sep_prefix;
  10275. for (; ep < epend; ep++) {
  10276. const char *p;
  10277. const char *q;
  10278. p = endofname(*ep);
  10279. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10280. * makes "export -p" to have output not suitable for "eval":
  10281. * import os
  10282. * os.environ["test-test"]="test"
  10283. * if os.fork() == 0:
  10284. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10285. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10286. */
  10287. q = nullstr;
  10288. if (*p == '=')
  10289. q = single_quote(++p);
  10290. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10291. }
  10292. return 0;
  10293. }
  10294. /*
  10295. * The set command builtin.
  10296. */
  10297. static int FAST_FUNC
  10298. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10299. {
  10300. int retval;
  10301. if (!argv[1])
  10302. return showvars(nullstr, 0, VUNSET);
  10303. INT_OFF;
  10304. retval = options(/*login_sh:*/ NULL);
  10305. if (retval == 0) { /* if no parse error... */
  10306. optschanged();
  10307. if (*argptr != NULL) {
  10308. setparam(argptr);
  10309. }
  10310. }
  10311. INT_ON;
  10312. return retval;
  10313. }
  10314. #if ENABLE_ASH_RANDOM_SUPPORT
  10315. static void FAST_FUNC
  10316. change_random(const char *value)
  10317. {
  10318. uint32_t t;
  10319. if (value == NULL) {
  10320. /* "get", generate */
  10321. t = next_random(&random_gen);
  10322. /* set without recursion */
  10323. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10324. vrandom.flags &= ~VNOFUNC;
  10325. } else {
  10326. /* set/reset */
  10327. t = strtoul(value, NULL, 10);
  10328. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10329. }
  10330. }
  10331. #endif
  10332. #if BASH_EPOCH_VARS
  10333. static void FAST_FUNC
  10334. change_epoch(struct var *vepoch, const char *fmt)
  10335. {
  10336. struct timeval tv;
  10337. char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  10338. gettimeofday(&tv, NULL);
  10339. sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
  10340. setvar(vepoch->var_text, buffer, VNOFUNC);
  10341. vepoch->flags &= ~VNOFUNC;
  10342. }
  10343. static void FAST_FUNC
  10344. change_seconds(const char *value UNUSED_PARAM)
  10345. {
  10346. change_epoch(&vepochs, "%lu");
  10347. }
  10348. static void FAST_FUNC
  10349. change_realtime(const char *value UNUSED_PARAM)
  10350. {
  10351. change_epoch(&vepochr, "%lu.%06u");
  10352. }
  10353. #endif
  10354. #if ENABLE_ASH_GETOPTS
  10355. static int
  10356. getopts(char *optstr, char *optvar, char **optfirst)
  10357. {
  10358. char *p, *q;
  10359. char c = '?';
  10360. int done = 0;
  10361. char sbuf[2];
  10362. char **optnext;
  10363. int ind = shellparam.optind;
  10364. int off = shellparam.optoff;
  10365. sbuf[1] = '\0';
  10366. shellparam.optind = -1;
  10367. optnext = optfirst + ind - 1;
  10368. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10369. p = NULL;
  10370. else
  10371. p = optnext[-1] + off;
  10372. if (p == NULL || *p == '\0') {
  10373. /* Current word is done, advance */
  10374. p = *optnext;
  10375. if (p == NULL || *p != '-' || *++p == '\0') {
  10376. atend:
  10377. unsetvar("OPTARG");
  10378. p = NULL;
  10379. done = 1;
  10380. goto out;
  10381. }
  10382. optnext++;
  10383. if (LONE_DASH(p)) /* check for "--" */
  10384. goto atend;
  10385. }
  10386. c = *p++;
  10387. for (q = optstr; *q != c;) {
  10388. if (*q == '\0') {
  10389. /* OPTERR is a bashism */
  10390. const char *cp = lookupvar("OPTERR");
  10391. if ((cp && LONE_CHAR(cp, '0'))
  10392. || (optstr[0] == ':')
  10393. ) {
  10394. sbuf[0] = c;
  10395. /*sbuf[1] = '\0'; - already is */
  10396. setvar0("OPTARG", sbuf);
  10397. } else {
  10398. fprintf(stderr, "Illegal option -%c\n", c);
  10399. unsetvar("OPTARG");
  10400. }
  10401. c = '?';
  10402. goto out;
  10403. }
  10404. if (*++q == ':')
  10405. q++;
  10406. }
  10407. if (*++q == ':') {
  10408. if (*p == '\0' && (p = *optnext) == NULL) {
  10409. /* OPTERR is a bashism */
  10410. const char *cp = lookupvar("OPTERR");
  10411. if ((cp && LONE_CHAR(cp, '0'))
  10412. || (optstr[0] == ':')
  10413. ) {
  10414. sbuf[0] = c;
  10415. /*sbuf[1] = '\0'; - already is */
  10416. setvar0("OPTARG", sbuf);
  10417. c = ':';
  10418. } else {
  10419. fprintf(stderr, "No arg for -%c option\n", c);
  10420. unsetvar("OPTARG");
  10421. c = '?';
  10422. }
  10423. goto out;
  10424. }
  10425. if (p == *optnext)
  10426. optnext++;
  10427. setvar0("OPTARG", p);
  10428. p = NULL;
  10429. } else
  10430. setvar0("OPTARG", nullstr);
  10431. out:
  10432. ind = optnext - optfirst + 1;
  10433. setvar("OPTIND", itoa(ind), VNOFUNC);
  10434. sbuf[0] = c;
  10435. /*sbuf[1] = '\0'; - already is */
  10436. setvar0(optvar, sbuf);
  10437. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10438. shellparam.optind = ind;
  10439. return done;
  10440. }
  10441. /*
  10442. * The getopts builtin. Shellparam.optnext points to the next argument
  10443. * to be processed. Shellparam.optptr points to the next character to
  10444. * be processed in the current argument. If shellparam.optnext is NULL,
  10445. * then it's the first time getopts has been called.
  10446. */
  10447. static int FAST_FUNC
  10448. getoptscmd(int argc, char **argv)
  10449. {
  10450. char **optbase;
  10451. if (argc < 3)
  10452. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10453. if (argc == 3) {
  10454. optbase = shellparam.p;
  10455. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10456. shellparam.optind = 1;
  10457. shellparam.optoff = -1;
  10458. }
  10459. } else {
  10460. optbase = &argv[3];
  10461. if ((unsigned)shellparam.optind > argc - 2) {
  10462. shellparam.optind = 1;
  10463. shellparam.optoff = -1;
  10464. }
  10465. }
  10466. return getopts(argv[1], argv[2], optbase);
  10467. }
  10468. #endif /* ASH_GETOPTS */
  10469. /* ============ Shell parser */
  10470. struct heredoc {
  10471. struct heredoc *next; /* next here document in list */
  10472. union node *here; /* redirection node */
  10473. char *eofmark; /* string indicating end of input */
  10474. smallint striptabs; /* if set, strip leading tabs */
  10475. };
  10476. static smallint tokpushback; /* last token pushed back */
  10477. static smallint quoteflag; /* set if (part of) last token was quoted */
  10478. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10479. static struct heredoc *heredoclist; /* list of here documents to read */
  10480. static char *wordtext; /* text of last word returned by readtoken */
  10481. static struct nodelist *backquotelist;
  10482. static union node *redirnode;
  10483. static struct heredoc *heredoc;
  10484. static const char *
  10485. tokname(char *buf, int tok)
  10486. {
  10487. if (tok < TSEMI)
  10488. return tokname_array[tok];
  10489. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10490. return buf;
  10491. }
  10492. /* raise_error_unexpected_syntax:
  10493. * Called when an unexpected token is read during the parse. The argument
  10494. * is the token that is expected, or -1 if more than one type of token can
  10495. * occur at this point.
  10496. */
  10497. static void raise_error_unexpected_syntax(int) NORETURN;
  10498. static void
  10499. raise_error_unexpected_syntax(int token)
  10500. {
  10501. char msg[64];
  10502. char buf[16];
  10503. int l;
  10504. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10505. if (token >= 0)
  10506. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10507. raise_error_syntax(msg);
  10508. /* NOTREACHED */
  10509. }
  10510. /* parsing is heavily cross-recursive, need these forward decls */
  10511. static union node *andor(void);
  10512. static union node *pipeline(void);
  10513. static union node *parse_command(void);
  10514. static void parseheredoc(void);
  10515. static int peektoken(void);
  10516. static int readtoken(void);
  10517. static union node *
  10518. list(int nlflag)
  10519. {
  10520. union node *n1, *n2, *n3;
  10521. int tok;
  10522. n1 = NULL;
  10523. for (;;) {
  10524. switch (peektoken()) {
  10525. case TNL:
  10526. if (!(nlflag & 1))
  10527. break;
  10528. parseheredoc();
  10529. return n1;
  10530. case TEOF:
  10531. if (!n1 && (nlflag & 1))
  10532. n1 = NODE_EOF;
  10533. parseheredoc();
  10534. return n1;
  10535. }
  10536. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10537. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10538. return n1;
  10539. nlflag |= 2;
  10540. n2 = andor();
  10541. tok = readtoken();
  10542. if (tok == TBACKGND) {
  10543. if (n2->type == NPIPE) {
  10544. n2->npipe.pipe_backgnd = 1;
  10545. } else {
  10546. if (n2->type != NREDIR) {
  10547. n3 = stzalloc(sizeof(struct nredir));
  10548. n3->nredir.n = n2;
  10549. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10550. n2 = n3;
  10551. }
  10552. n2->type = NBACKGND;
  10553. }
  10554. }
  10555. if (n1 == NULL) {
  10556. n1 = n2;
  10557. } else {
  10558. n3 = stzalloc(sizeof(struct nbinary));
  10559. n3->type = NSEMI;
  10560. n3->nbinary.ch1 = n1;
  10561. n3->nbinary.ch2 = n2;
  10562. n1 = n3;
  10563. }
  10564. switch (tok) {
  10565. case TNL:
  10566. case TEOF:
  10567. tokpushback = 1;
  10568. /* fall through */
  10569. case TBACKGND:
  10570. case TSEMI:
  10571. break;
  10572. default:
  10573. if ((nlflag & 1))
  10574. raise_error_unexpected_syntax(-1);
  10575. tokpushback = 1;
  10576. return n1;
  10577. }
  10578. }
  10579. }
  10580. static union node *
  10581. andor(void)
  10582. {
  10583. union node *n1, *n2, *n3;
  10584. int t;
  10585. n1 = pipeline();
  10586. for (;;) {
  10587. t = readtoken();
  10588. if (t == TAND) {
  10589. t = NAND;
  10590. } else if (t == TOR) {
  10591. t = NOR;
  10592. } else {
  10593. tokpushback = 1;
  10594. return n1;
  10595. }
  10596. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10597. n2 = pipeline();
  10598. n3 = stzalloc(sizeof(struct nbinary));
  10599. n3->type = t;
  10600. n3->nbinary.ch1 = n1;
  10601. n3->nbinary.ch2 = n2;
  10602. n1 = n3;
  10603. }
  10604. }
  10605. static union node *
  10606. pipeline(void)
  10607. {
  10608. union node *n1, *n2, *pipenode;
  10609. struct nodelist *lp, *prev;
  10610. int negate;
  10611. negate = 0;
  10612. TRACE(("pipeline: entered\n"));
  10613. if (readtoken() == TNOT) {
  10614. negate = !negate;
  10615. checkkwd = CHKKWD | CHKALIAS;
  10616. } else
  10617. tokpushback = 1;
  10618. n1 = parse_command();
  10619. if (readtoken() == TPIPE) {
  10620. pipenode = stzalloc(sizeof(struct npipe));
  10621. pipenode->type = NPIPE;
  10622. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10623. lp = stzalloc(sizeof(struct nodelist));
  10624. pipenode->npipe.cmdlist = lp;
  10625. lp->n = n1;
  10626. do {
  10627. prev = lp;
  10628. lp = stzalloc(sizeof(struct nodelist));
  10629. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10630. lp->n = parse_command();
  10631. prev->next = lp;
  10632. } while (readtoken() == TPIPE);
  10633. lp->next = NULL;
  10634. n1 = pipenode;
  10635. }
  10636. tokpushback = 1;
  10637. if (negate) {
  10638. n2 = stzalloc(sizeof(struct nnot));
  10639. n2->type = NNOT;
  10640. n2->nnot.com = n1;
  10641. return n2;
  10642. }
  10643. return n1;
  10644. }
  10645. static union node *
  10646. makename(void)
  10647. {
  10648. union node *n;
  10649. n = stzalloc(sizeof(struct narg));
  10650. n->type = NARG;
  10651. /*n->narg.next = NULL; - stzalloc did it */
  10652. n->narg.text = wordtext;
  10653. n->narg.backquote = backquotelist;
  10654. return n;
  10655. }
  10656. static void
  10657. fixredir(union node *n, const char *text, int err)
  10658. {
  10659. int fd;
  10660. TRACE(("Fix redir %s %d\n", text, err));
  10661. if (!err)
  10662. n->ndup.vname = NULL;
  10663. fd = bb_strtou(text, NULL, 10);
  10664. if (!errno && fd >= 0)
  10665. n->ndup.dupfd = fd;
  10666. else if (LONE_DASH(text))
  10667. n->ndup.dupfd = -1;
  10668. else {
  10669. if (err)
  10670. raise_error_syntax("bad fd number");
  10671. n->ndup.vname = makename();
  10672. }
  10673. }
  10674. static void
  10675. parsefname(void)
  10676. {
  10677. union node *n = redirnode;
  10678. if (n->type == NHERE)
  10679. checkkwd = CHKEOFMARK;
  10680. if (readtoken() != TWORD)
  10681. raise_error_unexpected_syntax(-1);
  10682. if (n->type == NHERE) {
  10683. struct heredoc *here = heredoc;
  10684. struct heredoc *p;
  10685. if (quoteflag == 0)
  10686. n->type = NXHERE;
  10687. TRACE(("Here document %d\n", n->type));
  10688. rmescapes(wordtext, 0, NULL);
  10689. here->eofmark = wordtext;
  10690. here->next = NULL;
  10691. if (heredoclist == NULL)
  10692. heredoclist = here;
  10693. else {
  10694. for (p = heredoclist; p->next; p = p->next)
  10695. continue;
  10696. p->next = here;
  10697. }
  10698. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10699. fixredir(n, wordtext, 0);
  10700. } else {
  10701. n->nfile.fname = makename();
  10702. }
  10703. }
  10704. static union node *
  10705. simplecmd(void)
  10706. {
  10707. union node *args, **app;
  10708. union node *n = NULL;
  10709. union node *vars, **vpp;
  10710. union node **rpp, *redir;
  10711. int savecheckkwd;
  10712. int savelinno;
  10713. #if BASH_TEST2
  10714. smallint double_brackets_flag = 0;
  10715. #endif
  10716. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10717. args = NULL;
  10718. app = &args;
  10719. vars = NULL;
  10720. vpp = &vars;
  10721. redir = NULL;
  10722. rpp = &redir;
  10723. savecheckkwd = CHKALIAS;
  10724. savelinno = g_parsefile->linno;
  10725. for (;;) {
  10726. int t;
  10727. checkkwd = savecheckkwd;
  10728. t = readtoken();
  10729. switch (t) {
  10730. #if BASH_FUNCTION
  10731. case TFUNCTION:
  10732. if (peektoken() != TWORD)
  10733. raise_error_unexpected_syntax(TWORD);
  10734. function_flag = 1;
  10735. break;
  10736. #endif
  10737. #if BASH_TEST2
  10738. case TAND: /* "&&" */
  10739. case TOR: /* "||" */
  10740. if (!double_brackets_flag) {
  10741. tokpushback = 1;
  10742. goto out;
  10743. }
  10744. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10745. #endif
  10746. case TWORD:
  10747. n = stzalloc(sizeof(struct narg));
  10748. n->type = NARG;
  10749. /*n->narg.next = NULL; - stzalloc did it */
  10750. n->narg.text = wordtext;
  10751. #if BASH_TEST2
  10752. if (strcmp("[[", wordtext) == 0)
  10753. double_brackets_flag = 1;
  10754. else if (strcmp("]]", wordtext) == 0)
  10755. double_brackets_flag = 0;
  10756. #endif
  10757. n->narg.backquote = backquotelist;
  10758. if (savecheckkwd && isassignment(wordtext)) {
  10759. *vpp = n;
  10760. vpp = &n->narg.next;
  10761. } else {
  10762. *app = n;
  10763. app = &n->narg.next;
  10764. savecheckkwd = 0;
  10765. }
  10766. #if BASH_FUNCTION
  10767. if (function_flag) {
  10768. checkkwd = CHKNL | CHKKWD;
  10769. switch (peektoken()) {
  10770. case TBEGIN:
  10771. case TIF:
  10772. case TCASE:
  10773. case TUNTIL:
  10774. case TWHILE:
  10775. case TFOR:
  10776. goto do_func;
  10777. case TLP:
  10778. function_flag = 0;
  10779. break;
  10780. # if BASH_TEST2
  10781. case TWORD:
  10782. if (strcmp("[[", wordtext) == 0)
  10783. goto do_func;
  10784. /* fall through */
  10785. # endif
  10786. default:
  10787. raise_error_unexpected_syntax(-1);
  10788. }
  10789. }
  10790. #endif
  10791. break;
  10792. case TREDIR:
  10793. *rpp = n = redirnode;
  10794. rpp = &n->nfile.next;
  10795. parsefname(); /* read name of redirection file */
  10796. break;
  10797. case TLP:
  10798. IF_BASH_FUNCTION(do_func:)
  10799. if (args && app == &args->narg.next
  10800. && !vars && !redir
  10801. ) {
  10802. struct builtincmd *bcmd;
  10803. const char *name;
  10804. /* We have a function */
  10805. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10806. raise_error_unexpected_syntax(TRP);
  10807. name = n->narg.text;
  10808. if (!goodname(name)
  10809. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10810. ) {
  10811. raise_error_syntax("bad function name");
  10812. }
  10813. n->type = NDEFUN;
  10814. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10815. n->ndefun.text = n->narg.text;
  10816. n->ndefun.linno = g_parsefile->linno;
  10817. n->ndefun.body = parse_command();
  10818. return n;
  10819. }
  10820. IF_BASH_FUNCTION(function_flag = 0;)
  10821. /* fall through */
  10822. default:
  10823. tokpushback = 1;
  10824. goto out;
  10825. }
  10826. }
  10827. out:
  10828. *app = NULL;
  10829. *vpp = NULL;
  10830. *rpp = NULL;
  10831. n = stzalloc(sizeof(struct ncmd));
  10832. if (NCMD != 0)
  10833. n->type = NCMD;
  10834. n->ncmd.linno = savelinno;
  10835. n->ncmd.args = args;
  10836. n->ncmd.assign = vars;
  10837. n->ncmd.redirect = redir;
  10838. return n;
  10839. }
  10840. static union node *
  10841. parse_command(void)
  10842. {
  10843. union node *n1, *n2;
  10844. union node *ap, **app;
  10845. union node *cp, **cpp;
  10846. union node *redir, **rpp;
  10847. union node **rpp2;
  10848. int t;
  10849. int savelinno;
  10850. redir = NULL;
  10851. rpp2 = &redir;
  10852. savelinno = g_parsefile->linno;
  10853. switch (readtoken()) {
  10854. default:
  10855. raise_error_unexpected_syntax(-1);
  10856. /* NOTREACHED */
  10857. case TIF:
  10858. n1 = stzalloc(sizeof(struct nif));
  10859. n1->type = NIF;
  10860. n1->nif.test = list(0);
  10861. if (readtoken() != TTHEN)
  10862. raise_error_unexpected_syntax(TTHEN);
  10863. n1->nif.ifpart = list(0);
  10864. n2 = n1;
  10865. while (readtoken() == TELIF) {
  10866. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10867. n2 = n2->nif.elsepart;
  10868. n2->type = NIF;
  10869. n2->nif.test = list(0);
  10870. if (readtoken() != TTHEN)
  10871. raise_error_unexpected_syntax(TTHEN);
  10872. n2->nif.ifpart = list(0);
  10873. }
  10874. if (lasttoken == TELSE)
  10875. n2->nif.elsepart = list(0);
  10876. else {
  10877. n2->nif.elsepart = NULL;
  10878. tokpushback = 1;
  10879. }
  10880. t = TFI;
  10881. break;
  10882. case TWHILE:
  10883. case TUNTIL: {
  10884. int got;
  10885. n1 = stzalloc(sizeof(struct nbinary));
  10886. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10887. n1->nbinary.ch1 = list(0);
  10888. got = readtoken();
  10889. if (got != TDO) {
  10890. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10891. got == TWORD ? wordtext : ""));
  10892. raise_error_unexpected_syntax(TDO);
  10893. }
  10894. n1->nbinary.ch2 = list(0);
  10895. t = TDONE;
  10896. break;
  10897. }
  10898. case TFOR:
  10899. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10900. raise_error_syntax("bad for loop variable");
  10901. n1 = stzalloc(sizeof(struct nfor));
  10902. n1->type = NFOR;
  10903. n1->nfor.linno = savelinno;
  10904. n1->nfor.var = wordtext;
  10905. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10906. if (readtoken() == TIN) {
  10907. app = &ap;
  10908. while (readtoken() == TWORD) {
  10909. n2 = stzalloc(sizeof(struct narg));
  10910. n2->type = NARG;
  10911. /*n2->narg.next = NULL; - stzalloc did it */
  10912. n2->narg.text = wordtext;
  10913. n2->narg.backquote = backquotelist;
  10914. *app = n2;
  10915. app = &n2->narg.next;
  10916. }
  10917. *app = NULL;
  10918. n1->nfor.args = ap;
  10919. if (lasttoken != TNL && lasttoken != TSEMI)
  10920. raise_error_unexpected_syntax(-1);
  10921. } else {
  10922. n2 = stzalloc(sizeof(struct narg));
  10923. n2->type = NARG;
  10924. /*n2->narg.next = NULL; - stzalloc did it */
  10925. n2->narg.text = (char *)dolatstr;
  10926. /*n2->narg.backquote = NULL;*/
  10927. n1->nfor.args = n2;
  10928. /*
  10929. * Newline or semicolon here is optional (but note
  10930. * that the original Bourne shell only allowed NL).
  10931. */
  10932. if (lasttoken != TSEMI)
  10933. tokpushback = 1;
  10934. }
  10935. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10936. if (readtoken() != TDO)
  10937. raise_error_unexpected_syntax(TDO);
  10938. n1->nfor.body = list(0);
  10939. t = TDONE;
  10940. break;
  10941. case TCASE:
  10942. n1 = stzalloc(sizeof(struct ncase));
  10943. n1->type = NCASE;
  10944. n1->ncase.linno = savelinno;
  10945. if (readtoken() != TWORD)
  10946. raise_error_unexpected_syntax(TWORD);
  10947. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10948. n2->type = NARG;
  10949. /*n2->narg.next = NULL; - stzalloc did it */
  10950. n2->narg.text = wordtext;
  10951. n2->narg.backquote = backquotelist;
  10952. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10953. if (readtoken() != TIN)
  10954. raise_error_unexpected_syntax(TIN);
  10955. cpp = &n1->ncase.cases;
  10956. next_case:
  10957. checkkwd = CHKNL | CHKKWD;
  10958. t = readtoken();
  10959. while (t != TESAC) {
  10960. if (lasttoken == TLP)
  10961. readtoken();
  10962. *cpp = cp = stzalloc(sizeof(struct nclist));
  10963. cp->type = NCLIST;
  10964. app = &cp->nclist.pattern;
  10965. for (;;) {
  10966. *app = ap = stzalloc(sizeof(struct narg));
  10967. ap->type = NARG;
  10968. /*ap->narg.next = NULL; - stzalloc did it */
  10969. ap->narg.text = wordtext;
  10970. ap->narg.backquote = backquotelist;
  10971. if (readtoken() != TPIPE)
  10972. break;
  10973. app = &ap->narg.next;
  10974. readtoken();
  10975. }
  10976. //ap->narg.next = NULL;
  10977. if (lasttoken != TRP)
  10978. raise_error_unexpected_syntax(TRP);
  10979. cp->nclist.body = list(2);
  10980. cpp = &cp->nclist.next;
  10981. checkkwd = CHKNL | CHKKWD;
  10982. t = readtoken();
  10983. if (t != TESAC) {
  10984. if (t != TENDCASE)
  10985. raise_error_unexpected_syntax(TENDCASE);
  10986. goto next_case;
  10987. }
  10988. }
  10989. *cpp = NULL;
  10990. goto redir;
  10991. case TLP:
  10992. n1 = stzalloc(sizeof(struct nredir));
  10993. n1->type = NSUBSHELL;
  10994. n1->nredir.linno = savelinno;
  10995. n1->nredir.n = list(0);
  10996. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10997. t = TRP;
  10998. break;
  10999. case TBEGIN:
  11000. n1 = list(0);
  11001. t = TEND;
  11002. break;
  11003. IF_BASH_FUNCTION(case TFUNCTION:)
  11004. case TWORD:
  11005. case TREDIR:
  11006. tokpushback = 1;
  11007. return simplecmd();
  11008. }
  11009. if (readtoken() != t)
  11010. raise_error_unexpected_syntax(t);
  11011. redir:
  11012. /* Now check for redirection which may follow command */
  11013. checkkwd = CHKKWD | CHKALIAS;
  11014. rpp = rpp2;
  11015. while (readtoken() == TREDIR) {
  11016. *rpp = n2 = redirnode;
  11017. rpp = &n2->nfile.next;
  11018. parsefname();
  11019. }
  11020. tokpushback = 1;
  11021. *rpp = NULL;
  11022. if (redir) {
  11023. if (n1->type != NSUBSHELL) {
  11024. n2 = stzalloc(sizeof(struct nredir));
  11025. n2->type = NREDIR;
  11026. n2->nredir.linno = savelinno;
  11027. n2->nredir.n = n1;
  11028. n1 = n2;
  11029. }
  11030. n1->nredir.redirect = redir;
  11031. }
  11032. return n1;
  11033. }
  11034. #if BASH_DOLLAR_SQUOTE
  11035. static int
  11036. decode_dollar_squote(void)
  11037. {
  11038. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11039. int c, cnt;
  11040. char *p;
  11041. char buf[4];
  11042. c = pgetc();
  11043. p = strchr(C_escapes, c);
  11044. if (p) {
  11045. buf[0] = c;
  11046. p = buf;
  11047. cnt = 3;
  11048. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11049. do {
  11050. c = pgetc();
  11051. *++p = c;
  11052. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11053. pungetc();
  11054. } else if (c == 'x') { /* \xHH */
  11055. do {
  11056. c = pgetc();
  11057. *++p = c;
  11058. } while (isxdigit(c) && --cnt);
  11059. pungetc();
  11060. if (cnt == 3) { /* \x but next char is "bad" */
  11061. c = 'x';
  11062. goto unrecognized;
  11063. }
  11064. } else { /* simple seq like \\ or \t */
  11065. p++;
  11066. }
  11067. *p = '\0';
  11068. p = buf;
  11069. c = bb_process_escape_sequence((void*)&p);
  11070. } else { /* unrecognized "\z": print both chars unless ' or " */
  11071. if (c != '\'' && c != '"') {
  11072. unrecognized:
  11073. c |= 0x100; /* "please encode \, then me" */
  11074. }
  11075. }
  11076. return c;
  11077. }
  11078. #endif
  11079. /* Used by expandstr to get here-doc like behaviour. */
  11080. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11081. static ALWAYS_INLINE int
  11082. realeofmark(const char *eofmark)
  11083. {
  11084. return eofmark && eofmark != FAKEEOFMARK;
  11085. }
  11086. /*
  11087. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11088. * is not NULL, read a here document. In the latter case, eofmark is the
  11089. * word which marks the end of the document and striptabs is true if
  11090. * leading tabs should be stripped from the document. The argument c
  11091. * is the first character of the input token or document.
  11092. *
  11093. * Because C does not have internal subroutines, I have simulated them
  11094. * using goto's to implement the subroutine linkage. The following macros
  11095. * will run code that appears at the end of readtoken1.
  11096. */
  11097. #define CHECKEND() {goto checkend; checkend_return:;}
  11098. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11099. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11100. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11101. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11102. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11103. static int
  11104. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11105. {
  11106. /* NB: syntax parameter fits into smallint */
  11107. /* c parameter is an unsigned char or PEOF or PEOA */
  11108. char *out;
  11109. size_t len;
  11110. struct nodelist *bqlist;
  11111. smallint quotef;
  11112. smallint oldstyle;
  11113. smallint pssyntax; /* we are expanding a prompt string */
  11114. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11115. /* syntax stack */
  11116. struct synstack synbase = { };
  11117. struct synstack *synstack = &synbase;
  11118. #if ENABLE_ASH_EXPAND_PRMT
  11119. pssyntax = (syntax == PSSYNTAX);
  11120. if (pssyntax)
  11121. syntax = DQSYNTAX;
  11122. #else
  11123. pssyntax = 0; /* constant */
  11124. #endif
  11125. synstack->syntax = syntax;
  11126. if (syntax == DQSYNTAX)
  11127. synstack->dblquote = 1;
  11128. quotef = 0;
  11129. bqlist = NULL;
  11130. STARTSTACKSTR(out);
  11131. loop:
  11132. /* For each line, until end of word */
  11133. CHECKEND(); /* set c to PEOF if at end of here document */
  11134. for (;;) { /* until end of line or end of word */
  11135. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11136. switch (SIT(c, synstack->syntax)) {
  11137. case CNL: /* '\n' */
  11138. if (synstack->syntax == BASESYNTAX
  11139. && !synstack->varnest
  11140. ) {
  11141. goto endword; /* exit outer loop */
  11142. }
  11143. USTPUTC(c, out);
  11144. nlprompt();
  11145. c = pgetc();
  11146. goto loop; /* continue outer loop */
  11147. case CWORD:
  11148. USTPUTC(c, out);
  11149. break;
  11150. case CCTL:
  11151. #if BASH_DOLLAR_SQUOTE
  11152. if (c == '\\' && bash_dollar_squote) {
  11153. c = decode_dollar_squote();
  11154. if (c == '\0') {
  11155. /* skip $'\000', $'\x00' (like bash) */
  11156. break;
  11157. }
  11158. if (c & 0x100) {
  11159. /* Unknown escape. Encode as '\z' */
  11160. c = (unsigned char)c;
  11161. if (eofmark == NULL || synstack->dblquote)
  11162. USTPUTC(CTLESC, out);
  11163. USTPUTC('\\', out);
  11164. }
  11165. }
  11166. #endif
  11167. if (!eofmark || synstack->dblquote || synstack->varnest)
  11168. USTPUTC(CTLESC, out);
  11169. USTPUTC(c, out);
  11170. break;
  11171. case CBACK: /* backslash */
  11172. c = pgetc_without_PEOA();
  11173. if (c == PEOF) {
  11174. USTPUTC(CTLESC, out);
  11175. USTPUTC('\\', out);
  11176. pungetc();
  11177. } else if (c == '\n') {
  11178. nlprompt();
  11179. } else {
  11180. if (pssyntax && c == '$') {
  11181. USTPUTC(CTLESC, out);
  11182. USTPUTC('\\', out);
  11183. }
  11184. /* Backslash is retained if we are in "str"
  11185. * and next char isn't dquote-special.
  11186. */
  11187. if (synstack->dblquote
  11188. && c != '\\'
  11189. && c != '`'
  11190. && c != '$'
  11191. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11192. && (c != '}' || !synstack->varnest)
  11193. ) {
  11194. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11195. USTPUTC('\\', out);
  11196. }
  11197. USTPUTC(CTLESC, out);
  11198. USTPUTC(c, out);
  11199. quotef = 1;
  11200. }
  11201. break;
  11202. case CSQUOTE:
  11203. synstack->syntax = SQSYNTAX;
  11204. quotemark:
  11205. if (eofmark == NULL) {
  11206. USTPUTC(CTLQUOTEMARK, out);
  11207. }
  11208. break;
  11209. case CDQUOTE:
  11210. synstack->syntax = DQSYNTAX;
  11211. synstack->dblquote = 1;
  11212. toggledq:
  11213. if (synstack->varnest)
  11214. synstack->innerdq ^= 1;
  11215. goto quotemark;
  11216. case CENDQUOTE:
  11217. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11218. if (eofmark != NULL && synstack->varnest == 0) {
  11219. USTPUTC(c, out);
  11220. break;
  11221. }
  11222. if (synstack->dqvarnest == 0) {
  11223. synstack->syntax = BASESYNTAX;
  11224. synstack->dblquote = 0;
  11225. }
  11226. quotef = 1;
  11227. if (c == '"')
  11228. goto toggledq;
  11229. goto quotemark;
  11230. case CVAR: /* '$' */
  11231. PARSESUB(); /* parse substitution */
  11232. break;
  11233. case CENDVAR: /* '}' */
  11234. if (!synstack->innerdq && synstack->varnest > 0) {
  11235. if (!--synstack->varnest && synstack->varpushed)
  11236. synstack_pop(&synstack);
  11237. else if (synstack->dqvarnest > 0)
  11238. synstack->dqvarnest--;
  11239. c = CTLENDVAR;
  11240. }
  11241. USTPUTC(c, out);
  11242. break;
  11243. #if ENABLE_FEATURE_SH_MATH
  11244. case CLP: /* '(' in arithmetic */
  11245. synstack->parenlevel++;
  11246. USTPUTC(c, out);
  11247. break;
  11248. case CRP: /* ')' in arithmetic */
  11249. if (synstack->parenlevel > 0) {
  11250. synstack->parenlevel--;
  11251. } else {
  11252. if (pgetc_eatbnl() == ')') {
  11253. c = CTLENDARI;
  11254. synstack_pop(&synstack);
  11255. } else {
  11256. /*
  11257. * unbalanced parens
  11258. * (don't 2nd guess - no error)
  11259. */
  11260. pungetc();
  11261. }
  11262. }
  11263. USTPUTC(c, out);
  11264. break;
  11265. #endif
  11266. case CBQUOTE: /* '`' */
  11267. if (checkkwd & CHKEOFMARK) {
  11268. quotef = 1;
  11269. USTPUTC('`', out);
  11270. break;
  11271. }
  11272. PARSEBACKQOLD();
  11273. break;
  11274. case CENDFILE:
  11275. goto endword; /* exit outer loop */
  11276. case CIGN:
  11277. break;
  11278. default:
  11279. if (synstack->varnest == 0) {
  11280. #if BASH_REDIR_OUTPUT
  11281. if (c == '&') {
  11282. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11283. if (pgetc() == '>')
  11284. c = 0x100 + '>'; /* flag &> */
  11285. pungetc();
  11286. }
  11287. #endif
  11288. goto endword; /* exit outer loop */
  11289. }
  11290. IF_ASH_ALIAS(if (c != PEOA))
  11291. USTPUTC(c, out);
  11292. }
  11293. c = pgetc();
  11294. } /* for (;;) */
  11295. endword:
  11296. #if ENABLE_FEATURE_SH_MATH
  11297. if (synstack->syntax == ARISYNTAX)
  11298. raise_error_syntax("missing '))'");
  11299. #endif
  11300. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11301. raise_error_syntax("unterminated quoted string");
  11302. if (synstack->varnest != 0) {
  11303. /* { */
  11304. raise_error_syntax("missing '}'");
  11305. }
  11306. USTPUTC('\0', out);
  11307. len = out - (char *)stackblock();
  11308. out = stackblock();
  11309. if (eofmark == NULL) {
  11310. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11311. && quotef == 0
  11312. ) {
  11313. if (isdigit_str9(out)) {
  11314. PARSEREDIR(); /* passed as params: out, c */
  11315. lasttoken = TREDIR;
  11316. return lasttoken;
  11317. }
  11318. /* else: non-number X seen, interpret it
  11319. * as "NNNX>file" = "NNNX >file" */
  11320. }
  11321. pungetc();
  11322. }
  11323. quoteflag = quotef;
  11324. backquotelist = bqlist;
  11325. grabstackblock(len);
  11326. wordtext = out;
  11327. lasttoken = TWORD;
  11328. return lasttoken;
  11329. /* end of readtoken routine */
  11330. /*
  11331. * Check to see whether we are at the end of the here document. When this
  11332. * is called, c is set to the first character of the next input line. If
  11333. * we are at the end of the here document, this routine sets the c to PEOF.
  11334. */
  11335. checkend: {
  11336. if (realeofmark(eofmark)) {
  11337. int markloc;
  11338. char *p;
  11339. #if ENABLE_ASH_ALIAS
  11340. if (c == PEOA)
  11341. c = pgetc_without_PEOA();
  11342. #endif
  11343. if (striptabs) {
  11344. while (c == '\t') {
  11345. c = pgetc_without_PEOA();
  11346. }
  11347. }
  11348. markloc = out - (char *)stackblock();
  11349. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11350. if (c != *p)
  11351. goto more_heredoc;
  11352. c = pgetc_without_PEOA();
  11353. }
  11354. if (c == '\n' || c == PEOF) {
  11355. c = PEOF;
  11356. g_parsefile->linno++;
  11357. needprompt = doprompt;
  11358. } else {
  11359. int len_here;
  11360. more_heredoc:
  11361. p = (char *)stackblock() + markloc + 1;
  11362. len_here = out - p;
  11363. if (len_here) {
  11364. len_here -= (c >= PEOF);
  11365. c = p[-1];
  11366. if (len_here) {
  11367. char *str;
  11368. str = alloca(len_here + 1);
  11369. *(char *)mempcpy(str, p, len_here) = '\0';
  11370. pushstring(str, NULL);
  11371. }
  11372. }
  11373. }
  11374. STADJUST((char *)stackblock() + markloc - out, out);
  11375. }
  11376. goto checkend_return;
  11377. }
  11378. /*
  11379. * Parse a redirection operator. The variable "out" points to a string
  11380. * specifying the fd to be redirected. The variable "c" contains the
  11381. * first character of the redirection operator.
  11382. */
  11383. parseredir: {
  11384. /* out is already checked to be a valid number or "" */
  11385. int fd = (*out == '\0' ? -1 : atoi(out));
  11386. union node *np;
  11387. np = stzalloc(sizeof(struct nfile));
  11388. if (c == '>') {
  11389. np->nfile.fd = 1;
  11390. c = pgetc_eatbnl();
  11391. if (c == '>')
  11392. np->type = NAPPEND;
  11393. else if (c == '|')
  11394. np->type = NCLOBBER;
  11395. else if (c == '&')
  11396. np->type = NTOFD;
  11397. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11398. else {
  11399. np->type = NTO;
  11400. pungetc();
  11401. }
  11402. }
  11403. #if BASH_REDIR_OUTPUT
  11404. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11405. np->nfile.fd = 1;
  11406. pgetc(); /* this is '>', no need to check */
  11407. np->type = NTO2;
  11408. }
  11409. #endif
  11410. else { /* c == '<' */
  11411. /*np->nfile.fd = 0; - stzalloc did it */
  11412. c = pgetc_eatbnl();
  11413. switch (c) {
  11414. case '<':
  11415. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11416. np = stzalloc(sizeof(struct nhere));
  11417. /*np->nfile.fd = 0; - stzalloc did it */
  11418. }
  11419. np->type = NHERE;
  11420. heredoc = stzalloc(sizeof(struct heredoc));
  11421. heredoc->here = np;
  11422. c = pgetc_eatbnl();
  11423. if (c == '-') {
  11424. heredoc->striptabs = 1;
  11425. } else {
  11426. /*heredoc->striptabs = 0; - stzalloc did it */
  11427. pungetc();
  11428. }
  11429. break;
  11430. case '&':
  11431. np->type = NFROMFD;
  11432. break;
  11433. case '>':
  11434. np->type = NFROMTO;
  11435. break;
  11436. default:
  11437. np->type = NFROM;
  11438. pungetc();
  11439. break;
  11440. }
  11441. }
  11442. if (fd >= 0)
  11443. np->nfile.fd = fd;
  11444. redirnode = np;
  11445. goto parseredir_return;
  11446. }
  11447. /*
  11448. * Parse a substitution. At this point, we have read the dollar sign
  11449. * and nothing else.
  11450. */
  11451. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11452. * (assuming ascii char codes, as the original implementation did) */
  11453. #define is_special(c) \
  11454. (((unsigned)(c) - 33 < 32) \
  11455. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11456. parsesub: {
  11457. unsigned char subtype;
  11458. int typeloc;
  11459. c = pgetc_eatbnl();
  11460. if ((checkkwd & CHKEOFMARK)
  11461. || c > 255 /* PEOA or PEOF */
  11462. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11463. ) {
  11464. #if BASH_DOLLAR_SQUOTE
  11465. if (synstack->syntax != DQSYNTAX && c == '\'')
  11466. bash_dollar_squote = 1;
  11467. else
  11468. #endif
  11469. USTPUTC('$', out);
  11470. pungetc();
  11471. } else if (c == '(') {
  11472. /* $(command) or $((arith)) */
  11473. if (pgetc_eatbnl() == '(') {
  11474. #if ENABLE_FEATURE_SH_MATH
  11475. PARSEARITH();
  11476. #else
  11477. raise_error_syntax("support for $((arith)) is disabled");
  11478. #endif
  11479. } else {
  11480. pungetc();
  11481. PARSEBACKQNEW();
  11482. }
  11483. } else {
  11484. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11485. smalluint newsyn = synstack->syntax;
  11486. USTPUTC(CTLVAR, out);
  11487. typeloc = out - (char *)stackblock();
  11488. STADJUST(1, out);
  11489. subtype = VSNORMAL;
  11490. if (c == '{') {
  11491. c = pgetc_eatbnl();
  11492. subtype = 0;
  11493. }
  11494. varname:
  11495. if (is_name(c)) {
  11496. /* $[{[#]]NAME[}] */
  11497. do {
  11498. STPUTC(c, out);
  11499. c = pgetc_eatbnl();
  11500. } while (is_in_name(c));
  11501. } else if (isdigit(c)) {
  11502. /* $[{[#]]NUM[}] */
  11503. do {
  11504. STPUTC(c, out);
  11505. c = pgetc_eatbnl();
  11506. } while (isdigit(c));
  11507. } else if (c != '}') {
  11508. /* $[{[#]]<specialchar>[}] */
  11509. int cc = c;
  11510. c = pgetc_eatbnl();
  11511. if (!subtype && cc == '#') {
  11512. subtype = VSLENGTH;
  11513. if (c == '_' || isalnum(c))
  11514. goto varname;
  11515. cc = c;
  11516. c = pgetc_eatbnl();
  11517. if (cc == '}' || c != '}') {
  11518. pungetc();
  11519. subtype = 0;
  11520. c = cc;
  11521. cc = '#';
  11522. }
  11523. }
  11524. if (!is_special(cc)) {
  11525. if (subtype == VSLENGTH)
  11526. subtype = 0;
  11527. goto badsub;
  11528. }
  11529. USTPUTC(cc, out);
  11530. } else
  11531. goto badsub;
  11532. if (c != '}' && subtype == VSLENGTH) {
  11533. /* ${#VAR didn't end with } */
  11534. goto badsub;
  11535. }
  11536. if (subtype == 0) {
  11537. static const char types[] ALIGN1 = "}-+?=";
  11538. /* ${VAR...} but not $VAR or ${#VAR} */
  11539. /* c == first char after VAR */
  11540. int cc = c;
  11541. switch (c) {
  11542. case ':':
  11543. c = pgetc_eatbnl();
  11544. #if BASH_SUBSTR
  11545. /* This check is only needed to not misinterpret
  11546. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11547. * constructs.
  11548. */
  11549. if (!strchr(types, c)) {
  11550. subtype = VSSUBSTR;
  11551. pungetc();
  11552. break; /* "goto badsub" is bigger (!) */
  11553. }
  11554. #endif
  11555. subtype = VSNUL;
  11556. /*FALLTHROUGH*/
  11557. default: {
  11558. const char *p = strchr(types, c);
  11559. if (p == NULL)
  11560. break;
  11561. subtype |= p - types + VSNORMAL;
  11562. break;
  11563. }
  11564. case '%':
  11565. case '#':
  11566. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11567. c = pgetc_eatbnl();
  11568. if (c == cc)
  11569. subtype++;
  11570. else
  11571. pungetc();
  11572. newsyn = BASESYNTAX;
  11573. break;
  11574. #if BASH_PATTERN_SUBST
  11575. case '/':
  11576. /* ${v/[/]pattern/repl} */
  11577. //TODO: encode pattern and repl separately.
  11578. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11579. // are broken (should print "ONE")
  11580. subtype = VSREPLACE;
  11581. newsyn = BASESYNTAX;
  11582. c = pgetc_eatbnl();
  11583. if (c != '/')
  11584. goto badsub;
  11585. subtype++; /* VSREPLACEALL */
  11586. break;
  11587. #endif
  11588. }
  11589. } else {
  11590. badsub:
  11591. pungetc();
  11592. }
  11593. if (newsyn == ARISYNTAX)
  11594. newsyn = DQSYNTAX;
  11595. if ((newsyn != synstack->syntax || synstack->innerdq)
  11596. && subtype != VSNORMAL
  11597. ) {
  11598. synstack_push(&synstack,
  11599. synstack->prev ?: alloca(sizeof(*synstack)),
  11600. newsyn);
  11601. synstack->varpushed = 1;
  11602. synstack->dblquote = newsyn != BASESYNTAX;
  11603. }
  11604. ((unsigned char *)stackblock())[typeloc] = subtype;
  11605. if (subtype != VSNORMAL) {
  11606. synstack->varnest++;
  11607. if (synstack->dblquote)
  11608. synstack->dqvarnest++;
  11609. }
  11610. STPUTC('=', out);
  11611. }
  11612. goto parsesub_return;
  11613. }
  11614. /*
  11615. * Called to parse command substitutions. Newstyle is set if the command
  11616. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11617. * list of commands (passed by reference), and savelen is the number of
  11618. * characters on the top of the stack which must be preserved.
  11619. */
  11620. parsebackq: {
  11621. struct nodelist **nlpp;
  11622. union node *n;
  11623. char *str;
  11624. size_t savelen;
  11625. smallint saveprompt = 0;
  11626. str = NULL;
  11627. savelen = out - (char *)stackblock();
  11628. if (savelen > 0) {
  11629. /*
  11630. * FIXME: this can allocate very large block on stack and SEGV.
  11631. * Example:
  11632. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11633. * allocates 100kb for every command subst. With about
  11634. * a hundred command substitutions stack overflows.
  11635. * With larger prepended string, SEGV happens sooner.
  11636. */
  11637. str = alloca(savelen);
  11638. memcpy(str, stackblock(), savelen);
  11639. }
  11640. if (oldstyle) {
  11641. /* We must read until the closing backquote, giving special
  11642. * treatment to some slashes, and then push the string and
  11643. * reread it as input, interpreting it normally.
  11644. */
  11645. char *pout;
  11646. size_t psavelen;
  11647. char *pstr;
  11648. STARTSTACKSTR(pout);
  11649. for (;;) {
  11650. int pc;
  11651. setprompt_if(needprompt, 2);
  11652. pc = pgetc_eatbnl();
  11653. switch (pc) {
  11654. case '`':
  11655. goto done;
  11656. case '\\':
  11657. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11658. if (pc != '\\' && pc != '`' && pc != '$'
  11659. && (!synstack->dblquote || pc != '"')
  11660. ) {
  11661. STPUTC('\\', pout);
  11662. }
  11663. if (pc <= 255 /* not PEOA or PEOF */) {
  11664. break;
  11665. }
  11666. /* fall through */
  11667. case PEOF:
  11668. IF_ASH_ALIAS(case PEOA:)
  11669. raise_error_syntax("EOF in backquote substitution");
  11670. case '\n':
  11671. nlnoprompt();
  11672. break;
  11673. default:
  11674. break;
  11675. }
  11676. STPUTC(pc, pout);
  11677. }
  11678. done:
  11679. STPUTC('\0', pout);
  11680. psavelen = pout - (char *)stackblock();
  11681. if (psavelen > 0) {
  11682. pstr = grabstackstr(pout);
  11683. setinputstring(pstr);
  11684. }
  11685. }
  11686. nlpp = &bqlist;
  11687. while (*nlpp)
  11688. nlpp = &(*nlpp)->next;
  11689. *nlpp = stzalloc(sizeof(**nlpp));
  11690. /* (*nlpp)->next = NULL; - stzalloc did it */
  11691. if (oldstyle) {
  11692. saveprompt = doprompt;
  11693. doprompt = 0;
  11694. }
  11695. n = list(2);
  11696. if (oldstyle)
  11697. doprompt = saveprompt;
  11698. else if (readtoken() != TRP)
  11699. raise_error_unexpected_syntax(TRP);
  11700. (*nlpp)->n = n;
  11701. if (oldstyle) {
  11702. /*
  11703. * Start reading from old file again, ignoring any pushed back
  11704. * tokens left from the backquote parsing
  11705. */
  11706. popfile();
  11707. tokpushback = 0;
  11708. }
  11709. while (stackblocksize() <= savelen)
  11710. growstackblock();
  11711. STARTSTACKSTR(out);
  11712. if (str) {
  11713. memcpy(out, str, savelen);
  11714. STADJUST(savelen, out);
  11715. }
  11716. USTPUTC(CTLBACKQ, out);
  11717. if (oldstyle)
  11718. goto parsebackq_oldreturn;
  11719. goto parsebackq_newreturn;
  11720. }
  11721. #if ENABLE_FEATURE_SH_MATH
  11722. /*
  11723. * Parse an arithmetic expansion (indicate start of one and set state)
  11724. */
  11725. parsearith: {
  11726. synstack_push(&synstack,
  11727. synstack->prev ?: alloca(sizeof(*synstack)),
  11728. ARISYNTAX);
  11729. synstack->dblquote = 1;
  11730. USTPUTC(CTLARI, out);
  11731. goto parsearith_return;
  11732. }
  11733. #endif
  11734. } /* end of readtoken */
  11735. /*
  11736. * Read the next input token.
  11737. * If the token is a word, we set backquotelist to the list of cmds in
  11738. * backquotes. We set quoteflag to true if any part of the word was
  11739. * quoted.
  11740. * If the token is TREDIR, then we set redirnode to a structure containing
  11741. * the redirection.
  11742. *
  11743. * [Change comment: here documents and internal procedures]
  11744. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11745. * word parsing code into a separate routine. In this case, readtoken
  11746. * doesn't need to have any internal procedures, but parseword does.
  11747. * We could also make parseoperator in essence the main routine, and
  11748. * have parseword (readtoken1?) handle both words and redirection.]
  11749. */
  11750. #define NEW_xxreadtoken
  11751. #ifdef NEW_xxreadtoken
  11752. /* singles must be first! */
  11753. static const char xxreadtoken_chars[7] ALIGN1 = {
  11754. '\n', '(', ')', /* singles */
  11755. '&', '|', ';', /* doubles */
  11756. 0
  11757. };
  11758. #define xxreadtoken_singles 3
  11759. #define xxreadtoken_doubles 3
  11760. static const char xxreadtoken_tokens[] ALIGN1 = {
  11761. TNL, TLP, TRP, /* only single occurrence allowed */
  11762. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11763. TEOF, /* corresponds to trailing nul */
  11764. TAND, TOR, TENDCASE /* if double occurrence */
  11765. };
  11766. static int
  11767. xxreadtoken(void)
  11768. {
  11769. int c;
  11770. if (tokpushback) {
  11771. tokpushback = 0;
  11772. return lasttoken;
  11773. }
  11774. setprompt_if(needprompt, 2);
  11775. for (;;) { /* until token or start of word found */
  11776. c = pgetc_eatbnl();
  11777. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11778. continue;
  11779. if (c == '#') {
  11780. while ((c = pgetc()) != '\n' && c != PEOF)
  11781. continue;
  11782. pungetc();
  11783. } else if (c == '\\') {
  11784. break; /* return readtoken1(...) */
  11785. } else {
  11786. const char *p;
  11787. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11788. if (c != PEOF) {
  11789. if (c == '\n') {
  11790. nlnoprompt();
  11791. }
  11792. p = strchr(xxreadtoken_chars, c);
  11793. if (p == NULL)
  11794. break; /* return readtoken1(...) */
  11795. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11796. int cc = pgetc_eatbnl();
  11797. if (cc == c) { /* double occurrence? */
  11798. p += xxreadtoken_doubles + 1;
  11799. } else {
  11800. pungetc();
  11801. #if BASH_REDIR_OUTPUT
  11802. if (c == '&' && cc == '>') /* &> */
  11803. break; /* return readtoken1(...) */
  11804. #endif
  11805. }
  11806. }
  11807. }
  11808. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11809. return lasttoken;
  11810. }
  11811. } /* for (;;) */
  11812. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11813. }
  11814. #else /* old xxreadtoken */
  11815. #define RETURN(token) return lasttoken = token
  11816. static int
  11817. xxreadtoken(void)
  11818. {
  11819. int c;
  11820. if (tokpushback) {
  11821. tokpushback = 0;
  11822. return lasttoken;
  11823. }
  11824. setprompt_if(needprompt, 2);
  11825. for (;;) { /* until token or start of word found */
  11826. c = pgetc_eatbnl();
  11827. switch (c) {
  11828. case ' ': case '\t':
  11829. IF_ASH_ALIAS(case PEOA:)
  11830. continue;
  11831. case '#':
  11832. while ((c = pgetc()) != '\n' && c != PEOF)
  11833. continue;
  11834. pungetc();
  11835. continue;
  11836. case '\n':
  11837. nlnoprompt();
  11838. RETURN(TNL);
  11839. case PEOF:
  11840. RETURN(TEOF);
  11841. case '&':
  11842. if (pgetc_eatbnl() == '&')
  11843. RETURN(TAND);
  11844. pungetc();
  11845. RETURN(TBACKGND);
  11846. case '|':
  11847. if (pgetc_eatbnl() == '|')
  11848. RETURN(TOR);
  11849. pungetc();
  11850. RETURN(TPIPE);
  11851. case ';':
  11852. if (pgetc_eatbnl() == ';')
  11853. RETURN(TENDCASE);
  11854. pungetc();
  11855. RETURN(TSEMI);
  11856. case '(':
  11857. RETURN(TLP);
  11858. case ')':
  11859. RETURN(TRP);
  11860. }
  11861. break;
  11862. }
  11863. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11864. #undef RETURN
  11865. }
  11866. #endif /* old xxreadtoken */
  11867. static int
  11868. readtoken(void)
  11869. {
  11870. int t;
  11871. int kwd = checkkwd;
  11872. #if DEBUG
  11873. smallint alreadyseen = tokpushback;
  11874. #endif
  11875. #if ENABLE_ASH_ALIAS
  11876. top:
  11877. #endif
  11878. t = xxreadtoken();
  11879. /*
  11880. * eat newlines
  11881. */
  11882. if (kwd & CHKNL) {
  11883. while (t == TNL) {
  11884. parseheredoc();
  11885. t = xxreadtoken();
  11886. }
  11887. }
  11888. if (t != TWORD || quoteflag) {
  11889. goto out;
  11890. }
  11891. /*
  11892. * check for keywords
  11893. */
  11894. if (kwd & CHKKWD) {
  11895. const char *const *pp;
  11896. pp = findkwd(wordtext);
  11897. if (pp) {
  11898. lasttoken = t = pp - tokname_array;
  11899. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11900. goto out;
  11901. }
  11902. }
  11903. if (checkkwd & CHKALIAS) {
  11904. #if ENABLE_ASH_ALIAS
  11905. struct alias *ap;
  11906. ap = lookupalias(wordtext, 1);
  11907. if (ap != NULL) {
  11908. if (*ap->val) {
  11909. pushstring(ap->val, ap);
  11910. }
  11911. goto top;
  11912. }
  11913. #endif
  11914. }
  11915. out:
  11916. checkkwd = 0;
  11917. #if DEBUG
  11918. if (!alreadyseen)
  11919. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11920. else
  11921. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11922. #endif
  11923. return t;
  11924. }
  11925. static int
  11926. peektoken(void)
  11927. {
  11928. int t;
  11929. t = readtoken();
  11930. tokpushback = 1;
  11931. return t;
  11932. }
  11933. /*
  11934. * Read and parse a command. Returns NODE_EOF on end of file.
  11935. * (NULL is a valid parse tree indicating a blank line.)
  11936. */
  11937. static union node *
  11938. parsecmd(int interact)
  11939. {
  11940. tokpushback = 0;
  11941. checkkwd = 0;
  11942. heredoclist = 0;
  11943. doprompt = interact;
  11944. setprompt_if(doprompt, doprompt);
  11945. needprompt = 0;
  11946. return list(1);
  11947. }
  11948. /*
  11949. * Input any here documents.
  11950. */
  11951. static void
  11952. parseheredoc(void)
  11953. {
  11954. struct heredoc *here;
  11955. union node *n;
  11956. here = heredoclist;
  11957. heredoclist = NULL;
  11958. while (here) {
  11959. tokpushback = 0;
  11960. setprompt_if(needprompt, 2);
  11961. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11962. here->eofmark, here->striptabs);
  11963. n = stzalloc(sizeof(struct narg));
  11964. n->narg.type = NARG;
  11965. /*n->narg.next = NULL; - stzalloc did it */
  11966. n->narg.text = wordtext;
  11967. n->narg.backquote = backquotelist;
  11968. here->here->nhere.doc = n;
  11969. here = here->next;
  11970. }
  11971. }
  11972. static const char *
  11973. expandstr(const char *ps, int syntax_type)
  11974. {
  11975. union node n;
  11976. int saveprompt;
  11977. struct parsefile *file_stop = g_parsefile;
  11978. volatile int saveint;
  11979. struct jmploc *volatile savehandler = exception_handler;
  11980. struct jmploc jmploc;
  11981. /* XXX Fix (char *) cast. */
  11982. setinputstring((char *)ps);
  11983. saveprompt = doprompt;
  11984. doprompt = 0;
  11985. /* readtoken1() might die horribly.
  11986. * Try a prompt with syntactically wrong command:
  11987. * PS1='$(date "+%H:%M:%S) > '
  11988. */
  11989. SAVE_INT(saveint);
  11990. if (setjmp(jmploc.loc) == 0) {
  11991. exception_handler = &jmploc;
  11992. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11993. }
  11994. exception_handler = savehandler;
  11995. RESTORE_INT(saveint);
  11996. doprompt = saveprompt;
  11997. /* Try: PS1='`xxx(`' */
  11998. unwindfiles(file_stop);
  11999. n.narg.type = NARG;
  12000. n.narg.next = NULL;
  12001. n.narg.text = wordtext;
  12002. n.narg.backquote = backquotelist;
  12003. /* expandarg() might fail too:
  12004. * PS1='$((123+))'
  12005. */
  12006. SAVE_INT(saveint);
  12007. if (setjmp(jmploc.loc) == 0) {
  12008. exception_handler = &jmploc;
  12009. expandarg(&n, NULL, EXP_QUOTED);
  12010. }
  12011. exception_handler = savehandler;
  12012. RESTORE_INT(saveint);
  12013. return stackblock();
  12014. }
  12015. static inline int
  12016. parser_eof(void)
  12017. {
  12018. return tokpushback && lasttoken == TEOF;
  12019. }
  12020. /*
  12021. * Execute a command or commands contained in a string.
  12022. */
  12023. static int
  12024. evalstring(char *s, int flags)
  12025. {
  12026. struct jmploc *volatile savehandler;
  12027. struct jmploc jmploc;
  12028. int ex;
  12029. union node *n;
  12030. struct stackmark smark;
  12031. int status;
  12032. s = sstrdup(s);
  12033. setinputstring(s);
  12034. setstackmark(&smark);
  12035. status = 0;
  12036. /* On exception inside execution loop, we must popfile().
  12037. * Try interactively:
  12038. * readonly a=a
  12039. * command eval "a=b" # throws "is read only" error
  12040. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12041. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12042. */
  12043. savehandler = exception_handler;
  12044. ex = setjmp(jmploc.loc);
  12045. if (ex)
  12046. goto out;
  12047. exception_handler = &jmploc;
  12048. while ((n = parsecmd(0)) != NODE_EOF) {
  12049. int i;
  12050. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12051. if (n)
  12052. status = i;
  12053. popstackmark(&smark);
  12054. if (evalskip)
  12055. break;
  12056. }
  12057. out:
  12058. popstackmark(&smark);
  12059. popfile();
  12060. stunalloc(s);
  12061. exception_handler = savehandler;
  12062. if (ex)
  12063. longjmp(exception_handler->loc, ex);
  12064. return status;
  12065. }
  12066. /*
  12067. * The eval command.
  12068. */
  12069. static int FAST_FUNC
  12070. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12071. {
  12072. char *p;
  12073. char *concat;
  12074. if (argv[1]) {
  12075. p = argv[1];
  12076. argv += 2;
  12077. if (argv[0]) {
  12078. STARTSTACKSTR(concat);
  12079. for (;;) {
  12080. concat = stack_putstr(p, concat);
  12081. p = *argv++;
  12082. if (p == NULL)
  12083. break;
  12084. STPUTC(' ', concat);
  12085. }
  12086. STPUTC('\0', concat);
  12087. p = grabstackstr(concat);
  12088. }
  12089. return evalstring(p, flags & EV_TESTED);
  12090. }
  12091. return 0;
  12092. }
  12093. /*
  12094. * Read and execute commands.
  12095. * "Top" is nonzero for the top level command loop;
  12096. * it turns on prompting if the shell is interactive.
  12097. */
  12098. static int
  12099. cmdloop(int top)
  12100. {
  12101. union node *n;
  12102. struct stackmark smark;
  12103. int inter;
  12104. int status = 0;
  12105. int numeof = 0;
  12106. TRACE(("cmdloop(%d) called\n", top));
  12107. for (;;) {
  12108. int skip;
  12109. setstackmark(&smark);
  12110. #if JOBS
  12111. if (doing_jobctl)
  12112. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12113. #endif
  12114. inter = 0;
  12115. if (iflag && top) {
  12116. inter++;
  12117. chkmail();
  12118. }
  12119. n = parsecmd(inter);
  12120. #if DEBUG
  12121. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12122. showtree(n);
  12123. #endif
  12124. if (n == NODE_EOF) {
  12125. if (!top || numeof >= 50)
  12126. break;
  12127. if (!stoppedjobs()) {
  12128. if (!Iflag)
  12129. break;
  12130. out2str("\nUse \"exit\" to leave shell.\n");
  12131. }
  12132. numeof++;
  12133. } else if (nflag == 0) {
  12134. int i;
  12135. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12136. job_warning >>= 1;
  12137. numeof = 0;
  12138. i = evaltree(n, 0);
  12139. if (n)
  12140. status = i;
  12141. }
  12142. popstackmark(&smark);
  12143. skip = evalskip;
  12144. if (skip) {
  12145. evalskip &= ~SKIPFUNC;
  12146. break;
  12147. }
  12148. }
  12149. return status;
  12150. }
  12151. /*
  12152. * Take commands from a file. To be compatible we should do a path
  12153. * search for the file, which is necessary to find sub-commands.
  12154. */
  12155. static char *
  12156. find_dot_file(char *name)
  12157. {
  12158. char *fullname;
  12159. const char *path = pathval();
  12160. struct stat statb;
  12161. /* don't try this for absolute or relative paths */
  12162. if (strchr(name, '/'))
  12163. return name;
  12164. while ((fullname = path_advance(&path, name)) != NULL) {
  12165. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  12166. /*
  12167. * Don't bother freeing here, since it will
  12168. * be freed by the caller.
  12169. */
  12170. return fullname;
  12171. }
  12172. if (fullname != name)
  12173. stunalloc(fullname);
  12174. }
  12175. /* not found in PATH */
  12176. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12177. return name;
  12178. #else
  12179. ash_msg_and_raise_error("%s: not found", name);
  12180. /* NOTREACHED */
  12181. #endif
  12182. }
  12183. static int FAST_FUNC
  12184. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12185. {
  12186. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12187. int status = 0;
  12188. char *fullname;
  12189. char **argv;
  12190. char *args_need_save;
  12191. volatile struct shparam saveparam;
  12192. //???
  12193. // struct strlist *sp;
  12194. // for (sp = cmdenviron; sp; sp = sp->next)
  12195. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12196. nextopt(nullstr); /* handle possible "--" */
  12197. argv = argptr;
  12198. if (!argv[0]) {
  12199. /* bash says: "bash: .: filename argument required" */
  12200. return 2; /* bash compat */
  12201. }
  12202. /* This aborts if file isn't found, which is POSIXly correct.
  12203. * bash returns exitcode 1 instead.
  12204. */
  12205. fullname = find_dot_file(argv[0]);
  12206. argv++;
  12207. args_need_save = argv[0];
  12208. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12209. int argc;
  12210. saveparam = shellparam;
  12211. shellparam.malloced = 0;
  12212. argc = 1;
  12213. while (argv[argc])
  12214. argc++;
  12215. shellparam.nparam = argc;
  12216. shellparam.p = argv;
  12217. };
  12218. /* This aborts if file can't be opened, which is POSIXly correct.
  12219. * bash returns exitcode 1 instead.
  12220. */
  12221. setinputfile(fullname, INPUT_PUSH_FILE);
  12222. commandname = fullname;
  12223. status = cmdloop(0);
  12224. popfile();
  12225. if (args_need_save) {
  12226. freeparam(&shellparam);
  12227. shellparam = saveparam;
  12228. };
  12229. return status;
  12230. }
  12231. static int FAST_FUNC
  12232. exitcmd(int argc UNUSED_PARAM, char **argv)
  12233. {
  12234. if (stoppedjobs())
  12235. return 0;
  12236. if (argv[1])
  12237. exitstatus = number(argv[1]);
  12238. raise_exception(EXEXIT);
  12239. /* NOTREACHED */
  12240. }
  12241. /*
  12242. * Read a file containing shell functions.
  12243. */
  12244. static void
  12245. readcmdfile(char *name)
  12246. {
  12247. setinputfile(name, INPUT_PUSH_FILE);
  12248. cmdloop(0);
  12249. popfile();
  12250. }
  12251. /* ============ find_command inplementation */
  12252. /*
  12253. * Resolve a command name. If you change this routine, you may have to
  12254. * change the shellexec routine as well.
  12255. */
  12256. static void
  12257. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12258. {
  12259. struct tblentry *cmdp;
  12260. int idx;
  12261. int prev;
  12262. char *fullname;
  12263. struct stat statb;
  12264. int e;
  12265. int updatetbl;
  12266. struct builtincmd *bcmd;
  12267. /* If name contains a slash, don't use PATH or hash table */
  12268. if (strchr(name, '/') != NULL) {
  12269. entry->u.index = -1;
  12270. if (act & DO_ABS) {
  12271. while (stat(name, &statb) < 0) {
  12272. #ifdef SYSV
  12273. if (errno == EINTR)
  12274. continue;
  12275. #endif
  12276. entry->cmdtype = CMDUNKNOWN;
  12277. return;
  12278. }
  12279. }
  12280. entry->cmdtype = CMDNORMAL;
  12281. return;
  12282. }
  12283. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12284. updatetbl = (path == pathval());
  12285. if (!updatetbl) {
  12286. act |= DO_ALTPATH;
  12287. if (strstr(path, "%builtin") != NULL)
  12288. act |= DO_ALTBLTIN;
  12289. }
  12290. /* If name is in the table, check answer will be ok */
  12291. cmdp = cmdlookup(name, 0);
  12292. if (cmdp != NULL) {
  12293. int bit;
  12294. switch (cmdp->cmdtype) {
  12295. default:
  12296. #if DEBUG
  12297. abort();
  12298. #endif
  12299. case CMDNORMAL:
  12300. bit = DO_ALTPATH;
  12301. break;
  12302. case CMDFUNCTION:
  12303. bit = DO_NOFUNC;
  12304. break;
  12305. case CMDBUILTIN:
  12306. bit = DO_ALTBLTIN;
  12307. break;
  12308. }
  12309. if (act & bit) {
  12310. updatetbl = 0;
  12311. cmdp = NULL;
  12312. } else if (cmdp->rehash == 0)
  12313. /* if not invalidated by cd, we're done */
  12314. goto success;
  12315. }
  12316. /* If %builtin not in path, check for builtin next */
  12317. bcmd = find_builtin(name);
  12318. if (bcmd) {
  12319. if (IS_BUILTIN_REGULAR(bcmd))
  12320. goto builtin_success;
  12321. if (act & DO_ALTPATH) {
  12322. if (!(act & DO_ALTBLTIN))
  12323. goto builtin_success;
  12324. } else if (builtinloc <= 0) {
  12325. goto builtin_success;
  12326. }
  12327. }
  12328. #if ENABLE_FEATURE_SH_STANDALONE
  12329. {
  12330. int applet_no = find_applet_by_name(name);
  12331. if (applet_no >= 0) {
  12332. entry->cmdtype = CMDNORMAL;
  12333. entry->u.index = -2 - applet_no;
  12334. return;
  12335. }
  12336. }
  12337. #endif
  12338. /* We have to search path. */
  12339. prev = -1; /* where to start */
  12340. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12341. if (cmdp->cmdtype == CMDBUILTIN)
  12342. prev = builtinloc;
  12343. else
  12344. prev = cmdp->param.index;
  12345. }
  12346. e = ENOENT;
  12347. idx = -1;
  12348. loop:
  12349. while ((fullname = path_advance(&path, name)) != NULL) {
  12350. stunalloc(fullname);
  12351. /* NB: code below will still use fullname
  12352. * despite it being "unallocated" */
  12353. idx++;
  12354. if (pathopt) {
  12355. if (prefix(pathopt, "builtin")) {
  12356. if (bcmd)
  12357. goto builtin_success;
  12358. continue;
  12359. }
  12360. if ((act & DO_NOFUNC)
  12361. || !prefix(pathopt, "func")
  12362. ) { /* ignore unimplemented options */
  12363. continue;
  12364. }
  12365. }
  12366. /* if rehash, don't redo absolute path names */
  12367. if (fullname[0] == '/' && idx <= prev) {
  12368. if (idx < prev)
  12369. continue;
  12370. TRACE(("searchexec \"%s\": no change\n", name));
  12371. goto success;
  12372. }
  12373. while (stat(fullname, &statb) < 0) {
  12374. #ifdef SYSV
  12375. if (errno == EINTR)
  12376. continue;
  12377. #endif
  12378. if (errno != ENOENT && errno != ENOTDIR)
  12379. e = errno;
  12380. goto loop;
  12381. }
  12382. e = EACCES; /* if we fail, this will be the error */
  12383. if (!S_ISREG(statb.st_mode))
  12384. continue;
  12385. if (pathopt) { /* this is a %func directory */
  12386. stalloc(strlen(fullname) + 1);
  12387. /* NB: stalloc will return space pointed by fullname
  12388. * (because we don't have any intervening allocations
  12389. * between stunalloc above and this stalloc) */
  12390. readcmdfile(fullname);
  12391. cmdp = cmdlookup(name, 0);
  12392. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12393. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12394. stunalloc(fullname);
  12395. goto success;
  12396. }
  12397. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12398. if (!updatetbl) {
  12399. entry->cmdtype = CMDNORMAL;
  12400. entry->u.index = idx;
  12401. return;
  12402. }
  12403. INT_OFF;
  12404. cmdp = cmdlookup(name, 1);
  12405. cmdp->cmdtype = CMDNORMAL;
  12406. cmdp->param.index = idx;
  12407. INT_ON;
  12408. goto success;
  12409. }
  12410. /* We failed. If there was an entry for this command, delete it */
  12411. if (cmdp && updatetbl)
  12412. delete_cmd_entry();
  12413. if (act & DO_ERR) {
  12414. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12415. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12416. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12417. char *argv[3];
  12418. argv[0] = (char*) "command_not_found_handle";
  12419. argv[1] = name;
  12420. argv[2] = NULL;
  12421. evalfun(hookp->param.func, 2, argv, 0);
  12422. entry->cmdtype = CMDUNKNOWN;
  12423. return;
  12424. }
  12425. #endif
  12426. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12427. }
  12428. entry->cmdtype = CMDUNKNOWN;
  12429. return;
  12430. builtin_success:
  12431. if (!updatetbl) {
  12432. entry->cmdtype = CMDBUILTIN;
  12433. entry->u.cmd = bcmd;
  12434. return;
  12435. }
  12436. INT_OFF;
  12437. cmdp = cmdlookup(name, 1);
  12438. cmdp->cmdtype = CMDBUILTIN;
  12439. cmdp->param.cmd = bcmd;
  12440. INT_ON;
  12441. success:
  12442. cmdp->rehash = 0;
  12443. entry->cmdtype = cmdp->cmdtype;
  12444. entry->u = cmdp->param;
  12445. }
  12446. /*
  12447. * The trap builtin.
  12448. */
  12449. static int FAST_FUNC
  12450. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12451. {
  12452. char *action;
  12453. char **ap;
  12454. int signo, exitcode;
  12455. nextopt(nullstr);
  12456. ap = argptr;
  12457. if (!*ap) {
  12458. for (signo = 0; signo < NSIG; signo++) {
  12459. char *tr = trap_ptr[signo];
  12460. if (tr) {
  12461. /* note: bash adds "SIG", but only if invoked
  12462. * as "bash". If called as "sh", or if set -o posix,
  12463. * then it prints short signal names.
  12464. * We are printing short names: */
  12465. out1fmt("trap -- %s %s\n",
  12466. single_quote(tr),
  12467. get_signame(signo));
  12468. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12469. * In this case, we will exit very soon, no need to free(). */
  12470. /* if (trap_ptr != trap && tp[0]) */
  12471. /* free(tr); */
  12472. }
  12473. }
  12474. /*
  12475. if (trap_ptr != trap) {
  12476. free(trap_ptr);
  12477. trap_ptr = trap;
  12478. }
  12479. */
  12480. return 0;
  12481. }
  12482. /* Why the second check?
  12483. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12484. * In this case, NUM is signal no, not an action.
  12485. */
  12486. action = NULL;
  12487. if (ap[1] && !is_number(ap[0]))
  12488. action = *ap++;
  12489. exitcode = 0;
  12490. while (*ap) {
  12491. signo = get_signum(*ap);
  12492. if (signo < 0) {
  12493. /* Mimic bash message exactly */
  12494. ash_msg("%s: invalid signal specification", *ap);
  12495. exitcode = 1;
  12496. goto next;
  12497. }
  12498. INT_OFF;
  12499. if (action) {
  12500. if (LONE_DASH(action))
  12501. action = NULL;
  12502. else {
  12503. if (action[0]) /* not NULL and not "" and not "-" */
  12504. may_have_traps = 1;
  12505. action = ckstrdup(action);
  12506. }
  12507. }
  12508. free(trap[signo]);
  12509. trap[signo] = action;
  12510. if (signo != 0)
  12511. setsignal(signo);
  12512. INT_ON;
  12513. next:
  12514. ap++;
  12515. }
  12516. return exitcode;
  12517. }
  12518. /* ============ Builtins */
  12519. #if ENABLE_ASH_HELP
  12520. static int FAST_FUNC
  12521. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12522. {
  12523. unsigned col;
  12524. unsigned i;
  12525. out1fmt(
  12526. "Built-in commands:\n"
  12527. "------------------\n");
  12528. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12529. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12530. builtintab[i].name + 1);
  12531. if (col > 60) {
  12532. out1fmt("\n");
  12533. col = 0;
  12534. }
  12535. }
  12536. # if ENABLE_FEATURE_SH_STANDALONE
  12537. {
  12538. const char *a = applet_names;
  12539. while (*a) {
  12540. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12541. if (col > 60) {
  12542. out1fmt("\n");
  12543. col = 0;
  12544. }
  12545. while (*a++ != '\0')
  12546. continue;
  12547. }
  12548. }
  12549. # endif
  12550. newline_and_flush(stdout);
  12551. return EXIT_SUCCESS;
  12552. }
  12553. #endif
  12554. #if MAX_HISTORY
  12555. static int FAST_FUNC
  12556. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12557. {
  12558. if (line_input_state)
  12559. show_history(line_input_state);
  12560. return EXIT_SUCCESS;
  12561. }
  12562. #endif
  12563. /*
  12564. * The export and readonly commands.
  12565. */
  12566. static int FAST_FUNC
  12567. exportcmd(int argc UNUSED_PARAM, char **argv)
  12568. {
  12569. struct var *vp;
  12570. char *name;
  12571. const char *p;
  12572. char **aptr;
  12573. char opt;
  12574. int flag;
  12575. int flag_off;
  12576. /* "readonly" in bash accepts, but ignores -n.
  12577. * We do the same: it saves a conditional in nextopt's param.
  12578. */
  12579. flag_off = 0;
  12580. while ((opt = nextopt("np")) != '\0') {
  12581. if (opt == 'n')
  12582. flag_off = VEXPORT;
  12583. }
  12584. flag = VEXPORT;
  12585. if (argv[0][0] == 'r') {
  12586. flag = VREADONLY;
  12587. flag_off = 0; /* readonly ignores -n */
  12588. }
  12589. flag_off = ~flag_off;
  12590. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12591. {
  12592. aptr = argptr;
  12593. name = *aptr;
  12594. if (name) {
  12595. do {
  12596. p = strchr(name, '=');
  12597. if (p != NULL) {
  12598. p++;
  12599. } else {
  12600. vp = *findvar(hashvar(name), name);
  12601. if (vp) {
  12602. vp->flags = ((vp->flags | flag) & flag_off);
  12603. continue;
  12604. }
  12605. }
  12606. setvar(name, p, (flag & flag_off));
  12607. } while ((name = *++aptr) != NULL);
  12608. return 0;
  12609. }
  12610. }
  12611. /* No arguments. Show the list of exported or readonly vars.
  12612. * -n is ignored.
  12613. */
  12614. showvars(argv[0], flag, 0);
  12615. return 0;
  12616. }
  12617. /*
  12618. * Delete a function if it exists.
  12619. */
  12620. static void
  12621. unsetfunc(const char *name)
  12622. {
  12623. struct tblentry *cmdp;
  12624. cmdp = cmdlookup(name, 0);
  12625. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12626. delete_cmd_entry();
  12627. }
  12628. /*
  12629. * The unset builtin command. We unset the function before we unset the
  12630. * variable to allow a function to be unset when there is a readonly variable
  12631. * with the same name.
  12632. */
  12633. static int FAST_FUNC
  12634. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12635. {
  12636. char **ap;
  12637. int i;
  12638. int flag = 0;
  12639. while ((i = nextopt("vf")) != 0) {
  12640. flag = i;
  12641. }
  12642. for (ap = argptr; *ap; ap++) {
  12643. if (flag != 'f') {
  12644. unsetvar(*ap);
  12645. continue;
  12646. }
  12647. if (flag != 'v')
  12648. unsetfunc(*ap);
  12649. }
  12650. return 0;
  12651. }
  12652. static const unsigned char timescmd_str[] ALIGN1 = {
  12653. ' ', offsetof(struct tms, tms_utime),
  12654. '\n', offsetof(struct tms, tms_stime),
  12655. ' ', offsetof(struct tms, tms_cutime),
  12656. '\n', offsetof(struct tms, tms_cstime),
  12657. 0
  12658. };
  12659. static int FAST_FUNC
  12660. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12661. {
  12662. unsigned clk_tck;
  12663. const unsigned char *p;
  12664. struct tms buf;
  12665. clk_tck = bb_clk_tck();
  12666. times(&buf);
  12667. p = timescmd_str;
  12668. do {
  12669. unsigned sec, frac;
  12670. unsigned long t;
  12671. t = *(clock_t *)(((char *) &buf) + p[1]);
  12672. sec = t / clk_tck;
  12673. frac = t % clk_tck;
  12674. out1fmt("%um%u.%03us%c",
  12675. sec / 60, sec % 60,
  12676. (frac * 1000) / clk_tck,
  12677. p[0]);
  12678. p += 2;
  12679. } while (*p);
  12680. return 0;
  12681. }
  12682. #if ENABLE_FEATURE_SH_MATH
  12683. /*
  12684. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12685. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12686. *
  12687. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12688. */
  12689. static int FAST_FUNC
  12690. letcmd(int argc UNUSED_PARAM, char **argv)
  12691. {
  12692. arith_t i;
  12693. argv++;
  12694. if (!*argv)
  12695. ash_msg_and_raise_error("expression expected");
  12696. do {
  12697. i = ash_arith(*argv);
  12698. } while (*++argv);
  12699. return !i;
  12700. }
  12701. #endif
  12702. /*
  12703. * The read builtin. Options:
  12704. * -r Do not interpret '\' specially
  12705. * -s Turn off echo (tty only)
  12706. * -n NCHARS Read NCHARS max
  12707. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12708. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12709. * -u FD Read from given FD instead of fd 0
  12710. * -d DELIM End on DELIM char, not newline
  12711. * This uses unbuffered input, which may be avoidable in some cases.
  12712. * TODO: bash also has:
  12713. * -a ARRAY Read into array[0],[1],etc
  12714. * -e Use line editing (tty only)
  12715. */
  12716. static int FAST_FUNC
  12717. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12718. {
  12719. struct builtin_read_params params;
  12720. const char *r;
  12721. int i;
  12722. memset(&params, 0, sizeof(params));
  12723. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12724. switch (i) {
  12725. case 'p':
  12726. params.opt_p = optionarg;
  12727. break;
  12728. case 'n':
  12729. params.opt_n = optionarg;
  12730. break;
  12731. case 's':
  12732. params.read_flags |= BUILTIN_READ_SILENT;
  12733. break;
  12734. case 't':
  12735. params.opt_t = optionarg;
  12736. break;
  12737. case 'r':
  12738. params.read_flags |= BUILTIN_READ_RAW;
  12739. break;
  12740. case 'u':
  12741. params.opt_u = optionarg;
  12742. break;
  12743. #if BASH_READ_D
  12744. case 'd':
  12745. params.opt_d = optionarg;
  12746. break;
  12747. #endif
  12748. default:
  12749. break;
  12750. }
  12751. }
  12752. params.argv = argptr;
  12753. params.setvar = setvar0;
  12754. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12755. /* "read -s" needs to save/restore termios, can't allow ^C
  12756. * to jump out of it.
  12757. */
  12758. again:
  12759. INT_OFF;
  12760. r = shell_builtin_read(&params);
  12761. INT_ON;
  12762. if ((uintptr_t)r == 1 && errno == EINTR) {
  12763. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12764. * Correct behavior is to not exit "read"
  12765. */
  12766. if (pending_sig == 0)
  12767. goto again;
  12768. }
  12769. if ((uintptr_t)r > 1)
  12770. ash_msg_and_raise_error(r);
  12771. return (uintptr_t)r;
  12772. }
  12773. static int FAST_FUNC
  12774. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12775. {
  12776. static const char permuser[3] ALIGN1 = "ogu";
  12777. mode_t mask;
  12778. int symbolic_mode = 0;
  12779. while (nextopt("S") != '\0') {
  12780. symbolic_mode = 1;
  12781. }
  12782. INT_OFF;
  12783. mask = umask(0);
  12784. umask(mask);
  12785. INT_ON;
  12786. if (*argptr == NULL) {
  12787. if (symbolic_mode) {
  12788. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12789. char *p = buf;
  12790. int i;
  12791. i = 2;
  12792. for (;;) {
  12793. *p++ = ',';
  12794. *p++ = permuser[i];
  12795. *p++ = '=';
  12796. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12797. if (!(mask & 0400)) *p++ = 'r';
  12798. if (!(mask & 0200)) *p++ = 'w';
  12799. if (!(mask & 0100)) *p++ = 'x';
  12800. mask <<= 3;
  12801. if (--i < 0)
  12802. break;
  12803. }
  12804. *p = '\0';
  12805. puts(buf + 1);
  12806. } else {
  12807. out1fmt("%04o\n", mask);
  12808. }
  12809. } else {
  12810. char *modestr = *argptr;
  12811. /* numeric umasks are taken as-is */
  12812. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12813. if (!isdigit(modestr[0]))
  12814. mask ^= 0777;
  12815. mask = bb_parse_mode(modestr, mask);
  12816. if ((unsigned)mask > 0777) {
  12817. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12818. }
  12819. if (!isdigit(modestr[0]))
  12820. mask ^= 0777;
  12821. umask(mask);
  12822. }
  12823. return 0;
  12824. }
  12825. static int FAST_FUNC
  12826. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12827. {
  12828. return shell_builtin_ulimit(argv);
  12829. }
  12830. /* ============ main() and helpers */
  12831. /*
  12832. * Called to exit the shell.
  12833. */
  12834. static void
  12835. exitshell(void)
  12836. {
  12837. struct jmploc loc;
  12838. char *p;
  12839. int status;
  12840. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12841. if (line_input_state)
  12842. save_history(line_input_state);
  12843. #endif
  12844. status = exitstatus;
  12845. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12846. if (setjmp(loc.loc)) {
  12847. if (exception_type == EXEXIT)
  12848. status = exitstatus;
  12849. goto out;
  12850. }
  12851. exception_handler = &loc;
  12852. p = trap[0];
  12853. if (p) {
  12854. trap[0] = NULL;
  12855. evalskip = 0;
  12856. evalstring(p, 0);
  12857. /*free(p); - we'll exit soon */
  12858. }
  12859. out:
  12860. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12861. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12862. */
  12863. setjobctl(0);
  12864. flush_stdout_stderr();
  12865. _exit(status);
  12866. /* NOTREACHED */
  12867. }
  12868. /* Don't inline: conserve stack of caller from having our locals too */
  12869. static NOINLINE void
  12870. init(void)
  12871. {
  12872. /* we will never free this */
  12873. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12874. basepf.linno = 1;
  12875. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12876. setsignal(SIGCHLD);
  12877. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12878. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12879. */
  12880. signal(SIGHUP, SIG_DFL);
  12881. {
  12882. char **envp;
  12883. const char *p;
  12884. initvar();
  12885. for (envp = environ; envp && *envp; envp++) {
  12886. /* Used to have
  12887. * p = endofname(*envp);
  12888. * if (p != *envp && *p == '=') {
  12889. * here to weed out badly-named variables, but this breaks
  12890. * scenarios where people do want them passed to children:
  12891. * import os
  12892. * os.environ["test-test"]="test"
  12893. * if os.fork() == 0:
  12894. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12895. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12896. */
  12897. if (strchr(*envp, '=')) {
  12898. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12899. }
  12900. }
  12901. setvareq((char*)defifsvar, VTEXTFIXED);
  12902. setvareq((char*)defoptindvar, VTEXTFIXED);
  12903. setvar0("PPID", utoa(getppid()));
  12904. #if BASH_SHLVL_VAR
  12905. p = lookupvar("SHLVL");
  12906. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12907. #endif
  12908. #if BASH_HOSTNAME_VAR
  12909. if (!lookupvar("HOSTNAME")) {
  12910. struct utsname uts;
  12911. uname(&uts);
  12912. setvar0("HOSTNAME", uts.nodename);
  12913. }
  12914. #endif
  12915. p = lookupvar("PWD");
  12916. if (p) {
  12917. struct stat st1, st2;
  12918. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12919. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12920. ) {
  12921. p = NULL;
  12922. }
  12923. }
  12924. setpwd(p, 0);
  12925. }
  12926. }
  12927. //usage:#define ash_trivial_usage
  12928. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  12929. //usage:#define ash_full_usage "\n\n"
  12930. //usage: "Unix shell interpreter"
  12931. /*
  12932. * Process the shell command line arguments.
  12933. */
  12934. static int
  12935. procargs(char **argv)
  12936. {
  12937. int i;
  12938. const char *xminusc;
  12939. char **xargv;
  12940. int login_sh;
  12941. xargv = argv;
  12942. login_sh = xargv[0] && xargv[0][0] == '-';
  12943. #if NUM_SCRIPTS > 0
  12944. if (minusc)
  12945. goto setarg0;
  12946. #endif
  12947. arg0 = xargv[0];
  12948. /* if (xargv[0]) - mmm, this is always true! */
  12949. xargv++;
  12950. argptr = xargv;
  12951. for (i = 0; i < NOPTS; i++)
  12952. optlist[i] = 2;
  12953. if (options(&login_sh)) {
  12954. /* it already printed err message */
  12955. raise_exception(EXERROR);
  12956. }
  12957. xargv = argptr;
  12958. xminusc = minusc;
  12959. if (*xargv == NULL) {
  12960. if (xminusc)
  12961. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12962. sflag = 1;
  12963. }
  12964. if (iflag == 2 /* no explicit -i given */
  12965. && sflag == 1 /* -s given (or implied) */
  12966. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  12967. && isatty(0) && isatty(1) /* we are on tty */
  12968. ) {
  12969. iflag = 1;
  12970. }
  12971. if (mflag == 2)
  12972. mflag = iflag;
  12973. for (i = 0; i < NOPTS; i++)
  12974. if (optlist[i] == 2)
  12975. optlist[i] = 0;
  12976. #if DEBUG == 2
  12977. debug = 1;
  12978. #endif
  12979. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12980. if (xminusc) {
  12981. minusc = *xargv++;
  12982. if (*xargv)
  12983. goto setarg0;
  12984. } else if (!sflag) {
  12985. setinputfile(*xargv, 0);
  12986. setarg0:
  12987. arg0 = *xargv++;
  12988. commandname = arg0;
  12989. }
  12990. shellparam.p = xargv;
  12991. #if ENABLE_ASH_GETOPTS
  12992. shellparam.optind = 1;
  12993. shellparam.optoff = -1;
  12994. #endif
  12995. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12996. while (*xargv) {
  12997. shellparam.nparam++;
  12998. xargv++;
  12999. }
  13000. optschanged();
  13001. return login_sh;
  13002. }
  13003. /*
  13004. * Read /etc/profile, ~/.profile, $ENV.
  13005. */
  13006. static void
  13007. read_profile(const char *name)
  13008. {
  13009. name = expandstr(name, DQSYNTAX);
  13010. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13011. return;
  13012. cmdloop(0);
  13013. popfile();
  13014. }
  13015. /*
  13016. * This routine is called when an error or an interrupt occurs in an
  13017. * interactive shell and control is returned to the main command loop.
  13018. * (In dash, this function is auto-generated by build machinery).
  13019. */
  13020. static void
  13021. reset(void)
  13022. {
  13023. /* from eval.c: */
  13024. evalskip = 0;
  13025. loopnest = 0;
  13026. /* from expand.c: */
  13027. ifsfree();
  13028. /* from input.c: */
  13029. g_parsefile->left_in_buffer = 0;
  13030. g_parsefile->left_in_line = 0; /* clear input buffer */
  13031. popallfiles();
  13032. /* from redir.c: */
  13033. unwindredir(NULL);
  13034. /* from var.c: */
  13035. unwindlocalvars(NULL);
  13036. }
  13037. #if PROFILE
  13038. static short profile_buf[16384];
  13039. extern int etext();
  13040. #endif
  13041. /*
  13042. * Main routine. We initialize things, parse the arguments, execute
  13043. * profiles if we're a login shell, and then call cmdloop to execute
  13044. * commands. The setjmp call sets up the location to jump to when an
  13045. * exception occurs. When an exception occurs the variable "state"
  13046. * is used to figure out how far we had gotten.
  13047. */
  13048. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13049. #if NUM_SCRIPTS > 0
  13050. int ash_main(int argc, char **argv)
  13051. #else
  13052. int ash_main(int argc UNUSED_PARAM, char **argv)
  13053. #endif
  13054. /* note: 'argc' is used only if embedded scripts are enabled */
  13055. {
  13056. volatile smallint state;
  13057. struct jmploc jmploc;
  13058. struct stackmark smark;
  13059. int login_sh;
  13060. /* Initialize global data */
  13061. INIT_G_misc();
  13062. INIT_G_memstack();
  13063. INIT_G_var();
  13064. #if ENABLE_ASH_ALIAS
  13065. INIT_G_alias();
  13066. #endif
  13067. INIT_G_cmdtable();
  13068. #if PROFILE
  13069. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13070. #endif
  13071. state = 0;
  13072. if (setjmp(jmploc.loc)) {
  13073. smallint e;
  13074. smallint s;
  13075. reset();
  13076. e = exception_type;
  13077. s = state;
  13078. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13079. exitshell();
  13080. }
  13081. if (e == EXINT) {
  13082. newline_and_flush(stderr);
  13083. }
  13084. popstackmark(&smark);
  13085. FORCE_INT_ON; /* enable interrupts */
  13086. if (s == 1)
  13087. goto state1;
  13088. if (s == 2)
  13089. goto state2;
  13090. if (s == 3)
  13091. goto state3;
  13092. goto state4;
  13093. }
  13094. exception_handler = &jmploc;
  13095. rootpid = getpid();
  13096. init();
  13097. setstackmark(&smark);
  13098. #if NUM_SCRIPTS > 0
  13099. if (argc < 0)
  13100. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13101. minusc = get_script_content(-argc - 1);
  13102. #endif
  13103. login_sh = procargs(argv);
  13104. #if DEBUG
  13105. TRACE(("Shell args: "));
  13106. trace_puts_args(argv);
  13107. #endif
  13108. if (login_sh) {
  13109. const char *hp;
  13110. state = 1;
  13111. read_profile("/etc/profile");
  13112. state1:
  13113. state = 2;
  13114. hp = lookupvar("HOME");
  13115. if (hp)
  13116. read_profile("$HOME/.profile");
  13117. }
  13118. state2:
  13119. state = 3;
  13120. if (
  13121. #ifndef linux
  13122. getuid() == geteuid() && getgid() == getegid() &&
  13123. #endif
  13124. iflag
  13125. ) {
  13126. const char *shinit = lookupvar("ENV");
  13127. if (shinit != NULL && *shinit != '\0')
  13128. read_profile(shinit);
  13129. }
  13130. popstackmark(&smark);
  13131. state3:
  13132. state = 4;
  13133. if (minusc) {
  13134. /* evalstring pushes parsefile stack.
  13135. * Ensure we don't falsely claim that 0 (stdin)
  13136. * is one of stacked source fds.
  13137. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13138. // if (!sflag) g_parsefile->pf_fd = -1;
  13139. // ^^ not necessary since now we special-case fd 0
  13140. // in save_fd_on_redirect()
  13141. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13142. // The above makes
  13143. // ash -sc 'echo $-'
  13144. // continue reading input from stdin after running 'echo'.
  13145. // bash does not do this: it prints "hBcs" and exits.
  13146. evalstring(minusc, EV_EXIT);
  13147. }
  13148. if (sflag || minusc == NULL) {
  13149. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13150. if (iflag) {
  13151. const char *hp = lookupvar("HISTFILE");
  13152. if (!hp) {
  13153. hp = lookupvar("HOME");
  13154. if (hp) {
  13155. INT_OFF;
  13156. hp = concat_path_file(hp, ".ash_history");
  13157. setvar0("HISTFILE", hp);
  13158. free((char*)hp);
  13159. INT_ON;
  13160. hp = lookupvar("HISTFILE");
  13161. }
  13162. }
  13163. if (hp)
  13164. line_input_state->hist_file = hp;
  13165. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13166. hp = lookupvar("HISTFILESIZE");
  13167. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13168. # endif
  13169. }
  13170. #endif
  13171. state4: /* XXX ??? - why isn't this before the "if" statement */
  13172. cmdloop(1);
  13173. }
  13174. #if PROFILE
  13175. monitor(0);
  13176. #endif
  13177. #ifdef GPROF
  13178. {
  13179. extern void _mcleanup(void);
  13180. _mcleanup();
  13181. }
  13182. #endif
  13183. TRACE(("End of main reached\n"));
  13184. exitshell();
  13185. /* NOTREACHED */
  13186. }
  13187. /*-
  13188. * Copyright (c) 1989, 1991, 1993, 1994
  13189. * The Regents of the University of California. All rights reserved.
  13190. *
  13191. * This code is derived from software contributed to Berkeley by
  13192. * Kenneth Almquist.
  13193. *
  13194. * Redistribution and use in source and binary forms, with or without
  13195. * modification, are permitted provided that the following conditions
  13196. * are met:
  13197. * 1. Redistributions of source code must retain the above copyright
  13198. * notice, this list of conditions and the following disclaimer.
  13199. * 2. Redistributions in binary form must reproduce the above copyright
  13200. * notice, this list of conditions and the following disclaimer in the
  13201. * documentation and/or other materials provided with the distribution.
  13202. * 3. Neither the name of the University nor the names of its contributors
  13203. * may be used to endorse or promote products derived from this software
  13204. * without specific prior written permission.
  13205. *
  13206. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13207. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13208. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13209. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13210. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13211. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13212. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13213. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13214. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13215. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13216. * SUCH DAMAGE.
  13217. */